Ensure smarty variables are consistently assigned in report
[civicrm-core.git] / CRM / Report / Form.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 * Class CRM_Report_Form
14 */
15 class CRM_Report_Form extends CRM_Core_Form {
16 /**
17 * Variables smarty expects to have set.
18 *
19 * We ensure these are assigned (value = NULL) when Smarty is instantiated in
20 * order to avoid e-notices / having to use empty or isset in the template layer.
21 *
22 * @var string[]
23 */
24 public $expectedSmartyVariables = ['pager', 'skip', 'sections', 'grandStat'];
25
26 /**
27 * Deprecated constant, Reports should be updated to use the getRowCount function.
28 */
29 const ROW_COUNT_LIMIT = 50;
30
31 /**
32 * Operator types - used for displaying filter elements
33 */
34 const
35 OP_INT = 1,
36 OP_STRING = 2,
37 OP_DATE = 4,
38 OP_DATETIME = 5,
39 OP_FLOAT = 8,
40 OP_SELECT = 64,
41 OP_MULTISELECT = 65,
42 OP_MULTISELECT_SEPARATOR = 66,
43 OP_MONTH = 128,
44 OP_ENTITYREF = 256;
45
46 /**
47 * The id of the report instance
48 *
49 * @var int
50 */
51 protected $_id;
52
53 /**
54 * The Number of rows to display on screen
55 * @var int
56 */
57 protected $_rowCount;
58
59 /**
60 * The id of the report template
61 *
62 * @var int
63 */
64 protected $_templateID;
65
66 /**
67 * The report title
68 *
69 * @var string
70 */
71 protected $_title;
72 protected $_noFields = FALSE;
73
74 /**
75 * The set of all columns in the report. An associative array
76 * with column name as the key and attributes as the value
77 *
78 * @var array
79 */
80 protected $_columns = [];
81
82 /**
83 * The set of filters in the report
84 *
85 * @var array
86 */
87 protected $_filters = [];
88
89 /**
90 * The set of optional columns in the report
91 *
92 * @var array
93 */
94 public $_options = [];
95
96 /**
97 * By default most reports hide contact id.
98 * Setting this to true makes it available
99 * @var bool
100 */
101 protected $_exposeContactID = TRUE;
102
103 /**
104 * Set of statistic fields
105 *
106 * @var array
107 */
108 protected $_statFields = [];
109
110 /**
111 * Set of statistics data
112 *
113 * @var array
114 */
115 protected $_statistics = [];
116
117 /**
118 * List of fields not to be repeated during display
119 *
120 * @var array
121 */
122 protected $_noRepeats = [];
123
124 /**
125 * List of fields not to be displayed
126 *
127 * @var array
128 */
129 protected $_noDisplay = [];
130
131 /**
132 * Object type that a custom group extends
133 *
134 * @var null
135 */
136 protected $_customGroupExtends = NULL;
137 protected $_customGroupExtendsJoin = [];
138 protected $_customGroupFilters = TRUE;
139 protected $_customGroupGroupBy = FALSE;
140 protected $_customGroupJoin = 'LEFT JOIN';
141
142 /**
143 * Build tags filter
144 * @var bool
145 */
146 protected $_tagFilter = FALSE;
147
148 /**
149 * specify entity table for tags filter
150 * @var string
151 */
152 protected $_tagFilterTable = 'civicrm_contact';
153
154 /**
155 * Build groups filter.
156 *
157 * @var bool
158 */
159 protected $_groupFilter = FALSE;
160
161 /**
162 * Has the report been optimised for group filtering.
163 *
164 * The functionality for group filtering has been improved but not
165 * all reports have been adjusted to take care of it.
166 *
167 * This property exists to highlight the reports which are still using the
168 * slow method & allow group filtering to still work for them until they
169 * can be migrated.
170 *
171 * In order to protect extensions we have to default to TRUE - but I have
172 * separately marked every class with a groupFilter in the hope that will trigger
173 * people to fix them as they touch them.
174 *
175 * @var bool
176 * @see https://issues.civicrm.org/jira/browse/CRM-19170
177 */
178 protected $groupFilterNotOptimised = TRUE;
179
180 /**
181 * Navigation fields
182 *
183 * @var array
184 */
185 public $_navigation = [];
186
187 public $_drilldownReport = [];
188
189 /**
190 * Array of tabs to display on report.
191 *
192 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
193 *
194 * $this->tabs['OrderBy'] = array(
195 * 'title' => ts('Sorting'),
196 * 'tpl' => 'OrderBy',
197 * 'div_label' => 'order-by',
198 * );
199 *
200 * @var array
201 */
202 protected $tabs = [];
203
204 /**
205 * Should we add paging.
206 *
207 * @var bool
208 */
209 protected $addPaging = TRUE;
210
211 protected $isForceGroupBy = FALSE;
212
213 protected $groupConcatTested = FALSE;
214
215 /**
216 * Are we in print mode. Can be set by another outputMode, ex: sendmail.
217 *
218 * @var bool
219 */
220 public $printOnly = FALSE;
221
222 /**
223 * An attribute for checkbox/radio form field layout
224 *
225 * @var array
226 */
227 protected $_fourColumnAttribute = [
228 '</td><td width="25%">',
229 '</td><td width="25%">',
230 '</td><td width="25%">',
231 '</tr><tr><td>',
232 ];
233
234 protected $_force = 1;
235
236 protected $_params = NULL;
237 protected $_formValues = NULL;
238 protected $_instanceValues = NULL;
239
240 protected $_instanceForm = FALSE;
241 protected $_criteriaForm = FALSE;
242
243 protected $_instanceButtonName = NULL;
244 protected $_createNewButtonName = NULL;
245 protected $_groupButtonName = NULL;
246 protected $_chartButtonName = NULL;
247 protected $_csvSupported = TRUE;
248 protected $_add2groupSupported = TRUE;
249 protected $_groups = NULL;
250 protected $_grandFlag = FALSE;
251 protected $_rowsFound = NULL;
252 protected $_selectAliases = [];
253 protected $_rollup = NULL;
254
255 /**
256 * Table containing list of contact IDs within the group filter.
257 *
258 * @var string
259 */
260 protected $groupTempTable = '';
261
262 /**
263 * @var array
264 */
265 protected $_aliases = [];
266
267 /**
268 * @var string
269 */
270 protected $_where;
271
272 /**
273 * @var string
274 */
275 protected $_from;
276
277 /**
278 * SQL Limit clause
279 * @var string
280 */
281 protected $_limit = NULL;
282
283 /**
284 * This can be set to specify a limit to the number of rows
285 * Since it is currently envisaged as part of the api usage it is only being applied
286 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
287 * of the code (see limit() fn.
288 *
289 * @var int
290 */
291 protected $_limitValue = NULL;
292
293 /**
294 * This can be set to specify row offset
295 * See notes on _limitValue
296 *
297 * @var int
298 */
299 protected $_offsetValue = NULL;
300 /**
301 * @var null
302 */
303 protected $_sections = NULL;
304 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
305
306 /**
307 * Whether to generate absolute URLs (ex: in report emails).
308 *
309 * @var bool
310 */
311 public $_absoluteUrl = FALSE;
312
313 /**
314 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
315 *
316 * @var bool
317 */
318 protected $_storeResultSet = FALSE;
319
320 /**
321 * When _storeResultSet Flag is set use this var to store result set in form of array
322 *
323 * @var bool
324 */
325 protected $_resultSet = [];
326
327 /**
328 * To what frequency group-by a date column
329 *
330 * @var array
331 */
332 protected $_groupByDateFreq = [
333 'MONTH' => 'Month',
334 'YEARWEEK' => 'Week',
335 'QUARTER' => 'Quarter',
336 'YEAR' => 'Year',
337 ];
338
339 /**
340 * Variables to hold the acl inner join and where clause
341 * @var string|null
342 */
343 protected $_aclFrom = NULL;
344 protected $_aclWhere = NULL;
345
346 /**
347 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
348 *
349 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
350 *
351 * @var array
352 */
353 protected $_selectedTables = [];
354
355 /**
356 * Array of DAO tables having columns included in WHERE or HAVING clause
357 *
358 * @var array
359 */
360 protected $filteredTables;
361
362 /**
363 * Output mode e.g 'print', 'csv', 'pdf'.
364 *
365 * @var string
366 */
367 protected $_outputMode;
368
369 /**
370 * Format of any chart in use.
371 *
372 * (it's unclear if this could be merged with outputMode at this stage)
373 *
374 * @var string|null
375 */
376 protected $_format;
377
378 public $_having = NULL;
379 public $_select = NULL;
380 public $_selectClauses = [];
381 public $_columnHeaders = [];
382 public $_orderBy = NULL;
383 public $_orderByFields = [];
384 public $_orderByArray = [];
385 /**
386 * Array of clauses to group by.
387 *
388 * @var array
389 */
390 protected $_groupByArray = [];
391 public $_groupBy = NULL;
392 public $_whereClauses = [];
393 public $_havingClauses = [];
394
395 /**
396 * DashBoardRowCount Dashboard row count.
397 *
398 * @var int
399 */
400 public $_dashBoardRowCount;
401
402 /**
403 * Is this being called without a form controller (ie. the report is being render outside the normal form
404 * - e.g the api is retrieving the rows.
405 *
406 * @var bool
407 */
408 public $noController = FALSE;
409
410 /**
411 * Variable to hold the currency alias.
412 *
413 * @var string|null
414 */
415 protected $_currencyColumn = NULL;
416
417 /**
418 * @var string
419 */
420 protected $_interval;
421
422 /**
423 * @var bool
424 */
425 protected $_sendmail;
426
427 /**
428 * @var int
429 */
430 protected $_chartId;
431
432 /**
433 * @var int
434 */
435 public $_section;
436
437 /**
438 * Report description.
439 *
440 * @var string
441 */
442 public $_description;
443
444 /**
445 * Is an address field selected.
446 *
447 * @var bool
448 * This was intended to determine if the address table should be joined in
449 * The isTableSelected function is now preferred for this purpose
450 */
451 protected $_addressField;
452
453 /**
454 * Is an email field selected.
455 *
456 * @var bool
457 * This was intended to determine if the email table should be joined in
458 * The isTableSelected function is now preferred for this purpose
459 */
460 protected $_emailField;
461
462 /**
463 * Is a phone field selected.
464 *
465 * @var bool
466 * This was intended to determine if the phone table should be joined in
467 * The isTableSelected function is now preferred for this purpose
468 */
469 protected $_phoneField;
470
471 /**
472 * Create new report instance? (or update existing) on save.
473 *
474 * @var bool
475 */
476 protected $_createNew;
477
478 /**
479 * When a grand total row has calculated the status we pop it off to here.
480 *
481 * This allows us to access it from the stats function and avoid recalculating.
482 *
483 * @var array
484 */
485 protected $rollupRow = [];
486
487 /**
488 * Database attributes - character set and collation.
489 *
490 * @var string
491 */
492 protected $_databaseAttributes = ' DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
493
494 /**
495 * SQL being run in this report.
496 *
497 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
498 *
499 * @var string
500 */
501
502 protected $sql;
503
504 /**
505 * An instruction not to add a Group By.
506 *
507 * This is relevant where the group by might be otherwise added after the code that determines the group by array.
508 *
509 * e.g. where stat fields are being added but other settings cause it to not be desirable to add a group by
510 * such as in pivot charts when no row header is set
511 *
512 * @var bool
513 */
514 protected $noGroupBy = FALSE;
515
516 /**
517 * SQL being run in this report as an array.
518 *
519 * The sql in the report is stored in this variable in order to be returned to api & test calls.
520 *
521 * @var string
522 */
523
524 protected $sqlArray;
525
526 /**
527 * Tables created for the report that need removal afterwards.
528 *
529 * ['civicrm_temp_report_x' => ['temporary' => TRUE, 'name' => 'civicrm_temp_report_x']
530 * @var array
531 */
532 protected $temporaryTables = [];
533
534 /**
535 * Can this report use the sql mode ONLY_FULL_GROUP_BY.
536 * @var bool
537 */
538 public $optimisedForOnlyFullGroupBy = TRUE;
539
540 /**
541 * Get the number of rows to show
542 * @return int
543 */
544 public function getRowCount(): int {
545 return $this->_rowCount;
546 }
547
548 /**
549 * set the number of rows to show
550 * @param $rowCount int
551 */
552 public function setRowCount($rowCount): void {
553 $this->_rowCount = $rowCount;
554 }
555
556 /**
557 * Class constructor.
558 */
559 public function __construct() {
560 parent::__construct();
561
562 $this->setRowCount(\Civi::settings()->get('default_pager_size'));
563
564 $this->addClass('crm-report-form');
565
566 if ($this->_tagFilter) {
567 $this->buildTagFilter();
568 }
569 if ($this->_exposeContactID) {
570 if (array_key_exists('civicrm_contact', $this->_columns)) {
571 $this->_columns['civicrm_contact']['fields']['exposed_id'] = [
572 'name' => 'id',
573 'title' => ts('Contact ID'),
574 'no_repeat' => TRUE,
575 ];
576 }
577 }
578
579 if ($this->_groupFilter) {
580 $this->buildGroupFilter();
581 }
582
583 // Get all custom groups
584 $allGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id');
585
586 // Get the custom groupIds for which the user has VIEW permission
587 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
588 // and addCustomDataToColumns() will allow access to all custom groups.
589 $permCustomGroupIds = [];
590 if (!CRM_Core_Permission::check('access all custom data')) {
591 $permCustomGroupIds = CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_custom_group', $allGroups, NULL);
592 // do not allow custom data for reports if user doesn't have
593 // permission to access custom data.
594 if (!empty($this->_customGroupExtends) && empty($permCustomGroupIds)) {
595 $this->_customGroupExtends = [];
596 }
597 }
598
599 // merge custom data columns to _columns list, if any
600 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
601
602 // add / modify display columns, filters ..etc
603 CRM_Utils_Hook::alterReportVar('columns', $this->_columns, $this);
604
605 //assign currencyColumn variable to tpl
606 $this->assign('currencyColumn', $this->_currencyColumn);
607 }
608
609 /**
610 * Shared pre-process function.
611 *
612 * If overriding preProcess function this should still be called.
613 *
614 * @throws \Exception
615 */
616 public function preProcessCommon() {
617 $this->_force = CRM_Utils_Request::retrieve('force', 'Boolean');
618 // Ensure smarty variables are assigned here since this function is called from
619 // the report api and the main buildForm is not.
620 self::$_template->ensureVariablesAreAssigned($this->expectedSmartyVariables);
621 $this->_dashBoardRowCount = CRM_Utils_Request::retrieve('rowCount', 'Integer');
622
623 $this->_section = CRM_Utils_Request::retrieve('section', 'Integer');
624
625 $this->assign('section', $this->_section);
626 CRM_Core_Region::instance('page-header')->add([
627 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
628 ]);
629 if (!$this->noController) {
630 $this->setID($this->get('instanceId'));
631
632 if (!$this->_id) {
633 $this->setID(CRM_Report_Utils_Report::getInstanceID());
634 if (!$this->_id) {
635 $this->setID(CRM_Report_Utils_Report::getInstanceIDForPath());
636 }
637 }
638
639 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
640 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
641 if (!isset($_SERVER['QUERY_STRING'])) {
642 // in php 7.4 can do this with less lines with ??=
643 $_SERVER['QUERY_STRING'] = '';
644 }
645 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
646 }
647
648 if ($this->_id) {
649 $this->assign('instanceId', $this->_id);
650 $params = ['id' => $this->_id];
651 $this->_instanceValues = [];
652 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
653 $params,
654 $this->_instanceValues
655 );
656 if (empty($this->_instanceValues)) {
657 CRM_Core_Error::statusBounce("Report could not be loaded.");
658 }
659 $this->_title = $this->_instanceValues['title'];
660 if (!empty($this->_instanceValues['permission']) &&
661 (!(CRM_Core_Permission::check($this->_instanceValues['permission']) ||
662 CRM_Core_Permission::check('administer Reports')
663 ))
664 ) {
665 CRM_Utils_System::permissionDenied();
666 CRM_Utils_System::civiExit();
667 }
668
669 $formValues = $this->_instanceValues['form_values'] ?? NULL;
670 if ($formValues) {
671 $this->_formValues = CRM_Utils_String::unserialize($formValues);
672 }
673 else {
674 $this->_formValues = NULL;
675 }
676
677 $this->setOutputMode();
678
679 if ($this->_outputMode == 'copy') {
680 $this->_createNew = TRUE;
681 $this->_params = $this->_formValues;
682 $this->_params['view_mode'] = 'criteria';
683 $this->_params['title'] = $this->getTitle() . ts(' (copy created by %1 on %2)', [
684 CRM_Core_Session::singleton()->getLoggedInContactDisplayName(),
685 CRM_Utils_Date::customFormat(date('Y-m-d H:i')),
686 ]);
687 // Do not pass go. Do not collect another chance to re-run the same query.
688 CRM_Report_Form_Instance::postProcess($this);
689 }
690
691 // lets always do a force if reset is found in the url.
692 // Hey why not? see CRM-17225 for more about this. The use of reset to be force is historical for reasons stated
693 // in the comment line above these 2.
694 if (!empty($_REQUEST['reset'])
695 && !in_array(CRM_Utils_Request::retrieve('output', 'String'), ['save', 'criteria'])) {
696 $this->_force = 1;
697 }
698
699 // set the mode
700 $this->assign('mode', 'instance');
701 }
702 elseif (!$this->noController) {
703 [$optionValueID, $optionValue] = CRM_Report_Utils_Report::getValueIDFromUrl();
704 $instanceCount = CRM_Report_Utils_Report::getInstanceCount($optionValue);
705 if (($instanceCount > 0) && $optionValueID) {
706 $this->assign('instanceUrl',
707 CRM_Utils_System::url('civicrm/report/list',
708 "reset=1&ovid=$optionValueID"
709 )
710 );
711 }
712 if ($optionValueID) {
713 $this->_description = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
714 }
715
716 // set the mode
717 $this->assign('mode', 'template');
718 }
719
720 // lets display the Report Settings section
721 $this->_instanceForm = $this->_force || $this->_id || (!empty($_POST));
722
723 // Do not display Report Settings section if administer Reports permission is absent OR
724 // if report instance is reserved and administer reserved reports absent
725 if (!CRM_Core_Permission::check('administer Reports') ||
726 (!empty($this->_instanceValues['is_reserved']) &&
727 !CRM_Core_Permission::check('administer reserved reports'))
728 ) {
729 $this->_instanceForm = FALSE;
730 }
731
732 $this->assign('criteriaForm', FALSE);
733 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
734 if (CRM_Core_Permission::check('administer Reports') ||
735 CRM_Core_Permission::check('access Report Criteria')
736 ) {
737 if (empty($this->_instanceValues['is_reserved']) ||
738 CRM_Core_Permission::check('administer reserved reports')
739 ) {
740 $this->assign('criteriaForm', TRUE);
741 $this->_criteriaForm = TRUE;
742 }
743 }
744
745 // Special permissions check for private instance if it's not the current contact instance
746 if ($this->_id &&
747 (CRM_Report_BAO_ReportInstance::reportIsPrivate($this->_id) &&
748 !CRM_Report_BAO_ReportInstance::contactIsOwner($this->_id))) {
749 if (!CRM_Core_Permission::check('access all private reports')) {
750 $this->_instanceForm = FALSE;
751 $this->assign('criteriaForm', FALSE);
752 }
753 }
754
755 $this->_instanceButtonName = $this->getButtonName('submit', 'save');
756 $this->_createNewButtonName = $this->getButtonName('submit', 'next');
757 $this->_groupButtonName = $this->getButtonName('submit', 'group');
758 $this->_chartButtonName = $this->getButtonName('submit', 'chart');
759 }
760
761 /**
762 * Add bread crumb.
763 */
764 public function addBreadCrumb() {
765 $breadCrumbs
766 = [
767 [
768 'title' => ts('Report Templates'),
769 'url' => CRM_Utils_System::url('civicrm/admin/report/template/list', 'reset=1'),
770 ],
771 ];
772
773 CRM_Utils_System::appendBreadCrumb($breadCrumbs);
774 }
775
776 /**
777 * Pre process function.
778 *
779 * Called prior to build form.
780 */
781 public function preProcess() {
782 $this->preProcessCommon();
783
784 if (!$this->_id) {
785 $this->addBreadCrumb();
786 }
787
788 foreach ($this->_columns as $tableName => $table) {
789 $this->setTableAlias($table, $tableName);
790
791 $expFields = [];
792 // higher preference to bao object
793 $daoOrBaoName = CRM_Utils_Array::value('bao', $table, CRM_Utils_Array::value('dao', $table));
794
795 if ($daoOrBaoName) {
796 if (method_exists($daoOrBaoName, 'exportableFields')) {
797 $expFields = $daoOrBaoName::exportableFields();
798 }
799 else {
800 $expFields = $daoOrBaoName::export();
801 }
802 }
803
804 $doNotCopy = ['required', 'default'];
805
806 $fieldGroups = ['fields', 'filters', 'group_bys', 'order_bys'];
807 foreach ($fieldGroups as $fieldGrp) {
808 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
809 foreach ($table[$fieldGrp] as $fieldName => $field) {
810 // $name is the field name used to reference the BAO/DAO export fields array
811 $name = $field['name'] ?? $fieldName;
812
813 // Sometimes the field name key in the BAO/DAO export fields array is
814 // different from the actual database field name.
815 // Unset $field['name'] so that actual database field name can be obtained
816 // from the BAO/DAO export fields array.
817 unset($field['name']);
818
819 if (array_key_exists($name, $expFields)) {
820 foreach ($doNotCopy as $dnc) {
821 // unset the values we don't want to be copied.
822 unset($expFields[$name][$dnc]);
823 }
824 if (empty($field)) {
825 $this->_columns[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
826 }
827 else {
828 foreach ($expFields[$name] as $property => $val) {
829 if (!array_key_exists($property, $field)) {
830 $this->_columns[$tableName][$fieldGrp][$fieldName][$property] = $val;
831 }
832 }
833 }
834 }
835
836 // fill other vars
837 if (!empty($field['no_repeat'])) {
838 $this->_noRepeats[] = "{$tableName}_{$fieldName}";
839 }
840 if (!empty($field['no_display'])) {
841 $this->_noDisplay[] = "{$tableName}_{$fieldName}";
842 }
843
844 // set alias = table-name, unless already set
845 $alias = $field['alias'] ?? (
846 $this->_columns[$tableName]['alias'] ?? $tableName
847 );
848 $this->_columns[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
849
850 // set name = fieldName, unless already set
851 if (!isset($this->_columns[$tableName][$fieldGrp][$fieldName]['name'])) {
852 $this->_columns[$tableName][$fieldGrp][$fieldName]['name'] = $name;
853 }
854
855 if (!isset($this->_columns[$tableName][$fieldGrp][$fieldName]['table_name'])) {
856 $this->_columns[$tableName][$fieldGrp][$fieldName]['table_name'] = $tableName;
857 }
858
859 // set dbAlias = alias.name, unless already set
860 if (!isset($this->_columns[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
861 $this->_columns[$tableName][$fieldGrp][$fieldName]['dbAlias']
862 = $alias . '.' .
863 $this->_columns[$tableName][$fieldGrp][$fieldName]['name'];
864 }
865
866 // a few auto fills for filters
867 if ($fieldGrp == 'filters') {
868 // fill operator types
869 if (!array_key_exists('operatorType', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
870 switch (CRM_Utils_Array::value('type', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
871 case CRM_Utils_Type::T_MONEY:
872 case CRM_Utils_Type::T_FLOAT:
873 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
874 break;
875
876 case CRM_Utils_Type::T_INT:
877 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_INT;
878 break;
879
880 case CRM_Utils_Type::T_DATE:
881 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE;
882 break;
883
884 case CRM_Utils_Type::T_BOOLEAN:
885 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT;
886 if (!array_key_exists('options', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
887 $this->_columns[$tableName][$fieldGrp][$fieldName]['options']
888 = [
889 '' => ts('Any'),
890 '0' => ts('No'),
891 '1' => ts('Yes'),
892 ];
893 }
894 break;
895
896 default:
897 if ($daoOrBaoName &&
898 array_key_exists('pseudoconstant', $this->_columns[$tableName][$fieldGrp][$fieldName])
899 ) {
900 // with multiple options operator-type is generally multi-select
901 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
902 if (!array_key_exists('options', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
903 // fill options
904 $this->_columns[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant::get($daoOrBaoName, $fieldName);
905 }
906 }
907 break;
908 }
909 }
910 }
911 if (!isset($this->_columns[$tableName]['metadata'][$fieldName])) {
912 $this->_columns[$tableName]['metadata'][$fieldName] = $this->_columns[$tableName][$fieldGrp][$fieldName];
913 }
914 else {
915 $this->_columns[$tableName]['metadata'][$fieldName] = array_merge($this->_columns[$tableName][$fieldGrp][$fieldName], $this->_columns[$tableName]['metadata'][$fieldName]);
916 }
917 }
918 }
919 }
920
921 // copy filters to a separate handy variable
922 if (array_key_exists('filters', $table)) {
923 $this->_filters[$tableName] = $this->_columns[$tableName]['filters'];
924 }
925
926 if (array_key_exists('group_bys', $table)) {
927 $groupBys[$tableName] = $this->_columns[$tableName]['group_bys'];
928 }
929
930 if (array_key_exists('fields', $table)) {
931 $reportFields[$tableName] = $this->_columns[$tableName]['fields'];
932 }
933 }
934
935 if ($this->_force) {
936 $this->setDefaultValues(FALSE);
937 }
938
939 CRM_Report_Utils_Get::processFilter($this->_filters, $this->_defaults);
940 CRM_Report_Utils_Get::processGroupBy($groupBys, $this->_defaults);
941 CRM_Report_Utils_Get::processFields($reportFields, $this->_defaults);
942 CRM_Report_Utils_Get::processChart($this->_defaults);
943
944 if ($this->_force) {
945 $this->_formValues = $this->_defaults;
946 $this->postProcess();
947 }
948 }
949
950 /**
951 * Set default values.
952 *
953 * @param bool $freeze
954 *
955 * @return array
956 */
957 public function setDefaultValues($freeze = TRUE) {
958 $freezeGroup = [];
959
960 // FIXME: generalizing form field naming conventions would reduce
961 // Lots of lines below.
962 foreach ($this->_columns as $tableName => $table) {
963 if (array_key_exists('fields', $table)) {
964 foreach ($table['fields'] as $fieldName => $field) {
965 if (empty($field['no_display'])) {
966 if (!empty($field['required'])) {
967 // set default
968 $this->_defaults['fields'][$fieldName] = 1;
969
970 if ($freeze) {
971 // find element object, so that we could use quickform's freeze method
972 // for required elements
973 $obj = $this->getElementFromGroup("fields", $fieldName);
974 if ($obj) {
975 $freezeGroup[] = $obj;
976 }
977 }
978 }
979 elseif (isset($field['default'])) {
980 $this->_defaults['fields'][$fieldName] = $field['default'];
981 }
982 }
983 }
984 }
985
986 if (array_key_exists('group_bys', $table)) {
987 foreach ($table['group_bys'] as $fieldName => $field) {
988 if (isset($field['default'])) {
989 if (!empty($field['frequency'])) {
990 $this->_defaults['group_bys_freq'][$fieldName] = 'MONTH';
991 }
992 $this->_defaults['group_bys'][$fieldName] = $field['default'];
993 }
994 }
995 }
996 if (array_key_exists('filters', $table)) {
997 foreach ($table['filters'] as $fieldName => $field) {
998 if (isset($field['default'])) {
999 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE
1000 ) {
1001 if (is_array($field['default'])) {
1002 $this->_defaults["{$fieldName}_from"] = $field['default']['from'] ?? NULL;
1003 $this->_defaults["{$fieldName}_to"] = $field['default']['to'] ?? NULL;
1004 $this->_defaults["{$fieldName}_relative"] = 0;
1005 }
1006 else {
1007 $this->_defaults["{$fieldName}_relative"] = $field['default'];
1008 }
1009 }
1010 else {
1011 if ((CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_INT) && is_array($field['default'])) {
1012 $this->_defaults["{$fieldName}_min"] = $field['default']['min'] ?? NULL;
1013 $this->_defaults["{$fieldName}_max"] = $field['default']['max'] ?? NULL;
1014 }
1015 $this->_defaults["{$fieldName}_value"] = $field['default'];
1016 }
1017 }
1018 //assign default value as "in" for multiselect
1019 //operator, To freeze the select element
1020 if (CRM_Utils_Array::value('operatorType', $field) ==
1021 CRM_Report_Form::OP_MULTISELECT
1022 ) {
1023 $this->_defaults["{$fieldName}_op"] = 'in';
1024 }
1025 if (CRM_Utils_Array::value('operatorType', $field) ==
1026 CRM_Report_Form::OP_ENTITYREF
1027 ) {
1028 $this->_defaults["{$fieldName}_op"] = 'in';
1029 }
1030 elseif (CRM_Utils_Array::value('operatorType', $field) ==
1031 CRM_Report_Form::OP_MULTISELECT_SEPARATOR
1032 ) {
1033 $this->_defaults["{$fieldName}_op"] = 'mhas';
1034 }
1035 elseif ($op = CRM_Utils_Array::value('default_op', $field)) {
1036 $this->_defaults["{$fieldName}_op"] = $op;
1037 }
1038 }
1039 }
1040
1041 if (
1042 empty($this->_formValues['order_bys']) &&
1043 (array_key_exists('order_bys', $table) &&
1044 is_array($table['order_bys']))
1045 ) {
1046 if (!array_key_exists('order_bys', $this->_defaults)) {
1047 $this->_defaults['order_bys'] = [];
1048 }
1049 foreach ($table['order_bys'] as $fieldName => $field) {
1050 if (!empty($field['default']) || !empty($field['default_order']) ||
1051 CRM_Utils_Array::value('default_is_section', $field) ||
1052 !empty($field['default_weight'])
1053 ) {
1054 $order_by = [
1055 'column' => $fieldName,
1056 'order' => CRM_Utils_Array::value('default_order', $field, 'ASC'),
1057 'section' => CRM_Utils_Array::value('default_is_section', $field, 0),
1058 ];
1059
1060 if (!empty($field['default_weight'])) {
1061 $this->_defaults['order_bys'][(int) $field['default_weight']] = $order_by;
1062 }
1063 else {
1064 array_unshift($this->_defaults['order_bys'], $order_by);
1065 }
1066 }
1067 }
1068 }
1069
1070 foreach ($this->_options as $fieldName => $field) {
1071 if (isset($field['default'])) {
1072 $this->_defaults['options'][$fieldName] = $field['default'];
1073 }
1074 }
1075 }
1076
1077 if (!empty($this->_submitValues)) {
1078 $this->preProcessOrderBy($this->_submitValues);
1079 }
1080 else {
1081 $this->preProcessOrderBy($this->_defaults);
1082 }
1083
1084 // lets finish freezing task here itself
1085 if (!empty($freezeGroup)) {
1086 foreach ($freezeGroup as $elem) {
1087 $elem->freeze();
1088 }
1089 }
1090
1091 if ($this->_formValues) {
1092 $this->_defaults = array_merge($this->_defaults, $this->_formValues);
1093 }
1094
1095 if ($this->_instanceValues) {
1096 $this->_defaults = array_merge($this->_defaults, $this->_instanceValues);
1097 }
1098
1099 CRM_Report_Form_Instance::setDefaultValues($this, $this->_defaults);
1100
1101 return $this->_defaults;
1102 }
1103
1104 /**
1105 * Get element from group.
1106 *
1107 * @param string $group
1108 * @param string $grpFieldName
1109 *
1110 * @return bool
1111 */
1112 public function getElementFromGroup($group, $grpFieldName) {
1113 $eleObj = $this->getElement($group);
1114 foreach ($eleObj->_elements as $index => $obj) {
1115 if ($grpFieldName == $obj->_attributes['name']) {
1116 return $obj;
1117 }
1118 }
1119 return FALSE;
1120 }
1121
1122 /**
1123 * Setter for $_params.
1124 *
1125 * @param array $params
1126 */
1127 public function setParams($params) {
1128 $this->_params = $params;
1129 }
1130
1131 /**
1132 * Getter for $_params.
1133 *
1134 * @return void|array $params
1135 */
1136 public function getParams() {
1137 return $this->_params;
1138 }
1139
1140 /**
1141 * Setter for $_id.
1142 *
1143 * @param int $instanceID
1144 */
1145 public function setID($instanceID) {
1146 $this->_id = $instanceID;
1147 }
1148
1149 /**
1150 * Getter for $_id.
1151 *
1152 * @return int
1153 */
1154 public function getID() {
1155 return $this->_id;
1156 }
1157
1158 /**
1159 * Getter for _outputMode
1160 *
1161 * Note you can implement hook_civicrm_alterReportVar('actions', ...)
1162 * which indirectly allows setting _outputMode if the user chooses
1163 * your action.
1164 *
1165 * @return string
1166 */
1167 public function getOutputMode():string {
1168 return $this->_outputMode;
1169 }
1170
1171 /**
1172 * Getter for report header form field value
1173 *
1174 * @return string
1175 */
1176 public function getReportHeader():string {
1177 return $this->_formValues['report_header'] ?? '';
1178 }
1179
1180 /**
1181 * Getter for report footer form field value
1182 *
1183 * @return string
1184 */
1185 public function getReportFooter():string {
1186 return $this->_formValues['report_footer'] ?? '';
1187 }
1188
1189 /**
1190 * Setter for $_force.
1191 *
1192 * @param bool $isForce
1193 */
1194 public function setForce($isForce) {
1195 $this->_force = $isForce;
1196 }
1197
1198 /**
1199 * Setter for $_limitValue.
1200 *
1201 * @param int $_limitValue
1202 */
1203 public function setLimitValue($_limitValue) {
1204 $this->_limitValue = $_limitValue;
1205 }
1206
1207 /**
1208 * Setter for $_offsetValue.
1209 *
1210 * @param int $_offsetValue
1211 */
1212 public function setOffsetValue($_offsetValue) {
1213 $this->_offsetValue = $_offsetValue;
1214 }
1215
1216 /**
1217 * Setter for $addPaging.
1218 *
1219 * @param bool $value
1220 */
1221 public function setAddPaging($value) {
1222 $this->addPaging = $value;
1223 }
1224
1225 /**
1226 * Getter for $_defaultValues.
1227 *
1228 * @return array
1229 */
1230 public function getDefaultValues() {
1231 return $this->_defaults;
1232 }
1233
1234 /**
1235 * Remove any temporary tables.
1236 */
1237 public function cleanUpTemporaryTables() {
1238 foreach ($this->temporaryTables as $temporaryTable) {
1239 CRM_Core_DAO::executeQuery('DROP ' . ($temporaryTable['temporary'] ? 'TEMPORARY' : '') . ' TABLE IF EXISTS ' . $temporaryTable['name']);
1240 }
1241 }
1242
1243 /**
1244 * Create a temporary table.
1245 *
1246 * This function creates a table AND adds the details to the developer tab & $this->>temporary tables.
1247 *
1248 * @param string $identifier
1249 * This is the key that will be used for the table in the temporaryTables property.
1250 * @param string $sql
1251 * Sql select statement or column description (the latter requires the columns flag)
1252 * @param bool $isColumns
1253 * Is the sql describing columns to create (rather than using a select query).
1254 * @param bool $isMemory
1255 * Create a memory table rather than a normal INNODB table.
1256 *
1257 * @return string
1258 */
1259 public function createTemporaryTable($identifier, $sql, $isColumns = FALSE, $isMemory = FALSE) {
1260 $tempTable = CRM_Utils_SQL_TempTable::build();
1261 if ($isMemory) {
1262 $tempTable->setMemory();
1263 }
1264 if ($isColumns) {
1265 $tempTable->createWithColumns($sql);
1266 }
1267 else {
1268 $tempTable->createWithQuery($sql);
1269 }
1270 $name = $tempTable->getName();
1271 // Developers may force tables to be durable to assist in debugging so lets check.
1272 $isNotTrueTemporary = $tempTable->isDurable();
1273 $this->addToDeveloperTab($tempTable->getCreateSql());
1274 $this->temporaryTables[$identifier] = ['temporary' => !$isNotTrueTemporary, 'name' => $name];
1275 return $name;
1276 }
1277
1278 /**
1279 * Add columns to report.
1280 */
1281 public function addColumns() {
1282 $options = [];
1283 $colGroups = NULL;
1284 foreach ($this->_columns as $tableName => $table) {
1285 if (array_key_exists('fields', $table)) {
1286 foreach ($table['fields'] as $fieldName => $field) {
1287 $groupTitle = '';
1288 if (empty($field['no_display'])) {
1289 foreach (['table', 'field'] as $var) {
1290 if (!empty(${$var}['grouping'])) {
1291 if (!is_array(${$var}['grouping'])) {
1292 $tableName = ${$var}['grouping'];
1293 }
1294 else {
1295 $tableName = array_keys(${$var}['grouping']);
1296 $tableName = $tableName[0];
1297 $groupTitle = array_values(${$var}['grouping']);
1298 $groupTitle = $groupTitle[0];
1299 }
1300 }
1301 }
1302
1303 if (!$groupTitle && isset($table['group_title'])) {
1304 $groupTitle = $table['group_title'];
1305 // Having a group_title is secret code for being a custom group
1306 // which cryptically translates to needing an accordion.
1307 // here we make that explicit.
1308 $colGroups[$tableName]['use_accordian_for_field_selection'] = TRUE;
1309 }
1310
1311 $colGroups[$tableName]['fields'][$fieldName] = $field['title'] ?? NULL;
1312 if ($groupTitle && empty($colGroups[$tableName]['group_title'])) {
1313 $colGroups[$tableName]['group_title'] = $groupTitle;
1314 }
1315 $options[$fieldName] = $field['title'] ?? NULL;
1316 }
1317 }
1318 }
1319 }
1320
1321 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
1322 NULL, NULL, NULL, $this->_fourColumnAttribute, TRUE
1323 );
1324 if (!empty($colGroups)) {
1325 $this->tabs['FieldSelection'] = [
1326 'title' => ts('Columns'),
1327 'tpl' => 'FieldSelection',
1328 'div_label' => 'col-groups',
1329 ];
1330
1331 // Note this assignment is only really required in buildForm. It is being 'over-called'
1332 // to reduce risk of being missed due to overridden functions.
1333 $this->assign('tabs', $this->tabs);
1334 }
1335
1336 $this->assign('colGroups', $colGroups);
1337 }
1338
1339 /**
1340 * Add filters to report.
1341 */
1342 public function addFilters() {
1343 $filters = $filterGroups = [];
1344
1345 foreach ($this->_filters as $table => $attributes) {
1346 $groupingKey = $this->_columns[$table]['grouping'] ?? '';
1347 $filterGroups[$groupingKey]['tables'][$table] = [];
1348 // If a prior table hasn't set group title then set it.
1349 if (empty($filterGroups[$groupingKey]['group_title'])) {
1350 $filterGroups[$groupingKey]['group_title'] = $this->_columns[$table]['group_title'] ?? '';
1351 }
1352 // The presence of 'group_title' is secret code for 'display in an accordion'
1353 // here we make this explicit.
1354 if (!isset($filterGroups[$groupingKey]['use_accordion_for_field_selection'])) {
1355 if (isset($this->_columns[$table]['use_accordion_for_field_selection'])) {
1356 $filterGroups[$groupingKey]['use_accordion_for_field_selection'] = $this->_columns[$table]['use_accordion_for_field_selection'];
1357 }
1358 else {
1359 $filterGroups[$groupingKey]['use_accordion_for_field_selection'] = isset($this->_columns[$table]['group_title']);
1360 }
1361 }
1362
1363 foreach ($attributes as $fieldName => $field) {
1364 $filterGroups[$groupingKey]['tables'][$table][$fieldName] = $field;
1365 // Filters is deprecated in favour of filterGroups.
1366 $filters[$table][$fieldName] = $field;
1367 // get ready with option value pair
1368 // @ 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
1369 // would be useful
1370 $operations = $this->getOperationPair(
1371 CRM_Utils_Array::value('operatorType', $field),
1372 $fieldName);
1373
1374 switch (CRM_Utils_Array::value('operatorType', $field)) {
1375 case CRM_Report_Form::OP_MONTH:
1376 if (!array_key_exists('options', $field) ||
1377 !is_array($field['options']) || empty($field['options'])
1378 ) {
1379 // If there's no option list for this filter, define one.
1380 $field['options'] = CRM_Utils_Date::getFullMonthNames();
1381
1382 // Add this option list to this column _columns. This is
1383 // required so that filter statistics show properly.
1384 $this->_columns[$table]['filters'][$fieldName]['options'] = $field['options'];
1385 }
1386 case CRM_Report_Form::OP_MULTISELECT:
1387 case CRM_Report_Form::OP_MULTISELECT_SEPARATOR:
1388 // assume a multi-select field
1389 if (!empty($field['options']) ||
1390 $fieldName == 'state_province_id' || $fieldName == 'county_id'
1391 ) {
1392 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1393 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
1394 );
1395
1396 if (count($operations) <= 1) {
1397 $element->freeze();
1398 }
1399 if ($fieldName == 'state_province_id' ||
1400 $fieldName == 'county_id'
1401 ) {
1402 $this->addChainSelect($fieldName . '_value', [
1403 'multiple' => TRUE,
1404 'label' => NULL,
1405 'class' => 'huge',
1406 ]);
1407 }
1408 else {
1409 $this->addElement('select', "{$fieldName}_value", NULL, $field['options'], [
1410 'style' => 'min-width:250px',
1411 'class' => 'crm-select2 huge',
1412 'multiple' => TRUE,
1413 'placeholder' => ts('- select -'),
1414 ]);
1415 }
1416 }
1417 break;
1418
1419 case CRM_Report_Form::OP_SELECT:
1420 // assume a select field
1421 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1422 if (!empty($field['options'])) {
1423 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
1424 }
1425 break;
1426
1427 case CRM_Report_Form::OP_ENTITYREF:
1428 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
1429 $this->setEntityRefDefaults($field, $table);
1430 $this->addEntityRef("{$fieldName}_value", NULL, $field['attributes']);
1431 break;
1432
1433 case CRM_Report_Form::OP_DATE:
1434 // build datetime fields
1435 $this->addDatePickerRange($fieldName, $field['title'], FALSE, FALSE, 'From', 'To', $operations, '_to', '_from');
1436 break;
1437
1438 case CRM_Report_Form::OP_DATETIME:
1439 // build datetime fields
1440 $this->addDatePickerRange($fieldName, $field['title'], TRUE, FALSE, 'From', 'To', $operations, '_to', '_from');
1441 break;
1442
1443 case CRM_Report_Form::OP_INT:
1444 case CRM_Report_Form::OP_FLOAT:
1445 // and a min value input box
1446 $this->add('text', "{$fieldName}_min", ts('Min'));
1447 // and a max value input box
1448 $this->add('text', "{$fieldName}_max", ts('Max'));
1449 default:
1450 // default type is string
1451 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
1452 ['onchange' => "return showHideMaxMinVal( '$fieldName', this.value );"]
1453 );
1454 // we need text box for value input
1455 $this->add('text', "{$fieldName}_value", NULL, ['class' => 'huge']);
1456 break;
1457 }
1458 }
1459 }
1460 if (!empty($filterGroups)) {
1461 $this->tabs['Filters'] = [
1462 'title' => ts('Filters'),
1463 'tpl' => 'Filters',
1464 'div_label' => 'set-filters',
1465 ];
1466 }
1467 $this->assign('filterGroups', $filterGroups);
1468 // Filters is deprecated in favour of filterGroups.
1469 $this->assign('filters', $filters);
1470 }
1471
1472 /**
1473 * Function to assign the tabs to the template in the correct order.
1474 *
1475 * We want the tabs to wind up in this order (if not overridden).
1476 *
1477 * - Field Selection
1478 * - Group Bys
1479 * - Order Bys
1480 * - Other Options
1481 * - Filters
1482 */
1483 protected function assignTabs() {
1484 $order = [
1485 'FieldSelection',
1486 'GroupBy',
1487 'OrderBy',
1488 'ReportOptions',
1489 'Filters',
1490 ];
1491 $order = array_intersect_key(array_fill_keys($order, 1), $this->tabs);
1492 $order = array_merge($order, $this->tabs);
1493 $this->assign('tabs', $order);
1494 }
1495
1496 /**
1497 * The intent is to add a tab for developers to view the sql.
1498 *
1499 * Currently using dpm.
1500 *
1501 * @param string $sql
1502 */
1503 public function addToDeveloperTab($sql) {
1504 if (!CRM_Core_Permission::check('view report sql')) {
1505 return;
1506 }
1507 $ignored_output_modes = ['pdf', 'csv', 'print'];
1508 if (in_array($this->_outputMode, $ignored_output_modes)) {
1509 return;
1510 }
1511 $this->tabs['Developer'] = [
1512 'title' => ts('Developer'),
1513 'tpl' => 'Developer',
1514 'div_label' => 'set-developer',
1515 ];
1516
1517 $this->assignTabs();
1518 $this->sqlFormattedArray = [];
1519 $this->sqlArray[] = $sql;
1520 foreach ($this->sqlArray as $sql) {
1521 foreach (['LEFT JOIN'] as $term) {
1522 $sql = str_replace($term, '<br> ' . $term, $sql);
1523 }
1524 foreach (['FROM', 'WHERE', 'GROUP BY', 'ORDER BY', 'LIMIT', ';'] as $term) {
1525 $sql = str_replace($term, '<br><br>' . $term, $sql);
1526 }
1527 $this->sqlFormattedArray[] = $sql;
1528 $this->assign('sql', implode(';<br><br><br><br>', $this->sqlFormattedArray));
1529 }
1530 $this->assign('sqlModes', $sqlModes = CRM_Utils_SQL::getSqlModes());
1531
1532 }
1533
1534 /**
1535 * Add options defined in $this->_options to the report.
1536 */
1537 public function addOptions() {
1538 if (!empty($this->_options)) {
1539 // FIXME: For now lets build all elements as checkboxes.
1540 // Once we clear with the format we can build elements based on type
1541
1542 foreach ($this->_options as $fieldName => $field) {
1543 $options = [];
1544
1545 if ($field['type'] == 'select') {
1546 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
1547 }
1548 elseif ($field['type'] == 'checkbox') {
1549 $options[$field['title']] = $fieldName;
1550 $this->addCheckBox($fieldName, NULL,
1551 $options, NULL,
1552 NULL, NULL, NULL, $this->_fourColumnAttribute
1553 );
1554 }
1555 }
1556 }
1557 if (!empty($this->_options) &&
1558 (!$this->_id
1559 || ($this->_id && CRM_Report_BAO_ReportInstance::contactCanAdministerReport($this->_id)))
1560 ) {
1561 $this->tabs['ReportOptions'] = [
1562 'title' => ts('Display Options'),
1563 'tpl' => 'ReportOptions',
1564 'div_label' => 'other-options',
1565 ];
1566 }
1567 $this->assign('otherOptions', $this->_options);
1568 }
1569
1570 /**
1571 * Add chart options to the report.
1572 */
1573 public function addChartOptions() {
1574 if (!empty($this->_charts)) {
1575 $this->addElement('select', "charts", ts('Chart'), $this->_charts);
1576 $this->assign('charts', $this->_charts);
1577 $this->addElement('xbutton', $this->_chartButtonName, ts('View'), ['type' => 'submit']);
1578 }
1579 }
1580
1581 /**
1582 * Add group by options to the report.
1583 */
1584 public function addGroupBys() {
1585 $options = $freqElements = [];
1586
1587 foreach ($this->_columns as $tableName => $table) {
1588 if (array_key_exists('group_bys', $table)) {
1589 foreach ($table['group_bys'] as $fieldName => $field) {
1590 if (!empty($field) && empty($field['no_display'])) {
1591 $options[$field['title']] = $fieldName;
1592 if (!empty($field['frequency'])) {
1593 $freqElements[$field['title']] = $fieldName;
1594 }
1595 }
1596 }
1597 }
1598 }
1599 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
1600 NULL, NULL, NULL, $this->_fourColumnAttribute
1601 );
1602 $this->assign('groupByElements', $options);
1603 if (!empty($options)) {
1604 $this->tabs['GroupBy'] = [
1605 'title' => ts('Grouping'),
1606 'tpl' => 'GroupBy',
1607 'div_label' => 'group-by-elements',
1608 ];
1609 }
1610
1611 foreach ($freqElements as $name) {
1612 $this->addElement('select', "group_bys_freq[$name]",
1613 ts('Frequency'), $this->_groupByDateFreq
1614 );
1615 }
1616 }
1617
1618 /**
1619 * Add data for order by tab.
1620 */
1621 public function addOrderBys() {
1622 $options = [];
1623 foreach ($this->_columns as $tableName => $table) {
1624
1625 // Report developer may define any column to order by; include these as order-by options.
1626 if (array_key_exists('order_bys', $table)) {
1627 foreach ($table['order_bys'] as $fieldName => $field) {
1628 if (!empty($field)) {
1629 $options[$fieldName] = $field['title'];
1630 }
1631 }
1632 }
1633
1634 // Add searchable custom fields as order-by options, if so requested
1635 // (These are already indexed, so allowing to order on them is cheap.)
1636
1637 if ($this->_autoIncludeIndexedFieldsAsOrderBys &&
1638 array_key_exists('extends', $table) && !empty($table['extends'])
1639 ) {
1640 foreach ($table['fields'] as $fieldName => $field) {
1641 if (empty($field['no_display'])) {
1642 $options[$fieldName] = $field['title'];
1643 }
1644 }
1645 }
1646 }
1647
1648 asort($options);
1649
1650 $this->assign('orderByOptions', $options);
1651 if (!empty($options)) {
1652 $this->tabs['OrderBy'] = [
1653 'title' => ts('Sorting'),
1654 'tpl' => 'OrderBy',
1655 'div_label' => 'order-by-elements',
1656 ];
1657 }
1658
1659 if (!empty($options)) {
1660 $options = [
1661 '-' => ts(' - none - '),
1662 ] + $options;
1663 for ($i = 1; $i <= 5; $i++) {
1664 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1665 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), [
1666 'ASC' => ts('Ascending'),
1667 'DESC' => ts('Descending'),
1668 ]);
1669 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, ['id' => "order_by_section_$i"]);
1670 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, ['id' => "order_by_pagebreak_$i"]);
1671 }
1672 }
1673 }
1674
1675 /**
1676 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
1677 *
1678 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1679 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1680 * Criteria.tpl.
1681 */
1682 public function buildInstanceAndButtons() {
1683 CRM_Report_Form_Instance::buildForm($this);
1684 $this->_actionButtonName = $this->getButtonName('submit');
1685 $this->addTaskMenu($this->getActions($this->_id));
1686
1687 $this->assign('instanceForm', $this->_instanceForm);
1688
1689 // CRM-16274 Determine if user has 'edit all contacts' or equivalent
1690 $permission = CRM_Core_Permission::getPermission();
1691 if ($this->_instanceForm && $permission == CRM_Core_Permission::EDIT &&
1692 $this->_add2groupSupported
1693 ) {
1694 $this->addElement('select', 'groups', ts('Group'),
1695 ['' => ts('Add Contacts to Group')] +
1696 CRM_Core_PseudoConstant::nestedGroup(),
1697 ['class' => 'crm-select2 crm-action-menu fa-plus huge']
1698 );
1699 $this->assign('group', TRUE);
1700 }
1701
1702 $this->addElement('xbutton', $this->_groupButtonName, '', [
1703 'type' => 'submit',
1704 'style' => 'display: none;',
1705 ]);
1706
1707 $this->addChartOptions();
1708 $showResultsLabel = $this->getResultsLabel();
1709 $this->addButtons([
1710 [
1711 'type' => 'submit',
1712 'name' => $showResultsLabel,
1713 'isDefault' => TRUE,
1714 ],
1715 ]);
1716 }
1717
1718 /**
1719 * Has this form been submitted already?
1720 *
1721 * @return bool
1722 */
1723 public function resultsDisplayed() {
1724 $buttonName = $this->controller->getButtonName();
1725 return ($buttonName || $this->_outputMode);
1726 }
1727
1728 /**
1729 * Get the actions for this report instance.
1730 *
1731 * @param int $instanceId
1732 *
1733 * @return array
1734 */
1735 protected function getActions($instanceId) {
1736 $actions = CRM_Report_BAO_ReportInstance::getActionMetadata();
1737 if (empty($instanceId)) {
1738 $actions['report_instance.save'] = [
1739 'title' => ts('Create Report'),
1740 'data' => [
1741 'is_confirm' => TRUE,
1742 'confirm_title' => ts('Create Report'),
1743 'confirm_refresh_fields' => json_encode([
1744 'title' => ['selector' => '.crm-report-instanceForm-form-block-title', 'prepend' => ''],
1745 'description' => ['selector' => '.crm-report-instanceForm-form-block-description', 'prepend' => ''],
1746 ]),
1747 ],
1748 ];
1749 unset($actions['report_instance.delete']);
1750 }
1751
1752 if (!$this->_csvSupported) {
1753 unset($actions['report_instance.csv']);
1754 }
1755
1756 CRM_Utils_Hook::alterReportVar('actions', $actions, $this);
1757
1758 return $actions;
1759 }
1760
1761 /**
1762 * Main build form function.
1763 */
1764 public function buildQuickForm() {
1765 $this->addColumns();
1766
1767 $this->addFilters();
1768
1769 $this->addOptions();
1770
1771 $this->addGroupBys();
1772
1773 $this->addOrderBys();
1774
1775 $this->buildInstanceAndButtons();
1776
1777 // Add form rule for report.
1778 if (is_callable([
1779 $this,
1780 'formRule',
1781 ])) {
1782 $this->addFormRule([get_class($this), 'formRule'], $this);
1783 }
1784 $this->assignTabs();
1785 }
1786
1787 /**
1788 * A form rule function for custom data.
1789 *
1790 * The rule ensures that fields selected in group_by if any) should only be the ones
1791 * present in display/select fields criteria;
1792 * note: works if and only if any custom field selected in group_by.
1793 *
1794 * @param array $fields
1795 * @param array $ignoreFields
1796 *
1797 * @return array
1798 */
1799 public function customDataFormRule($fields, $ignoreFields = []) {
1800 $errors = [];
1801 if (!empty($this->_customGroupExtends) && $this->_customGroupGroupBy &&
1802 !empty($fields['group_bys'])
1803 ) {
1804 foreach ($this->_columns as $tableName => $table) {
1805 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1806 substr($tableName, 0, 12) == 'custom_value') &&
1807 !empty($this->_columns[$tableName]['fields'])
1808 ) {
1809 foreach ($this->_columns[$tableName]['fields'] as $fieldName => $field) {
1810 if (array_key_exists($fieldName, $fields['group_bys']) &&
1811 !array_key_exists($fieldName, $fields['fields'])
1812 ) {
1813 $errors['fields'] = ts("Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.");
1814 }
1815 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1816 foreach ($fields['fields'] as $fld => $val) {
1817 if (!array_key_exists($fld, $fields['group_bys']) &&
1818 !in_array($fld, $ignoreFields)
1819 ) {
1820 $errors['fields'] = ts("Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.");
1821 }
1822 }
1823 }
1824 }
1825 }
1826 }
1827 }
1828 return $errors;
1829 }
1830
1831 /**
1832 * Get operators to display on form.
1833 *
1834 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1835 *
1836 * @param string $type
1837 * @param string $fieldName
1838 *
1839 * @return array
1840 */
1841 public function getOperationPair($type = "string", $fieldName = NULL) {
1842 // FIXME: At some point we should move these key-val pairs
1843 // to option_group and option_value table.
1844 switch ($type) {
1845 case CRM_Report_Form::OP_INT:
1846 case CRM_Report_Form::OP_FLOAT:
1847
1848 $result = [
1849 'lte' => ts('Is less than or equal to'),
1850 'gte' => ts('Is greater than or equal to'),
1851 'bw' => ts('Is between'),
1852 'eq' => ts('Is equal to'),
1853 'lt' => ts('Is less than'),
1854 'gt' => ts('Is greater than'),
1855 'neq' => ts('Is not equal to'),
1856 'nbw' => ts('Is not between'),
1857 'nll' => ts('Is empty (Null)'),
1858 'nnll' => ts('Is not empty (Null)'),
1859 ];
1860 return $result;
1861
1862 case CRM_Report_Form::OP_SELECT:
1863 $result = [
1864 'eq' => ts('Is equal to'),
1865 ];
1866 return $result;
1867
1868 case CRM_Report_Form::OP_MONTH:
1869 case CRM_Report_Form::OP_MULTISELECT:
1870 case CRM_Report_Form::OP_ENTITYREF:
1871
1872 $result = [
1873 'in' => ts('Is one of'),
1874 'notin' => ts('Is not one of'),
1875 'nll' => ts('Is empty (Null)'),
1876 'nnll' => ts('Is not empty (Null)'),
1877 ];
1878 return $result;
1879
1880 case CRM_Report_Form::OP_DATE:
1881
1882 $result = [
1883 'nll' => ts('Is empty (Null)'),
1884 'nnll' => ts('Is not empty (Null)'),
1885 ];
1886 return $result;
1887
1888 case CRM_Report_Form::OP_MULTISELECT_SEPARATOR:
1889 // use this operator for the values, concatenated with separator. For e.g if
1890 // multiple options for a column is stored as ^A{val1}^A{val2}^A
1891 $result = [
1892 'mhas' => ts('Is one of'),
1893 'mnot' => ts('Is not one of'),
1894 'nll' => ts('Is empty (Null)'),
1895 'nnll' => ts('Is not empty (Null)'),
1896 ];
1897 return $result;
1898
1899 default:
1900 // type is string
1901 $result = [
1902 'has' => ts('Contains'),
1903 'sw' => ts('Starts with'),
1904 'ew' => ts('Ends with'),
1905 'nhas' => ts('Does not contain'),
1906 'eq' => ts('Is equal to'),
1907 'neq' => ts('Is not equal to'),
1908 'nll' => ts('Is empty (Null)'),
1909 'nnll' => ts('Is not empty (Null)'),
1910 ];
1911 return $result;
1912 }
1913 }
1914
1915 /**
1916 * Build the tag filter field to display on the filters tab.
1917 */
1918 public function buildTagFilter() {
1919 $contactTags = CRM_Core_BAO_Tag::getTags($this->_tagFilterTable);
1920 if (!empty($contactTags)) {
1921 $this->_columns['civicrm_tag'] = [
1922 'dao' => 'CRM_Core_DAO_Tag',
1923 'filters' => [
1924 'tagid' => [
1925 'name' => 'tag_id',
1926 'title' => ts('Tag'),
1927 'type' => CRM_Utils_Type::T_INT,
1928 'tag' => TRUE,
1929 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
1930 'options' => $contactTags,
1931 ],
1932 ],
1933 ];
1934 }
1935 }
1936
1937 /**
1938 * Adds group filters to _columns (called from _Construct).
1939 */
1940 public function buildGroupFilter() {
1941 $this->_columns['civicrm_group']['filters'] = [
1942 'gid' => [
1943 'name' => 'group_id',
1944 'title' => ts('Group'),
1945 'type' => CRM_Utils_Type::T_INT,
1946 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
1947 'group' => TRUE,
1948 'options' => CRM_Core_PseudoConstant::nestedGroup(),
1949 ],
1950 ];
1951 if (empty($this->_columns['civicrm_group']['dao'])) {
1952 $this->_columns['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1953 }
1954 if (empty($this->_columns['civicrm_group']['alias'])) {
1955 $this->_columns['civicrm_group']['alias'] = 'cgroup';
1956 }
1957 }
1958
1959 /**
1960 * Get SQL operator from form text version.
1961 *
1962 * @param string $operator
1963 *
1964 * @return string
1965 */
1966 public function getSQLOperator($operator = "like") {
1967 switch ($operator) {
1968 case 'eq':
1969 return '=';
1970
1971 case 'lt':
1972 return '<';
1973
1974 case 'lte':
1975 return '<=';
1976
1977 case 'gt':
1978 return '>';
1979
1980 case 'gte':
1981 return '>=';
1982
1983 case 'ne':
1984 case 'neq':
1985 return '!=';
1986
1987 case 'nhas':
1988 return 'NOT LIKE';
1989
1990 case 'in':
1991 return 'IN';
1992
1993 case 'notin':
1994 return 'NOT IN';
1995
1996 case 'nll':
1997 return 'IS NULL';
1998
1999 case 'nnll':
2000 return 'IS NOT NULL';
2001
2002 default:
2003 // type is string
2004 return 'LIKE';
2005 }
2006 }
2007
2008 /**
2009 * Generate where clause.
2010 *
2011 * This can be overridden in reports for special treatment of a field
2012 *
2013 * @param array $field Field specifications
2014 * @param string $op Query operator (not an exact match to sql)
2015 * @param mixed $value
2016 * @param float $min
2017 * @param float $max
2018 *
2019 * @return null|string
2020 */
2021 public function whereClause(&$field, $op, $value, $min, $max) {
2022
2023 $type = CRM_Utils_Type::typeToString(CRM_Utils_Array::value('type', $field));
2024
2025 // CRM-18010: Ensure type of each report filters
2026 if (!$type) {
2027 trigger_error('Type is not defined for field ' . $field['name'], E_USER_WARNING);
2028 }
2029 $clause = NULL;
2030
2031 switch ($op) {
2032 case 'bw':
2033 case 'nbw':
2034 if (($min !== NULL && strlen($min) > 0) ||
2035 ($max !== NULL && strlen($max) > 0)
2036 ) {
2037 $clauses = [];
2038 if ($min) {
2039 $min = CRM_Utils_Type::escape($min, $type);
2040 if ($op == 'bw') {
2041 $clauses[] = "( {$field['dbAlias']} >= $min )";
2042 }
2043 else {
2044 $clauses[] = "( {$field['dbAlias']} < $min OR {$field['dbAlias']} IS NULL )";
2045 }
2046 }
2047 if ($max) {
2048 $max = CRM_Utils_Type::escape($max, $type);
2049 if ($op == 'bw') {
2050 $clauses[] = "( {$field['dbAlias']} <= $max )";
2051 }
2052 else {
2053 $clauses[] = "( {$field['dbAlias']} > $max )";
2054 }
2055 }
2056
2057 if (!empty($clauses)) {
2058 if ($op == 'bw') {
2059 $clause = implode(' AND ', $clauses);
2060 }
2061 else {
2062 $clause = '(' . implode('OR', $clauses) . ')';
2063 }
2064 }
2065 }
2066 break;
2067
2068 case 'has':
2069 case 'nhas':
2070 if ($value !== NULL && strlen($value) > 0) {
2071 $value = CRM_Utils_Type::escape($value, $type);
2072 if (strpos($value, '%') === FALSE) {
2073 $value = "'%{$value}%'";
2074 }
2075 else {
2076 $value = "'{$value}'";
2077 }
2078 $sqlOP = $this->getSQLOperator($op);
2079 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2080 }
2081 break;
2082
2083 case 'in':
2084 case 'notin':
2085 if ((is_string($value) || is_numeric($value)) && strlen($value)) {
2086 $value = explode(',', $value);
2087 }
2088 if ($value !== NULL && is_array($value) && count($value) > 0) {
2089 $sqlOP = $this->getSQLOperator($op);
2090 if (CRM_Utils_Array::value('type', $field) ==
2091 CRM_Utils_Type::T_STRING
2092 ) {
2093 //cycle through selections and escape values
2094 foreach ($value as $key => $selection) {
2095 $value[$key] = CRM_Utils_Type::escape($selection, $type);
2096 }
2097 $clause
2098 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
2099 "') )";
2100 }
2101 else {
2102 // for numerical values
2103 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
2104 ")";
2105 }
2106 if ($op == 'notin') {
2107 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
2108 }
2109 else {
2110 $clause = "( " . $clause . " )";
2111 }
2112 }
2113 break;
2114
2115 case 'mhas':
2116 case 'mnot':
2117 // multiple has or multiple not
2118 if ($value !== NULL && count($value) > 0) {
2119 $value = CRM_Utils_Type::escapeAll($value, $type);
2120 $operator = $op == 'mnot' ? 'NOT' : '';
2121 $regexp = "([[:cntrl:]]|^)" . implode('([[:cntrl:]]|$)|([[:cntrl:]]|^)', (array) $value) . "([[:cntrl:]]|$)";
2122 $clause = "{$field['dbAlias']} {$operator} REGEXP '{$regexp}'";
2123 }
2124 break;
2125
2126 case 'sw':
2127 case 'ew':
2128 if ($value !== NULL && strlen($value) > 0) {
2129 $value = CRM_Utils_Type::escape($value, $type);
2130 if (strpos($value, '%') === FALSE) {
2131 if ($op == 'sw') {
2132 $value = "'{$value}%'";
2133 }
2134 else {
2135 $value = "'%{$value}'";
2136 }
2137 }
2138 else {
2139 $value = "'{$value}'";
2140 }
2141 $sqlOP = $this->getSQLOperator($op);
2142 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2143 }
2144 break;
2145
2146 case 'nll':
2147 if ($type == 'String') {
2148 $sqlOP = $this->getSQLOperator($op);
2149 $clause = "( {$field['dbAlias']} $sqlOP OR {$field['dbAlias']} = '' )";
2150 }
2151 else {
2152 $sqlOP = $this->getSQLOperator($op);
2153 $clause = "( {$field['dbAlias']} $sqlOP )";
2154 }
2155 break;
2156
2157 case 'nnll':
2158 if ($type == 'String') {
2159 $sqlOP = $this->getSQLOperator($op);
2160 $clause = "( {$field['dbAlias']} $sqlOP AND {$field['dbAlias']} <> '' )";
2161 }
2162 else {
2163 $sqlOP = $this->getSQLOperator($op);
2164 $clause = "( {$field['dbAlias']} $sqlOP )";
2165 }
2166 break;
2167
2168 case 'eq':
2169 case 'neq':
2170 case 'ne':
2171 //CRM-18457: some custom field passes value in array format against binary operator
2172 if (is_array($value) && count($value)) {
2173 $value = $value[0];
2174 }
2175
2176 default:
2177 if ($value !== NULL && $value !== '') {
2178 if (isset($field['clause'])) {
2179 // FIXME: we not doing escape here. Better solution is to use two
2180 // different types - data-type and filter-type
2181 $clause = $field['clause'];
2182 }
2183 elseif (!is_array($value)) {
2184 $value = CRM_Utils_Type::escape($value, $type);
2185 $sqlOP = $this->getSQLOperator($op);
2186 if ($field['type'] == CRM_Utils_Type::T_STRING) {
2187 $value = "'{$value}'";
2188 }
2189 $clause = "( {$field['dbAlias']} $sqlOP $value )";
2190 }
2191 }
2192 break;
2193 }
2194
2195 //dev/core/544 Add report support for multiple contact subTypes
2196 if ($field['name'] == 'contact_sub_type' && $clause) {
2197 $clause = $this->whereSubtypeClause($field, $value, $op);
2198 }
2199 if (!empty($field['group']) && $clause) {
2200 $clause = $this->whereGroupClause($field, $value, $op);
2201 }
2202 elseif (!empty($field['tag']) && $clause) {
2203 // not using left join in query because if any contact
2204 // belongs to more than one tag, results duplicate
2205 // entries.
2206 $clause = $this->whereTagClause($field, $value, $op);
2207 }
2208 elseif (!empty($field['membership_org']) && $clause) {
2209 $clause = $this->whereMembershipOrgClause($value, $op);
2210 }
2211 elseif (!empty($field['membership_type']) && $clause) {
2212 $clause = $this->whereMembershipTypeClause($value, $op);
2213 }
2214 return $clause;
2215 }
2216
2217 /**
2218 * Get SQL where clause for contact subtypes
2219 * @param string $field
2220 * @param mixed $value
2221 * @param string $op SQL Operator
2222 *
2223 * @return string
2224 */
2225 public function whereSubtypeClause($field, $value, $op) {
2226 // Get the correct SQL operator.
2227 $orNull = FALSE;
2228 switch ($op) {
2229 case 'notin':
2230 $op = 'nhas';
2231 $clauseSeparator = ' AND ';
2232 $orNull = TRUE;
2233 break;
2234
2235 case 'in':
2236 $op = 'has';
2237 $clauseSeparator = ' OR ';
2238 break;
2239 }
2240 $sqlOp = $this->getSQLOperator($op);
2241 if ($sqlOp == 'IS NULL' || $sqlOp == 'IS NOT NULL') {
2242 $clause = "{$field['dbAlias']} $sqlOp";
2243 }
2244 else {
2245 $subclauses = [];
2246 foreach ($value as $item) {
2247 $subclauses[] = "( {$field['dbAlias']} $sqlOp '%" . CRM_Core_DAO::VALUE_SEPARATOR . $item . CRM_Core_DAO::VALUE_SEPARATOR . "%' )";
2248 }
2249 $clause = implode($clauseSeparator, $subclauses);
2250 }
2251 $clause = "( $clause )";
2252 if ($orNull) {
2253 $clause = "( ( {$field['dbAlias']} IS NULL ) OR $clause )";
2254 }
2255 return $clause;
2256 }
2257
2258 /**
2259 * Get SQL where clause for a date field.
2260 *
2261 * @param string $fieldName
2262 * @param string $relative
2263 * @param string $from
2264 * @param string $to
2265 * @param string $type
2266 * @param string $fromTime
2267 * @param string $toTime
2268 *
2269 * @return null|string
2270 */
2271 public function dateClause(
2272 $fieldName,
2273 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
2274 ) {
2275 $clauses = [];
2276 if (array_key_exists($relative, $this->getOperationPair(CRM_Report_Form::OP_DATE))) {
2277 $sqlOP = $this->getSQLOperator($relative);
2278 return "( {$fieldName} {$sqlOP} )";
2279 }
2280 if (strlen($to) === 10) {
2281 // If we just have the date we assume the end of that day.
2282 $to .= ' 23:59:59';
2283 }
2284
2285 if ($relative) {
2286 [$from, $to] = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
2287 }
2288
2289 if ($from) {
2290 $clauses[] = "( {$fieldName} >= " . date('YmdHis', strtotime($from)) . ')';
2291 }
2292
2293 if ($to) {
2294 $clauses[] = "( {$fieldName} <= " . date('YmdHis', strtotime($to)) . ')';
2295 }
2296 if (!empty($clauses)) {
2297 return implode(' AND ', $clauses);
2298 }
2299
2300 return NULL;
2301 }
2302
2303 /**
2304 * Get values for from and to for date ranges.
2305 *
2306 * @deprecated
2307 *
2308 * @param bool $relative
2309 * @param string $from
2310 * @param string $to
2311 * @param string $fromTime
2312 * @param string $toTime
2313 *
2314 * @return array
2315 */
2316 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
2317 if (!empty($fromTime) || !empty($toTime)) {
2318 throw new CRM_Core_Exception('Report template needs to be updated as getFromTo no longer supports fromTime or ToTime Parameters');
2319 }
2320 return CRM_Utils_Date::getFromTo($relative, $from, $to);
2321 }
2322
2323 /**
2324 * Alter display of rows.
2325 *
2326 * Iterate through the rows retrieved via SQL and make changes for display purposes,
2327 * such as rendering contacts as links.
2328 *
2329 * @param array $rows
2330 * Rows generated by SQL, with an array for each row.
2331 */
2332 public function alterDisplay(&$rows) {
2333 }
2334
2335 /**
2336 * Alter the way in which custom data fields are displayed.
2337 *
2338 * @param array $rows
2339 */
2340 public function alterCustomDataDisplay(&$rows) {
2341 // custom code to alter rows having custom values
2342 if (empty($this->_customGroupExtends)) {
2343 return;
2344 }
2345
2346 $customFields = [];
2347 $customFieldIds = [];
2348 foreach ($this->_params['fields'] as $fieldAlias => $value) {
2349 if ($fieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
2350 $customFieldIds[$fieldAlias] = $fieldId;
2351 }
2352 }
2353 if (empty($customFieldIds)) {
2354 return;
2355 }
2356
2357 // skip for type date and ContactReference since date format is already handled
2358 $query = "
2359 SELECT cg.table_name, cf.id
2360 FROM civicrm_custom_field cf
2361 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
2362 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
2363 cg.is_active = 1 AND
2364 cf.is_active = 1 AND
2365 cf.is_searchable = 1 AND
2366 cf.data_type NOT IN ('ContactReference', 'Date') AND
2367 cf.id IN (" . implode(",", $customFieldIds) . ")";
2368
2369 $dao = CRM_Core_DAO::executeQuery($query);
2370 while ($dao->fetch()) {
2371 $customFields[$dao->table_name . '_custom_' . $dao->id] = $dao->id;
2372 }
2373
2374 $entryFound = FALSE;
2375 foreach ($rows as $rowNum => $row) {
2376 foreach ($row as $tableCol => $val) {
2377 if (array_key_exists($tableCol, $customFields)) {
2378 $rows[$rowNum][$tableCol] = CRM_Core_BAO_CustomField::displayValue($val, $customFields[$tableCol]);
2379 $entryFound = TRUE;
2380 }
2381 }
2382
2383 // skip looking further in rows, if first row itself doesn't
2384 // have the column we need
2385 if (!$entryFound) {
2386 break;
2387 }
2388 }
2389 }
2390
2391 /**
2392 * Remove duplicate rows.
2393 *
2394 * @param array $rows
2395 */
2396 public function removeDuplicates(&$rows) {
2397 if (empty($this->_noRepeats)) {
2398 return;
2399 }
2400 $checkList = [];
2401
2402 foreach ($rows as $key => $list) {
2403 foreach ($list as $colName => $colVal) {
2404 if (array_key_exists($colName, $checkList) &&
2405 $checkList[$colName] == $colVal
2406 ) {
2407 $rows[$key][$colName] = "";
2408 }
2409 if (in_array($colName, $this->_noRepeats)) {
2410 $checkList[$colName] = $colVal;
2411 }
2412 }
2413 }
2414 }
2415
2416 /**
2417 * Fix subtotal display.
2418 *
2419 * @param array $row
2420 * @param array $fields
2421 * @param bool $subtotal
2422 */
2423 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
2424 foreach ($row as $colName => $colVal) {
2425 if (in_array($colName, $fields)) {
2426 }
2427 elseif (isset($this->_columnHeaders[$colName])) {
2428 if ($subtotal) {
2429 $row[$colName] = 'Subtotal';
2430 $subtotal = FALSE;
2431 }
2432 else {
2433 unset($row[$colName]);
2434 }
2435 }
2436 }
2437 }
2438
2439 /**
2440 * Calculate grant total.
2441 *
2442 * @param array $rows
2443 *
2444 * @return bool
2445 */
2446 public function grandTotal(&$rows) {
2447 if (!$this->_rollup || count($rows) == 1) {
2448 return FALSE;
2449 }
2450
2451 $this->moveSummaryColumnsToTheRightHandSide();
2452
2453 if ($this->_limit && count($rows) >= $this->getRowCount()) {
2454 return FALSE;
2455 }
2456
2457 $this->rollupRow = array_pop($rows);
2458
2459 foreach ($this->_columnHeaders as $fld => $val) {
2460 if (!in_array($fld, $this->_statFields)) {
2461 if (!$this->_grandFlag) {
2462 $this->rollupRow[$fld] = ts('Grand Total');
2463 $this->_grandFlag = TRUE;
2464 }
2465 else {
2466 $this->rollupRow[$fld] = "";
2467 }
2468 }
2469 }
2470
2471 $this->assign('grandStat', $this->rollupRow);
2472 return TRUE;
2473 }
2474
2475 /**
2476 * Format display output.
2477 *
2478 * @param array $rows
2479 * @param bool $pager
2480 */
2481 public function formatDisplay(&$rows, $pager = TRUE) {
2482 // set pager based on if any limit was applied in the query.
2483 if ($pager) {
2484 $this->setPager();
2485 }
2486 $chartEnabled = !empty($this->_params['charts']) && !empty($rows);
2487 $this->assign('chartEnabled', $chartEnabled);
2488 // allow building charts if any
2489 if ($chartEnabled) {
2490 $this->buildChart($rows);
2491 $this->_chartId = "{$this->_params['charts']}_" .
2492 ($this->_id ? $this->_id : substr(get_class($this), 16)) . '_' .
2493 CRM_Core_Config::singleton()->userSystem->getSessionId();
2494 $this->assign('chartId', $this->_chartId);
2495 }
2496
2497 // unset columns not to be displayed.
2498 foreach ($this->_columnHeaders as $key => $value) {
2499 if (!empty($value['no_display'])) {
2500 unset($this->_columnHeaders[$key]);
2501 }
2502 foreach (['colspan', 'type'] as $expectedKey) {
2503 if (!isset($this->_columnHeaders[$key][$expectedKey])) {
2504 // Ensure it is set to prevent smarty notices.
2505 $this->_columnHeaders[$key][$expectedKey] = FALSE;
2506 }
2507 }
2508 }
2509
2510 // unset columns not to be displayed.
2511 if (!empty($rows)) {
2512 foreach ($this->_noDisplay as $noDisplayField) {
2513 foreach ($rows as $rowNum => $row) {
2514 unset($this->_columnHeaders[$noDisplayField]);
2515 $expectedKeys = ['class'];
2516 foreach ($expectedKeys as $expectedKey) {
2517 if (!array_key_exists($expectedKey, $row)) {
2518 $rows[$rowNum][$expectedKey] = NULL;
2519 }
2520 }
2521 }
2522 }
2523 }
2524
2525 // Find alter display functions.
2526 $firstRow = reset($rows);
2527 if ($firstRow) {
2528 $selectedFields = array_keys($firstRow);
2529 $alterFunctions = $alterMap = $alterSpecs = [];
2530 foreach ($this->_columns as $tableName => $table) {
2531 if (array_key_exists('metadata', $table)) {
2532 foreach ($table['metadata'] as $field => $specs) {
2533 if (in_array($tableName . '_' . $field, $selectedFields)) {
2534 if (array_key_exists('alter_display', $specs)) {
2535 $alterFunctions[$tableName . '_' . $field] = $specs['alter_display'];
2536 $alterMap[$tableName . '_' . $field] = $field;
2537 $alterSpecs[$tableName . '_' . $field] = NULL;
2538 }
2539 // Add any alters that can be intuited from the field specs.
2540 // So far only boolean but a lot more could be.
2541 if (empty($alterSpecs[$tableName . '_' . $field]) && isset($specs['type']) && $specs['type'] == CRM_Utils_Type::T_BOOLEAN) {
2542 $alterFunctions[$tableName . '_' . $field] = 'alterBoolean';
2543 $alterMap[$tableName . '_' . $field] = $field;
2544 $alterSpecs[$tableName . '_' . $field] = NULL;
2545 }
2546 }
2547 }
2548 }
2549 }
2550
2551 // Run the alter display functions
2552 foreach ($rows as $index => & $row) {
2553 foreach ($row as $selectedField => $value) {
2554 if (array_key_exists($selectedField, $alterFunctions) && isset($value)) {
2555 $rows[$index][$selectedField] = $this->{$alterFunctions[$selectedField]}($value, $row, $selectedField, $alterMap[$selectedField], $alterSpecs[$selectedField]);
2556 }
2557 }
2558 }
2559 }
2560
2561 // use this method for formatting rows for display purpose.
2562 $this->alterDisplay($rows);
2563 CRM_Utils_Hook::alterReportVar('rows', $rows, $this);
2564
2565 // build array of section totals
2566 $this->sectionTotals();
2567
2568 // process grand-total row
2569 $this->grandTotal($rows);
2570
2571 // use this method for formatting custom rows for display purpose.
2572 $this->alterCustomDataDisplay($rows);
2573 }
2574
2575 /**
2576 * @param $value
2577 * @param $row
2578 * @param $selectedfield
2579 * @param $criteriaFieldName
2580 *
2581 * @return array
2582 */
2583 protected function alterStateProvinceID($value, &$row, $selectedfield, $criteriaFieldName) {
2584 $url = CRM_Utils_System::url(CRM_Utils_System::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl);
2585 $row[$selectedfield . '_link'] = $url;
2586 $row[$selectedfield . '_hover'] = ts("%1 for this state.", [
2587 1 => $value,
2588 ]);
2589
2590 $states = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
2591 if (!is_array($states)) {
2592 return $states;
2593 }
2594 }
2595
2596 /**
2597 * @param $value
2598 * @param $row
2599 * @param $selectedField
2600 * @param $criteriaFieldName
2601 *
2602 * @return array
2603 */
2604 protected function alterCountryID($value, &$row, $selectedField, $criteriaFieldName) {
2605 $url = CRM_Utils_System::url(CRM_Utils_System::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl);
2606 $row[$selectedField . '_link'] = $url;
2607 $row[$selectedField . '_hover'] = ts("%1 for this country.", [
2608 1 => $value,
2609 ]);
2610 $countries = CRM_Core_PseudoConstant::country($value, FALSE);
2611 if (!is_array($countries)) {
2612 return $countries;
2613 }
2614 }
2615
2616 /**
2617 * @param $value
2618 * @param $row
2619 * @param $selectedfield
2620 * @param $criteriaFieldName
2621 *
2622 * @return array
2623 */
2624 protected function alterCountyID($value, &$row, $selectedfield, $criteriaFieldName) {
2625 $url = CRM_Utils_System::url(CRM_Utils_System::currentPath(), "reset=1&force=1&{$criteriaFieldName}_op=in&{$criteriaFieldName}_value={$value}", $this->_absoluteUrl);
2626 $row[$selectedfield . '_link'] = $url;
2627 $row[$selectedfield . '_hover'] = ts("%1 for this county.", [
2628 1 => $value,
2629 ]);
2630 $counties = CRM_Core_PseudoConstant::county($value, FALSE);
2631 if (!is_array($counties)) {
2632 return $counties;
2633 }
2634 }
2635
2636 /**
2637 * @param $value
2638 * @param $row
2639 * @param $selectedfield
2640 * @param $criteriaFieldName
2641 *
2642 * @return mixed
2643 */
2644 protected function alterLocationTypeID($value, &$row, $selectedfield, $criteriaFieldName) {
2645 return CRM_Core_PseudoConstant::getLabel('CRM_Core_DAO_Address', 'location_type_id', $value);
2646 }
2647
2648 /**
2649 * @param $value
2650 * @param $row
2651 * @param $fieldname
2652 *
2653 * @return mixed
2654 */
2655 protected function alterContactID($value, &$row, $fieldname) {
2656 $nameField = substr($fieldname, 0, -2) . 'name';
2657 static $first = TRUE;
2658 static $viewContactList = FALSE;
2659 if ($first) {
2660 $viewContactList = CRM_Core_Permission::check('access CiviCRM');
2661 $first = FALSE;
2662 }
2663 if (!$viewContactList) {
2664 return $value;
2665 }
2666 if (array_key_exists($nameField, $row)) {
2667 $row[$nameField . '_link'] = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl);
2668 }
2669 else {
2670 $row[$fieldname . '_link'] = CRM_Utils_System::url("civicrm/contact/view", 'reset=1&cid=' . $value, $this->_absoluteUrl);
2671 }
2672 return $value;
2673 }
2674
2675 /**
2676 * @param $value
2677 * @param $row
2678 * @param $fieldname
2679 *
2680 * @return mixed
2681 */
2682 protected function alterCommunicationtMethod($value, &$row, $fieldname) {
2683 $communicationMethods = CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'preferred_communication_method');
2684
2685 // Explode padded values.
2686 $values = CRM_utils_array::explodePadded($value);
2687 // Flip values, compute intersection with $communicationMethods, and implode with commas.
2688 $value = implode(', ', array_intersect_key($communicationMethods, array_flip($values)));
2689 return $value;
2690 }
2691
2692 /**
2693 * @param $value
2694 *
2695 * @return mixed
2696 */
2697 protected function alterBoolean($value) {
2698 $options = [0 => '', 1 => ts('Yes')];
2699 if (isset($options[$value])) {
2700 return $options[$value];
2701 }
2702 return $value;
2703 }
2704
2705 /**
2706 * Build chart.
2707 *
2708 * @param array $rows
2709 */
2710 public function buildChart(&$rows) {
2711 // override this method for building charts.
2712 }
2713
2714 // select() method below has been added recently (v3.3), and many of the report templates might
2715 // still be having their own select() method. We should fix them as and when encountered and move
2716 // towards generalizing the select() method below.
2717
2718 /**
2719 * Generate the SELECT clause and set class variable $_select.
2720 */
2721 public function select() {
2722 $select = $this->_selectAliases = [];
2723 $this->storeGroupByArray();
2724
2725 foreach ($this->_columns as $tableName => $table) {
2726 if (array_key_exists('fields', $table)) {
2727 foreach ($table['fields'] as $fieldName => $field) {
2728 if ($tableName == 'civicrm_address') {
2729 // deprecated, use $this->isTableSelected.
2730 $this->_addressField = TRUE;
2731 }
2732 if ($tableName == 'civicrm_email') {
2733 $this->_emailField = TRUE;
2734 }
2735 if ($tableName == 'civicrm_phone') {
2736 $this->_phoneField = TRUE;
2737 }
2738
2739 if (!empty($field['required']) ||
2740 !empty($this->_params['fields'][$fieldName])
2741 ) {
2742
2743 // 1. In many cases we want select clause to be built in slightly different way
2744 // for a particular field of a particular type.
2745 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2746 // as needed.
2747 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2748 if ($selectClause) {
2749 $select[] = $selectClause;
2750 continue;
2751 }
2752
2753 // include statistics columns only if set
2754 if (!empty($field['statistics']) && !empty($this->_groupByArray)) {
2755 $select = $this->addStatisticsToSelect($field, $tableName, $fieldName, $select);
2756 }
2757 else {
2758
2759 $selectClause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, $fieldName, $field);
2760 if ($selectClause) {
2761 $select[] = $selectClause;
2762 }
2763 else {
2764 $select = $this->addBasicFieldToSelect($tableName, $fieldName, $field, $select);
2765 }
2766 }
2767 }
2768 }
2769 }
2770
2771 // select for group bys
2772 if (array_key_exists('group_bys', $table)) {
2773 foreach ($table['group_bys'] as $fieldName => $field) {
2774
2775 if ($tableName == 'civicrm_address') {
2776 $this->_addressField = TRUE;
2777 }
2778 if ($tableName == 'civicrm_email') {
2779 $this->_emailField = TRUE;
2780 }
2781 if ($tableName == 'civicrm_phone') {
2782 $this->_phoneField = TRUE;
2783 }
2784 // 1. In many cases we want select clause to be built in slightly different way
2785 // for a particular field of a particular type.
2786 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2787 // as needed.
2788 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2789 if ($selectClause) {
2790 $select[] = $selectClause;
2791 continue;
2792 }
2793
2794 if (!empty($this->_params['group_bys']) &&
2795 !empty($this->_params['group_bys'][$fieldName]) &&
2796 !empty($this->_params['group_bys_freq'])
2797 ) {
2798 switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
2799 case 'YEARWEEK':
2800 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2801 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2802 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2803 $field['title'] = 'Week';
2804 break;
2805
2806 case 'YEAR':
2807 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2808 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2809 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2810 $field['title'] = 'Year';
2811 break;
2812
2813 case 'MONTH':
2814 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2815 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2816 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2817 $field['title'] = 'Month';
2818 break;
2819
2820 case 'QUARTER':
2821 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2822 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2823 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2824 $field['title'] = 'Quarter';
2825 break;
2826 }
2827 // for graphs and charts -
2828 if (!empty($this->_params['group_bys_freq'][$fieldName])) {
2829 $this->_interval = $field['title'];
2830 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title']
2831 = $field['title'] . ' Beginning';
2832 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2833 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
2834
2835 // just to make sure these values are transferred to rows.
2836 // since we 'll need them for calculation purpose,
2837 // e.g making subtotals look nicer or graphs
2838 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = ['no_display' => TRUE];
2839 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = ['no_display' => TRUE];
2840 }
2841 }
2842 }
2843 }
2844 }
2845
2846 if (empty($select)) {
2847 // CRM-21412 Do not give fatal error on report when no fields selected
2848 $select = [1];
2849 }
2850
2851 $this->_selectClauses = $select;
2852 $this->_select = "SELECT " . implode(', ', $select) . " ";
2853 }
2854
2855 /**
2856 * Build select clause for a single field.
2857 *
2858 * @param string $tableName
2859 * @param string $tableKey
2860 * @param string $fieldName
2861 * @param string $field
2862 *
2863 * @return bool
2864 */
2865 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2866 if (!empty($field['pseudofield'])) {
2867 $alias = "{$tableName}_{$fieldName}";
2868 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'] ?? NULL;
2869 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = $field['type'] ?? NULL;
2870 $this->_columnHeaders["{$tableName}_{$fieldName}"]['dbAlias'] = $field['dbAlias'] ?? NULL;
2871 $this->_selectAliases[] = $alias;
2872 return ' 1 as ' . $alias;
2873 }
2874 return FALSE;
2875 }
2876
2877 /**
2878 * Build where clause.
2879 */
2880 public function where() {
2881 $this->storeWhereHavingClauseArray();
2882
2883 if (empty($this->_whereClauses)) {
2884 $this->_where = "WHERE ( 1 ) ";
2885 $this->_having = "";
2886 }
2887 else {
2888 $this->_where = "WHERE " . implode(' AND ', $this->_whereClauses);
2889 }
2890
2891 if ($this->_aclWhere) {
2892 $this->_where .= " AND {$this->_aclWhere} ";
2893 }
2894
2895 if (!empty($this->_havingClauses)) {
2896 // use this clause to construct group by clause.
2897 $this->_having = "HAVING " . implode(' AND ', $this->_havingClauses);
2898 }
2899 }
2900
2901 /**
2902 * Store Where clauses into an array.
2903 *
2904 * Breaking out this step makes over-riding more flexible as the clauses can be used in constructing a
2905 * temp table that may not be part of the final where clause or added
2906 * in other functions
2907 */
2908 public function storeWhereHavingClauseArray() {
2909 foreach ($this->_columns as $tableName => $table) {
2910 if (array_key_exists('filters', $table)) {
2911 foreach ($table['filters'] as $fieldName => $field) {
2912 // respect pseudofield to filter spec so fields can be marked as
2913 // not to be handled here
2914 if (!empty($field['pseudofield'])) {
2915 continue;
2916 }
2917 $clause = $this->generateFilterClause($field, $fieldName);
2918
2919 if (!empty($clause)) {
2920 if (!empty($field['having'])) {
2921 $this->_havingClauses[] = $clause;
2922 }
2923 else {
2924 $this->_whereClauses[] = $clause;
2925 }
2926 }
2927 }
2928 }
2929 }
2930
2931 }
2932
2933 /**
2934 * Set output mode.
2935 */
2936 public function processReportMode() {
2937 $this->setOutputMode();
2938
2939 $this->_sendmail
2940 = CRM_Utils_Request::retrieve(
2941 'sendmail',
2942 'Boolean',
2943 CRM_Core_DAO::$_nullObject
2944 );
2945
2946 if ($this->_sendmail && !$this->_outputMode) {
2947 // If we're here from the mail_report job, then the default there gets
2948 // set to pdf before we get here, but if we're somehow here and sending
2949 // by email and don't have a format set, then use print.
2950 // @todo Is this on purpose - why would they be different defaults?
2951 $this->_outputMode = 'print';
2952 }
2953
2954 // _outputMode means multiple things and can cover export to file formats,
2955 // like csv, or actions with no output, like save. So this will only set
2956 // a handler if it's one of the former. But it's also possible we have a
2957 // really interesting handler out there. But the point is we don't need to
2958 // know, just to know that a handler doesn't always get set by this call.
2959 $this->setOutputHandler();
2960
2961 if (!empty($this->outputHandler)) {
2962 if ($this->_sendmail) {
2963 // If we're sending by email these are the only options that make
2964 // sense.
2965 $this->printOnly = TRUE;
2966 $this->addPaging = FALSE;
2967 $this->_absoluteUrl = TRUE;
2968 }
2969 else {
2970 // otherwise ask the handler
2971 $this->printOnly = $this->outputHandler->isPrintOnly();
2972 $this->addPaging = $this->outputHandler->isAddPaging();
2973 $this->_absoluteUrl = $this->outputHandler->isAbsoluteUrl();
2974 }
2975 }
2976 elseif ($this->_outputMode == 'copy' && $this->_criteriaForm) {
2977 $this->_createNew = TRUE;
2978 }
2979
2980 $this->assign('outputMode', $this->_outputMode);
2981 $this->assign('printOnly', $this->printOnly);
2982 // Get today's date to include in printed reports
2983 if ($this->printOnly) {
2984 $reportDate = CRM_Utils_Date::customFormat(date('Y-m-d H:i'));
2985 $this->assign('reportDate', $reportDate);
2986 }
2987 }
2988
2989 /**
2990 * Post Processing function for Form.
2991 *
2992 * postProcessCommon should be used to set other variables from input as the api accesses that function.
2993 * This function is not accessed when the api calls the report.
2994 */
2995 public function beginPostProcess() {
2996 $this->setParams($this->controller->exportValues($this->_name));
2997 if (empty($this->_params) &&
2998 $this->_force
2999 ) {
3000 $this->setParams($this->_formValues);
3001 }
3002
3003 // hack to fix params when submitted from dashboard, CRM-8532
3004 // fields array is missing because form building etc is skipped
3005 // in dashboard mode for report
3006 //@todo - this could be done in the dashboard no we have a setter
3007 if (empty($this->_params['fields']) && !$this->_noFields) {
3008 $this->setParams($this->_formValues);
3009 }
3010
3011 $this->processReportMode();
3012
3013 if ($this->_outputMode == 'save' || $this->_outputMode == 'copy') {
3014 $this->_createNew = ($this->_outputMode == 'copy');
3015 CRM_Report_Form_Instance::postProcess($this);
3016 }
3017 if ($this->_outputMode == 'delete') {
3018 CRM_Report_BAO_ReportInstance::doFormDelete($this->_id, 'civicrm/report/list?reset=1', 'civicrm/report/list?reset=1');
3019 }
3020
3021 $this->_formValues = $this->_params;
3022
3023 $this->beginPostProcessCommon();
3024 }
3025
3026 /**
3027 * BeginPostProcess function run in both report mode and non-report mode (api).
3028 */
3029 public function beginPostProcessCommon() {
3030 }
3031
3032 /**
3033 * Build the report query.
3034 *
3035 * @param bool $applyLimit
3036 *
3037 * @return string
3038 */
3039 public function buildQuery($applyLimit = TRUE) {
3040 $this->buildGroupTempTable();
3041 $this->select();
3042 $this->from();
3043 $this->customDataFrom();
3044 $this->buildPermissionClause();
3045 $this->where();
3046 $this->groupBy();
3047 $this->orderBy();
3048
3049 foreach ($this->unselectedOrderByColumns() as $alias => $field) {
3050 $clause = $this->getSelectClauseWithGroupConcatIfNotGroupedBy($field['table_name'], $field['name'], $field);
3051 if (!$clause) {
3052 $clause = "{$field['dbAlias']} as {$alias}";
3053 }
3054 $this->_select .= ", $clause ";
3055 }
3056
3057 if ($applyLimit && empty($this->_params['charts'])) {
3058 $this->limit();
3059 }
3060 CRM_Utils_Hook::alterReportVar('sql', $this, $this);
3061
3062 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
3063 $this->addToDeveloperTab($sql);
3064 return $sql;
3065 }
3066
3067 /**
3068 * Build group by clause.
3069 */
3070 public function groupBy() {
3071 $this->storeGroupByArray();
3072
3073 if (!empty($this->_groupByArray)) {
3074 if ($this->optimisedForOnlyFullGroupBy) {
3075 // We should probably deprecate this code path. What happens here is that
3076 // the group by is amended to reflect the select columns. This often breaks the
3077 // results. Retrofitting group strict group by onto existing report classes
3078 // went badly.
3079 $this->_groupBy = CRM_Contact_BAO_Query::getGroupByFromSelectColumns($this->_selectClauses, $this->_groupByArray);
3080 }
3081 else {
3082 $this->_groupBy = ' GROUP BY ' . implode($this->_groupByArray);
3083 }
3084 }
3085 }
3086
3087 /**
3088 * Build order by clause.
3089 */
3090 public function orderBy() {
3091 $this->_orderBy = "";
3092 $this->_sections = [];
3093 $this->storeOrderByArray();
3094 if (!empty($this->_orderByArray) && !$this->_rollup == 'WITH ROLLUP') {
3095 $this->_orderBy = "ORDER BY " . implode(', ', $this->_orderByArray);
3096 }
3097 $this->assign('sections', $this->_sections);
3098 }
3099
3100 /**
3101 * Extract order by fields and store as an array.
3102 *
3103 * In some cases other functions want to know which fields are selected for ordering by
3104 * Separating this into a separate function allows it to be called separately from constructing
3105 * the order by clause
3106 */
3107 public function storeOrderByArray() {
3108 $orderBys = [];
3109
3110 if (!empty($this->_params['order_bys']) &&
3111 is_array($this->_params['order_bys']) &&
3112 !empty($this->_params['order_bys'])
3113 ) {
3114
3115 // Process order_bys in user-specified order
3116 foreach ($this->_params['order_bys'] as $orderBy) {
3117 $orderByField = [];
3118 foreach ($this->_columns as $tableName => $table) {
3119 if (array_key_exists('order_bys', $table)) {
3120 // For DAO columns defined in $this->_columns
3121 $fields = $table['order_bys'];
3122 }
3123 elseif (array_key_exists('extends', $table)) {
3124 // For custom fields referenced in $this->_customGroupExtends
3125 $fields = CRM_Utils_Array::value('fields', $table, []);
3126 }
3127 else {
3128 continue;
3129 }
3130 if (!empty($fields) && is_array($fields)) {
3131 foreach ($fields as $fieldName => $field) {
3132 if ($fieldName == $orderBy['column']) {
3133 $orderByField = array_merge($field, $orderBy);
3134 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
3135 break 2;
3136 }
3137 }
3138 }
3139 }
3140
3141 if (!empty($orderByField)) {
3142 $this->_orderByFields[$orderByField['tplField']] = $orderByField;
3143 if ($this->groupConcatTested) {
3144 $orderBys[$orderByField['tplField']] = "{$orderByField['tplField']} {$orderBy['order']}";
3145 }
3146 else {
3147 // Not sure when this is preferable to using tplField (which has
3148 // definitely been tested to work in cases then this does not.
3149 // in caution not switching unless report has been tested for
3150 // group concat functionality.
3151 $orderBys[$orderByField['tplField']] = "{$orderByField['dbAlias']} {$orderBy['order']}";
3152 }
3153
3154 // Record any section headers for assignment to the template
3155 if (!empty($orderBy['section'])) {
3156 $orderByField['pageBreak'] = $orderBy['pageBreak'] ?? NULL;
3157 $this->_sections[$orderByField['tplField']] = $orderByField;
3158 }
3159 }
3160 }
3161 }
3162
3163 $this->_orderByArray = $orderBys;
3164
3165 $this->assign('sections', $this->_sections);
3166 }
3167
3168 /**
3169 * Determine unselected columns.
3170 *
3171 * @return array
3172 */
3173 public function unselectedOrderByColumns() {
3174 return array_diff_key($this->_orderByFields, $this->getSelectColumns());
3175 }
3176
3177 /**
3178 * Determine unselected columns.
3179 *
3180 * @return array
3181 */
3182 public function unselectedSectionColumns() {
3183 if (is_array($this->_sections)) {
3184 return array_diff_key($this->_sections, $this->getSelectColumns());
3185 }
3186 else {
3187 return [];
3188 }
3189 }
3190
3191 /**
3192 * Build output rows.
3193 *
3194 * @param string $sql
3195 * @param array $rows
3196 */
3197 public function buildRows($sql, &$rows) {
3198 if (!$this->optimisedForOnlyFullGroupBy) {
3199 CRM_Core_DAO::disableFullGroupByMode();
3200 }
3201 $dao = CRM_Core_DAO::executeQuery($sql);
3202 if (stristr($this->_select, 'SQL_CALC_FOUND_ROWS')) {
3203 $this->_rowsFound = CRM_Core_DAO::singleValueQuery('SELECT FOUND_ROWS()');
3204 }
3205 CRM_Core_DAO::reenableFullGroupByMode();
3206 if (!is_array($rows)) {
3207 $rows = [];
3208 }
3209
3210 // use this method to modify $this->_columnHeaders
3211 $this->modifyColumnHeaders();
3212
3213 $unselectedSectionColumns = $this->unselectedSectionColumns();
3214
3215 while ($dao->fetch()) {
3216 $row = [];
3217 foreach ($this->_columnHeaders as $key => $value) {
3218 if (property_exists($dao, $key)) {
3219 $row[$key] = $dao->$key;
3220 }
3221 }
3222
3223 // section headers not selected for display need to be added to row
3224 foreach ($unselectedSectionColumns as $key => $values) {
3225 if (property_exists($dao, $key)) {
3226 $row[$key] = $dao->$key;
3227 }
3228 }
3229
3230 $rows[] = $row;
3231 }
3232 }
3233
3234 /**
3235 * Calculate section totals.
3236 *
3237 * When "order by" fields are marked as sections, this assigns to the template
3238 * an array of total counts for each section. This data is used by the Smarty
3239 * plugin {sectionTotal}.
3240 */
3241 public function sectionTotals() {
3242
3243 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
3244 if (empty($this->_selectAliases)) {
3245 return;
3246 }
3247
3248 if (!empty($this->_sections)) {
3249 // build the query with no LIMIT clause
3250 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select);
3251 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3252
3253 // pull section aliases out of $this->_sections
3254 $sectionAliases = array_keys($this->_sections);
3255
3256 $ifnulls = [];
3257 foreach (array_merge($sectionAliases, $this->_selectAliases) as $alias) {
3258 $ifnulls[] = "ifnull($alias, '') as $alias";
3259 }
3260 $this->_select = "SELECT " . implode(", ", $ifnulls);
3261 $this->_select = CRM_Contact_BAO_Query::appendAnyValueToSelect($ifnulls, $sectionAliases);
3262
3263 // Group (un-limited) report by all aliases and get counts. This might
3264 // be done more efficiently when the contents of $sql are known, ie. by
3265 // overriding this method in the report class.
3266
3267 $query = $this->_select .
3268 ", count(*) as ct from ($sql) as subquery group by " .
3269 implode(", ", $sectionAliases);
3270
3271 // initialize array of total counts
3272 $totals = [];
3273 $dao = CRM_Core_DAO::executeQuery($query);
3274 while ($dao->fetch()) {
3275
3276 // let $this->_alterDisplay translate any integer ids to human-readable values.
3277 $rows[0] = $dao->toArray();
3278 $this->alterDisplay($rows);
3279 $this->alterCustomDataDisplay($rows);
3280 $row = $rows[0];
3281
3282 // add totals for all permutations of section values
3283 $values = [];
3284 $i = 1;
3285 $aliasCount = count($sectionAliases);
3286 foreach ($sectionAliases as $alias) {
3287 $values[] = $row[$alias];
3288 $key = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values);
3289 if ($i == $aliasCount) {
3290 // the last alias is the lowest-level section header; use count as-is
3291 $totals[$key] = $dao->ct;
3292 }
3293 else {
3294 // other aliases are higher level; roll count into their total
3295 $totals[$key] += $dao->ct;
3296 }
3297 }
3298 }
3299 $this->assign('sectionTotals', $totals);
3300 }
3301 }
3302
3303 /**
3304 * Modify column headers.
3305 */
3306 public function modifyColumnHeaders() {
3307 // use this method to modify $this->_columnHeaders
3308 }
3309
3310 /**
3311 * Move totals columns to the right edge of the table.
3312 *
3313 * It seems like a more logical layout to have any totals columns on the far right regardless of
3314 * the location of the rest of their table.
3315 */
3316 public function moveSummaryColumnsToTheRightHandSide() {
3317 $statHeaders = (array_intersect_key($this->_columnHeaders, array_flip($this->_statFields)));
3318 $this->_columnHeaders = array_merge(array_diff_key($this->_columnHeaders, $statHeaders), $this->_columnHeaders, $statHeaders);
3319 }
3320
3321 /**
3322 * Assign rows to the template.
3323 *
3324 * @param array $rows
3325 */
3326 public function doTemplateAssignment(&$rows) {
3327 $this->assign('columnHeaders', $this->_columnHeaders);
3328 $this->assign_by_ref('rows', $rows);
3329 $this->assign('statistics', $this->statistics($rows));
3330 }
3331
3332 /**
3333 * Build report statistics.
3334 *
3335 * Override this method to build your own statistics.
3336 *
3337 * @param array $rows
3338 *
3339 * @return array
3340 */
3341 public function statistics(&$rows) {
3342 $statistics = [];
3343
3344 $count = count($rows);
3345 // Why do we increment the count for rollup seems to artificially inflate the count.
3346 // It seems perhaps intentional to include the summary row in the count of results - although
3347 // this just seems odd.
3348 if ($this->_rollup && ($this->_rollup != '') && $this->_grandFlag) {
3349 $count++;
3350 }
3351
3352 $this->countStat($statistics, $count);
3353
3354 $this->groupByStat($statistics);
3355
3356 $this->filterStat($statistics);
3357
3358 return $statistics;
3359 }
3360
3361 /**
3362 * Add count statistics.
3363 *
3364 * @param array $statistics
3365 * @param int $count
3366 */
3367 public function countStat(&$statistics, $count) {
3368 $statistics['counts']['rowCount'] = [
3369 'title' => ts('Row(s) Listed'),
3370 'value' => $count,
3371 'type' => CRM_Utils_Type::T_INT,
3372 ];
3373
3374 if ($this->_rowsFound && ($this->_rowsFound > $count)) {
3375 $statistics['counts']['rowsFound'] = [
3376 'title' => ts('Total Row(s)'),
3377 'value' => $this->_rowsFound,
3378 'type' => CRM_Utils_Type::T_INT,
3379 ];
3380 }
3381 }
3382
3383 /**
3384 * Add group by statistics.
3385 *
3386 * @param array $statistics
3387 */
3388 public function groupByStat(&$statistics) {
3389 if (!empty($this->_params['group_bys']) &&
3390 is_array($this->_params['group_bys']) &&
3391 !empty($this->_params['group_bys'])
3392 ) {
3393 foreach ($this->_columns as $tableName => $table) {
3394 if (array_key_exists('group_bys', $table)) {
3395 foreach ($table['group_bys'] as $fieldName => $field) {
3396 if (!empty($this->_params['group_bys'][$fieldName])) {
3397 $combinations[] = $field['title'];
3398 }
3399 }
3400 }
3401 }
3402 $statistics['groups'][] = [
3403 'title' => ts('Grouping(s)'),
3404 'value' => implode(' & ', $combinations),
3405 ];
3406 }
3407 else {
3408 // prevents an e-notice in statistics.tpl.
3409 $statistics['groups'] = [];
3410 }
3411 }
3412
3413 /**
3414 * Filter statistics.
3415 *
3416 * @param array $statistics
3417 */
3418 public function filterStat(&$statistics) {
3419 foreach ($this->_columns as $tableName => $table) {
3420 if (array_key_exists('filters', $table)) {
3421 foreach ($table['filters'] as $fieldName => $field) {
3422 if ((CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE ||
3423 CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_TIME) &&
3424 CRM_Utils_Array::value('operatorType', $field) !=
3425 CRM_Report_Form::OP_MONTH
3426 ) {
3427 $from = $this->_params["{$fieldName}_from"] ?? NULL;
3428 $to = $this->_params["{$fieldName}_to"] ?? NULL;
3429 if (!empty($this->_params["{$fieldName}_relative"])) {
3430 [$from, $to] = CRM_Utils_Date::getFromTo($this->_params["{$fieldName}_relative"], NULL, NULL);
3431 }
3432 if (strlen($to) === 10) {
3433 // If we just have the date we assume the end of that day.
3434 $to .= ' 23:59:59';
3435 }
3436 if ($from || $to) {
3437 if ($from) {
3438 $from = date('l j F Y, g:iA', strtotime($from));
3439 }
3440 if ($to) {
3441 $to = date('l j F Y, g:iA', strtotime($to));
3442 }
3443 $statistics['filters'][] = [
3444 'title' => $field['title'],
3445 'value' => ts("Between %1 and %2", [1 => $from, 2 => $to]),
3446 ];
3447 }
3448 elseif (in_array($rel = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params),
3449 array_keys($this->getOperationPair(CRM_Report_Form::OP_DATE))
3450 )) {
3451 $pair = $this->getOperationPair(CRM_Report_Form::OP_DATE);
3452 $statistics['filters'][] = [
3453 'title' => $field['title'],
3454 'value' => $pair[$rel],
3455 ];
3456 }
3457 }
3458 else {
3459 $op = $this->_params["{$fieldName}_op"] ?? NULL;
3460 $value = NULL;
3461 if ($op) {
3462 $pair = $this->getOperationPair(
3463 CRM_Utils_Array::value('operatorType', $field),
3464 $fieldName
3465 );
3466 $min = $this->_params["{$fieldName}_min"] ?? NULL;
3467 $max = $this->_params["{$fieldName}_max"] ?? NULL;
3468 $val = $this->_params["{$fieldName}_value"] ?? NULL;
3469 if (in_array($op, ['bw', 'nbw']) && ($min || $max)) {
3470 $value = "{$pair[$op]} $min " . ts('and') . " $max";
3471 }
3472 elseif ($val && CRM_Utils_Array::value('operatorType', $field) & self::OP_ENTITYREF) {
3473 $this->setEntityRefDefaults($field, $tableName);
3474 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
3475 ['id' => $val] +
3476 CRM_Utils_Array::value('api', $field['attributes'], []));
3477 $values = [];
3478 foreach ($result['values'] as $v) {
3479 $values[] = $v['label'];
3480 }
3481 $value = "{$pair[$op]} " . implode(', ', $values);
3482 }
3483 elseif ($op == 'nll' || $op == 'nnll') {
3484 $value = $pair[$op];
3485 }
3486 elseif (is_array($val) && (!empty($val))) {
3487 $options = CRM_Utils_Array::value('options', $field, []);
3488 foreach ($val as $key => $valIds) {
3489 if (isset($options[$valIds])) {
3490 $val[$key] = $options[$valIds];
3491 }
3492 }
3493 $pair[$op] = (count($val) == 1) ? (($op == 'notin' || $op ==
3494 'mnot') ? ts('Is Not') : ts('Is')) : CRM_Utils_Array::value($op, $pair);
3495 $val = implode(', ', $val);
3496 $value = "{$pair[$op]} " . $val;
3497 }
3498 elseif (!is_array($val) && (!empty($val) || $val == '0') &&
3499 isset($field['options']) &&
3500 is_array($field['options']) && !empty($field['options'])
3501 ) {
3502 $value = CRM_Utils_Array::value($op, $pair) . " " .
3503 CRM_Utils_Array::value($val, $field['options'], $val);
3504 }
3505 elseif ($val) {
3506 $value = CRM_Utils_Array::value($op, $pair) . " " . $val;
3507 }
3508 }
3509 if ($value && empty($field['no_display'])) {
3510 $statistics['filters'][] = [
3511 'title' => $field['title'] ?? NULL,
3512 'value' => CRM_Utils_String::htmlToText($value),
3513 ];
3514 }
3515 }
3516 }
3517 }
3518 else {
3519 // Prevents an e-notice in statistics.tpl.
3520 $statistics['filters'] = [];
3521 }
3522 }
3523 }
3524
3525 /**
3526 * End post processing.
3527 *
3528 * @param array|null $rows
3529 */
3530 public function endPostProcess(&$rows = NULL) {
3531 $this->assign('report_class', get_class($this));
3532
3533 // This is used by unit tests, where _outputMode is intentionally blank.
3534 // Is there a reason it couldn't just always do this? It effectively does
3535 // the same thing anyway by assigning it to the template (in
3536 // doTemplateAssignment()).
3537 if ($this->_storeResultSet) {
3538 $this->_resultSet = $rows;
3539 }
3540
3541 // Add contacts to group
3542 if ($this->_outputMode == 'group') {
3543 $group = $this->_params['groups'];
3544 $this->add2group($group);
3545 }
3546 else {
3547 if ($this->_sendmail) {
3548 $this->sendEmail();
3549 }
3550 elseif (!empty($this->outputHandler)) {
3551 $this->outputHandler->download();
3552 CRM_Utils_System::civiExit();
3553 }
3554 // else we don't need to do anything here since it must have been
3555 // outputMode=save or something like that
3556 }
3557 }
3558
3559 /**
3560 * Set store result set indicator to TRUE.
3561 *
3562 * This is used by unit tests, along with getResultSet(), to get just
3563 * the output rows unformatted.
3564 */
3565 public function storeResultSet() {
3566 $this->_storeResultSet = TRUE;
3567 }
3568
3569 /**
3570 * Get result set.
3571 *
3572 * @return bool
3573 */
3574 public function getResultSet() {
3575 return $this->_resultSet;
3576 }
3577
3578 /**
3579 * Get the sql used to generate the report.
3580 *
3581 * @return string
3582 */
3583 public function getReportSql() {
3584 return $this->sqlArray;
3585 }
3586
3587 /**
3588 * Use the form name to create the tpl file name.
3589 *
3590 * @return string
3591 */
3592 public function getTemplateFileName() {
3593 $defaultTpl = parent::getTemplateFileName();
3594 $template = CRM_Core_Smarty::singleton();
3595 if (!$template->template_exists($defaultTpl)) {
3596 $defaultTpl = 'CRM/Report/Form.tpl';
3597 }
3598 return $defaultTpl;
3599 }
3600
3601 /**
3602 * Compile the report content.
3603 *
3604 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3605 *
3606 * @return string
3607 */
3608 public function compileContent() {
3609 $templateFile = $this->getHookedTemplateFileName();
3610 return CRM_Utils_Array::value('report_header', $this->_formValues) .
3611 CRM_Core_Form::$_template->fetch($templateFile) .
3612 CRM_Utils_Array::value('report_footer', $this->_formValues);
3613 }
3614
3615 /**
3616 * Post process function.
3617 */
3618 public function postProcess() {
3619 // get ready with post process params
3620 $this->beginPostProcess();
3621
3622 // build query
3623 $sql = $this->buildQuery();
3624
3625 // build array of result based on column headers. This method also allows
3626 // modifying column headers before using it to build result set i.e $rows.
3627 $rows = [];
3628 $this->buildRows($sql, $rows);
3629
3630 // format result set.
3631 $this->formatDisplay($rows);
3632
3633 // assign variables to templates
3634 $this->doTemplateAssignment($rows);
3635
3636 // do print / pdf / instance stuff if needed
3637 $this->endPostProcess($rows);
3638 }
3639
3640 /**
3641 * Set limit.
3642 *
3643 * @param int|null $rowCount
3644 *
3645 * @return array
3646 */
3647 public function limit($rowCount = NULL) {
3648 $rowCount = $rowCount ?? $this->getRowCount();
3649 // lets do the pager if in html mode
3650 $this->_limit = NULL;
3651
3652 // CRM-14115, over-ride row count if rowCount is specified in URL
3653 if ($this->_dashBoardRowCount) {
3654 $rowCount = $this->_dashBoardRowCount;
3655 }
3656 if ($this->addPaging) {
3657 $this->_select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select);
3658
3659 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer');
3660
3661 // @todo all http vars should be extracted in the preProcess
3662 // - not randomly in the class
3663 if (!$pageId && !empty($_POST)) {
3664 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3665 $pageId = max((int) $_POST['crmPID_B'], 1);
3666 }
3667 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3668 $pageId = max((int) $_POST['crmPID'], 1);
3669 }
3670 unset($_POST['crmPID_B'], $_POST['crmPID']);
3671 }
3672
3673 $pageId = $pageId ? $pageId : 1;
3674 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
3675 $offset = ($pageId - 1) * $rowCount;
3676
3677 $offset = CRM_Utils_Type::escape($offset, 'Int');
3678 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
3679
3680 $this->_limit = " LIMIT $offset, $rowCount";
3681 return [$offset, $rowCount];
3682 }
3683 if ($this->_limitValue) {
3684 if ($this->_offsetValue) {
3685 $this->_limit = " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3686 }
3687 else {
3688 $this->_limit = " LIMIT " . $this->_limitValue;
3689 }
3690 }
3691 }
3692
3693 /**
3694 * Set pager.
3695 *
3696 * @param int|null $rowCount
3697 */
3698 public function setPager($rowCount = NULL) {
3699 $rowCount = $rowCount ?? $this->getRowCount();
3700 // CRM-14115, over-ride row count if rowCount is specified in URL
3701 if ($this->_dashBoardRowCount) {
3702 $rowCount = $this->_dashBoardRowCount;
3703 }
3704
3705 if ($this->_limit && ($this->_limit != '')) {
3706 if (!$this->_rowsFound) {
3707 $sql = "SELECT FOUND_ROWS();";
3708 $this->_rowsFound = CRM_Core_DAO::singleValueQuery($sql);
3709 }
3710 $params = [
3711 'total' => $this->_rowsFound,
3712 'rowCount' => $rowCount,
3713 'status' => ts('Records') . ' %%StatusMessage%%',
3714 'buttonBottom' => 'PagerBottomButton',
3715 'buttonTop' => 'PagerTopButton',
3716 ];
3717 if (!empty($this->controller)) {
3718 // This happens when being called from the api Really we want the api to be able to
3719 // pass paging parameters, but at this stage just preventing test crashes.
3720 $params['pageID'] = $this->get(CRM_Utils_Pager::PAGE_ID);
3721 }
3722
3723 $pager = new CRM_Utils_Pager($params);
3724 $this->assign_by_ref('pager', $pager);
3725 $this->ajaxResponse['totalRows'] = $this->_rowsFound;
3726 }
3727 }
3728
3729 /**
3730 * Build a group filter with contempt for large data sets.
3731 *
3732 * This function has been retained as it takes time to migrate the reports over
3733 * to the new method which will not crash on large datasets.
3734 *
3735 * @deprecated
3736 *
3737 * @param string $field
3738 * @param mixed $value
3739 * @param string $op
3740 *
3741 * @return string
3742 */
3743 public function legacySlowGroupFilterClause($field, $value, $op) {
3744 $smartGroupQuery = "";
3745
3746 $group = new CRM_Contact_DAO_Group();
3747 $group->is_active = 1;
3748 $group->find();
3749 $smartGroups = [];
3750 while ($group->fetch()) {
3751 if (in_array($group->id, (array) $this->_params['gid_value']) &&
3752 $group->saved_search_id
3753 ) {
3754 $smartGroups[] = $group->id;
3755 }
3756 }
3757
3758 CRM_Contact_BAO_GroupContactCache::check($smartGroups);
3759
3760 $smartGroupQuery = '';
3761 if (!empty($smartGroups)) {
3762 $smartGroups = implode(',', $smartGroups);
3763 $smartGroupQuery = " UNION DISTINCT
3764 SELECT DISTINCT smartgroup_contact.contact_id
3765 FROM civicrm_group_contact_cache smartgroup_contact
3766 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3767 }
3768
3769 $sqlOp = $this->getSQLOperator($op);
3770 if (!is_array($value)) {
3771 $value = [$value];
3772 }
3773 //include child groups if any
3774 $value = array_merge($value, CRM_Contact_BAO_Group::getChildGroupIds($value));
3775
3776 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3777
3778 $contactAlias = $this->_aliases['civicrm_contact'];
3779 if (!empty($this->relationType) && $this->relationType == 'b_a') {
3780 $contactAlias = $this->_aliases['civicrm_contact_b'];
3781 }
3782 return " {$contactAlias}.id {$sqlOp} (
3783 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3784 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3785 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3786 {$smartGroupQuery} ) ";
3787 }
3788
3789 /**
3790 * Build where clause for groups.
3791 *
3792 * @param string $field
3793 * @param mixed $value
3794 * @param string $op
3795 *
3796 * @return string
3797 */
3798 public function whereGroupClause($field, $value, $op) {
3799 if ($this->groupFilterNotOptimised) {
3800 return $this->legacySlowGroupFilterClause($field, $value, $op);
3801 }
3802 if ($op === 'notin') {
3803 return " group_temp_table.contact_id IS NULL ";
3804 }
3805 // We will have used an inner join instead.
3806 return "1";
3807 }
3808
3809 /**
3810 * Create a table of the contact ids included by the group filter.
3811 *
3812 * This function is called by both the api (tests) and the UI.
3813 *
3814 * @throws \CiviCRM_API3_Exception
3815 */
3816 public function buildGroupTempTable(): void {
3817 if (!empty($this->groupTempTable) || empty($this->_params['gid_value']) || $this->groupFilterNotOptimised) {
3818 return;
3819 }
3820 $this->groupTempTable = $this->createTemporaryTable('groups', 'contact_id INT', TRUE);
3821 $filteredGroups = (array) $this->_params['gid_value'];
3822 CRM_Contact_BAO_GroupContactCache::populateTemporaryTableWithContactsInGroups($filteredGroups, $this->groupTempTable);
3823 CRM_Core_DAO::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX contact_id(contact_id)");
3824 }
3825
3826 /**
3827 * Execute query and add it to the developer tab.
3828 *
3829 * @param string $query
3830 * @param array $params
3831 *
3832 * @return \CRM_Core_DAO|object
3833 */
3834 protected function executeReportQuery($query, $params = []) {
3835 $this->addToDeveloperTab($query);
3836 return CRM_Core_DAO::executeQuery($query, $params);
3837 }
3838
3839 /**
3840 * Build where clause for tags.
3841 *
3842 * @param string $field
3843 * @param mixed $value
3844 * @param string $op
3845 *
3846 * @return string
3847 */
3848 public function whereTagClause($field, $value, $op) {
3849 // not using left join in query because if any contact
3850 // belongs to more than one tag, results duplicate
3851 // entries.
3852 $sqlOp = $this->getSQLOperator($op);
3853 if (!is_array($value)) {
3854 $value = [$value];
3855 }
3856 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3857 $entity_table = $this->_tagFilterTable;
3858 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3859 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3860 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3861 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3862 }
3863
3864 /**
3865 * Generate membership organization clause.
3866 *
3867 * @param mixed $value
3868 * @param string $op SQL Operator
3869 *
3870 * @return string
3871 */
3872 public function whereMembershipOrgClause($value, $op) {
3873 $sqlOp = $this->getSQLOperator($op);
3874 if (!is_array($value)) {
3875 $value = [$value];
3876 }
3877
3878 $tmp_membership_org_sql_list = implode(', ', $value);
3879 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3880 SELECT DISTINCT mem.contact_id
3881 FROM civicrm_membership mem
3882 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3883 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3884 WHERE mt.member_of_contact_id IN (" .
3885 $tmp_membership_org_sql_list . ")
3886 AND mt.is_active = '1'
3887 AND mem_status.is_current_member = '1'
3888 AND mem_status.is_active = '1' ) ";
3889 }
3890
3891 /**
3892 * Generate Membership Type SQL Clause.
3893 *
3894 * @param mixed $value
3895 * @param string $op
3896 *
3897 * @return string
3898 * SQL query string
3899 */
3900 public function whereMembershipTypeClause($value, $op) {
3901 $sqlOp = $this->getSQLOperator($op);
3902 if (!is_array($value)) {
3903 $value = [$value];
3904 }
3905
3906 $tmp_membership_sql_list = implode(', ', $value);
3907 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3908 SELECT DISTINCT mem.contact_id
3909 FROM civicrm_membership mem
3910 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3911 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3912 WHERE mem.membership_type_id IN (" .
3913 $tmp_membership_sql_list . ")
3914 AND mt.is_active = '1'
3915 AND mem_status.is_current_member = '1'
3916 AND mem_status.is_active = '1' ) ";
3917 }
3918
3919 /**
3920 * Buld contact acl clause
3921 * @deprecated in favor of buildPermissionClause
3922 *
3923 * Note that if the buildPermissionClause function is called (which most reports do from
3924 * buildQuery then the results of this function are re-calculated and overwritten.
3925 *
3926 * @param string $tableAlias
3927 */
3928 public function buildACLClause($tableAlias = 'contact_a') {
3929 [$this->_aclFrom, $this->_aclWhere] = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
3930 }
3931
3932 /**
3933 * Build the permision clause for all entities in this report
3934 */
3935 public function buildPermissionClause() {
3936 $ret = [];
3937 foreach ($this->selectedTables() as $tableName) {
3938 $baoName = str_replace('_DAO_', '_BAO_', CRM_Core_DAO_AllCoreTables::getClassForTable($tableName));
3939 if ($baoName && class_exists($baoName) && !empty($this->_columns[$tableName]['alias'])) {
3940 $tableAlias = $this->_columns[$tableName]['alias'];
3941 $clauses = array_filter($baoName::getSelectWhereClause($tableAlias));
3942 foreach ($clauses as $field => $clause) {
3943 // Skip contact_id field if redundant
3944 if ($field != 'contact_id' || !in_array('civicrm_contact', $this->selectedTables())) {
3945 $ret["$tableName.$field"] = $clause;
3946 }
3947 }
3948 }
3949 }
3950 // Override output from buildACLClause
3951 $this->_aclFrom = NULL;
3952 $this->_aclWhere = implode(' AND ', $ret);
3953 }
3954
3955 /**
3956 * Add custom data to the columns.
3957 *
3958 * @param bool $addFields
3959 * @param array $permCustomGroupIds
3960 */
3961 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = []) {
3962 if (empty($this->_customGroupExtends)) {
3963 return;
3964 }
3965 if (!is_array($this->_customGroupExtends)) {
3966 $this->_customGroupExtends = [$this->_customGroupExtends];
3967 }
3968 $customGroupWhere = '';
3969 if (!empty($permCustomGroupIds)) {
3970 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3971 ") AND";
3972 }
3973 $sql = "
3974 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3975 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format,
3976 cf.serialize as serialize
3977 FROM civicrm_custom_group cg
3978 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3979 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
3980 {$customGroupWhere}
3981 cg.is_active = 1 AND
3982 cf.is_active = 1 AND
3983 cf.is_searchable = 1
3984 ORDER BY cg.weight, cf.weight";
3985 $customDAO = CRM_Core_DAO::executeQuery($sql);
3986
3987 $curTable = NULL;
3988 while ($customDAO->fetch()) {
3989 if ($customDAO->table_name != $curTable) {
3990 $curTable = $customDAO->table_name;
3991 $curFields = $curFilters = [];
3992
3993 // dummy dao object
3994 $this->_columns[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3995 $this->_columns[$curTable]['extends'] = $customDAO->extends;
3996 $this->_columns[$curTable]['grouping'] = $customDAO->table_name;
3997 $this->_columns[$curTable]['group_title'] = $customDAO->title;
3998
3999 foreach (['fields', 'filters', 'group_bys'] as $colKey) {
4000 if (!array_key_exists($colKey, $this->_columns[$curTable])) {
4001 $this->_columns[$curTable][$colKey] = [];
4002 }
4003 }
4004 }
4005 $fieldName = 'custom_' . $customDAO->cf_id;
4006
4007 if ($addFields) {
4008 // this makes aliasing work in favor
4009 $curFields[$fieldName] = [
4010 'name' => $customDAO->column_name,
4011 'title' => $customDAO->label,
4012 'dataType' => $customDAO->data_type,
4013 'htmlType' => $customDAO->html_type,
4014 ];
4015 }
4016 if ($this->_customGroupFilters) {
4017 // this makes aliasing work in favor
4018 $curFilters[$fieldName] = [
4019 'name' => $customDAO->column_name,
4020 'title' => $customDAO->label,
4021 'dataType' => $customDAO->data_type,
4022 'htmlType' => $customDAO->html_type,
4023 ];
4024 }
4025
4026 switch ($customDAO->data_type) {
4027 case 'Date':
4028 // filters
4029 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE;
4030 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_DATE;
4031 // CRM-6946, show time part for datetime date fields
4032 if ($customDAO->time_format) {
4033 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_TIMESTAMP;
4034 }
4035 break;
4036
4037 case 'Boolean':
4038 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT;
4039 $curFilters[$fieldName]['options'] = ['' => ts('- select -')] + CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id, [], 'search');
4040 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
4041 break;
4042
4043 case 'Int':
4044 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_INT;
4045 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
4046 break;
4047
4048 case 'Money':
4049 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
4050 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_MONEY;
4051 // Use T_FLOAT instead of T_MONEY as the money number format happens
4052 // by calling CRM_Core_BAO_CustomField::displayValue in alterCustomDataDisplay
4053 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_FLOAT;
4054 break;
4055
4056 case 'Float':
4057 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
4058 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_FLOAT;
4059 break;
4060
4061 case 'String':
4062 case 'StateProvince':
4063 case 'Country':
4064 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
4065
4066 $options = CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id, [], 'search');
4067 if ((is_array($options) && count($options) != 0) || (!is_array($options) && $options !== FALSE)) {
4068 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField::isSerialized($customDAO) ? CRM_Report_Form::OP_MULTISELECT_SEPARATOR : CRM_Report_Form::OP_MULTISELECT;
4069 $curFilters[$fieldName]['options'] = $options;
4070 }
4071 break;
4072
4073 case 'ContactReference':
4074 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
4075 $curFilters[$fieldName]['name'] = 'display_name';
4076 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4077
4078 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
4079 $curFields[$fieldName]['name'] = 'display_name';
4080 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
4081 break;
4082
4083 default:
4084 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
4085 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
4086 }
4087
4088 // CRM-19401 fix
4089 if ($customDAO->html_type == 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
4090 $options = CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id, [], 'search');
4091 if ($options !== FALSE) {
4092 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField::isSerialized($customDAO) ? CRM_Report_Form::OP_MULTISELECT_SEPARATOR : CRM_Report_Form::OP_MULTISELECT;
4093 $curFilters[$fieldName]['options'] = $options;
4094 }
4095 }
4096
4097 if (!array_key_exists('type', $curFields[$fieldName])) {
4098 $curFields[$fieldName]['type'] = CRM_Utils_Array::value('type', $curFilters[$fieldName], []);
4099 }
4100
4101 if ($addFields) {
4102 $this->_columns[$curTable]['fields'] = array_merge($this->_columns[$curTable]['fields'], $curFields);
4103 }
4104 if ($this->_customGroupFilters) {
4105 $this->_columns[$curTable]['filters'] = array_merge($this->_columns[$curTable]['filters'], $curFilters);
4106 }
4107 if ($this->_customGroupGroupBy) {
4108 $this->_columns[$curTable]['group_bys'] = array_merge($this->_columns[$curTable]['group_bys'], $curFields);
4109 }
4110 }
4111 }
4112
4113 /**
4114 * Build custom data from clause.
4115 *
4116 * @param bool $joinsForFiltersOnly
4117 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
4118 */
4119 public function customDataFrom($joinsForFiltersOnly = FALSE) {
4120 if (empty($this->_customGroupExtends)) {
4121 return;
4122 }
4123 $mapper = CRM_Core_BAO_CustomQuery::$extendsMap;
4124 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
4125 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
4126 $customTables = [];
4127 $customTablesDAO = CRM_Core_DAO::executeQuery("SELECT table_name FROM civicrm_custom_group");
4128 while ($customTablesDAO->fetch()) {
4129 $customTables[] = $customTablesDAO->table_name;
4130 }
4131
4132 foreach ($this->_columns as $table => $prop) {
4133 if (in_array($table, $customTables)) {
4134 $extendsTable = $mapper[$prop['extends']];
4135 // Check field is required for rendering the report.
4136 if ((!$this->isFieldSelected($prop)) || ($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
4137 continue;
4138 }
4139 $baseJoin = CRM_Utils_Array::value($prop['extends'], $this->_customGroupExtendsJoin, "{$this->_aliases[$extendsTable]}.id");
4140
4141 $customJoin = is_array($this->_customGroupJoin) ? $this->_customGroupJoin[$table] : $this->_customGroupJoin;
4142 $this->_from .= "
4143 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
4144 // handle for ContactReference
4145 if (array_key_exists('fields', $prop)) {
4146 foreach ($prop['fields'] as $fieldName => $field) {
4147 if (CRM_Utils_Array::value('dataType', $field) ==
4148 'ContactReference'
4149 ) {
4150 $columnName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField::getKeyID($fieldName), 'column_name');
4151 $this->_from .= "
4152 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
4153 }
4154 }
4155 }
4156 }
4157 }
4158 }
4159
4160 /**
4161 * Check if the field is selected.
4162 *
4163 * @param string $prop
4164 *
4165 * @return bool
4166 */
4167 public function isFieldSelected($prop) {
4168 if (empty($prop)) {
4169 return FALSE;
4170 }
4171
4172 if (!empty($this->_params['fields'])) {
4173 foreach (array_keys($prop['fields']) as $fieldAlias) {
4174 $customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias);
4175 if ($customFieldId) {
4176 if (array_key_exists($fieldAlias, $this->_params['fields'])) {
4177 return TRUE;
4178 }
4179
4180 //might be survey response field.
4181 if (!empty($this->_params['fields']['survey_response']) &&
4182 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
4183 ) {
4184 return TRUE;
4185 }
4186 }
4187 }
4188 }
4189
4190 if (!empty($this->_params['group_bys']) && $this->_customGroupGroupBy) {
4191 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
4192 if (array_key_exists($fieldAlias, $this->_params['group_bys']) &&
4193 CRM_Core_BAO_CustomField::getKeyID($fieldAlias)
4194 ) {
4195 return TRUE;
4196 }
4197 }
4198 }
4199
4200 if (!empty($this->_params['order_bys'])) {
4201 foreach (array_keys($prop['fields']) as $fieldAlias) {
4202 foreach ($this->_params['order_bys'] as $orderBy) {
4203 if ($fieldAlias == $orderBy['column'] &&
4204 CRM_Core_BAO_CustomField::getKeyID($fieldAlias)
4205 ) {
4206 return TRUE;
4207 }
4208 }
4209 }
4210 }
4211 return $this->isFieldFiltered($prop);
4212
4213 }
4214
4215 /**
4216 * Check if the field is used as a filter.
4217 *
4218 * @param string $prop
4219 *
4220 * @return bool
4221 */
4222 protected function isFieldFiltered($prop) {
4223 if (!empty($prop['filters']) && $this->_customGroupFilters) {
4224 foreach ($prop['filters'] as $fieldAlias => $val) {
4225 foreach ([
4226 'value',
4227 'min',
4228 'max',
4229 'relative',
4230 'from',
4231 'to',
4232 ] as $attach) {
4233 if (isset($this->_params[$fieldAlias . '_' . $attach]) &&
4234 (!empty($this->_params[$fieldAlias . '_' . $attach])
4235 || ($attach != 'relative' &&
4236 $this->_params[$fieldAlias . '_' . $attach] == '0')
4237 )
4238 ) {
4239 return TRUE;
4240 }
4241 }
4242 if (!empty($this->_params[$fieldAlias . '_op']) &&
4243 in_array($this->_params[$fieldAlias . '_op'], ['nll', 'nnll'])
4244 ) {
4245 return TRUE;
4246 }
4247 }
4248 }
4249
4250 return FALSE;
4251 }
4252
4253 /**
4254 * Check for empty order_by configurations and remove them.
4255 *
4256 * Also set template to hide them.
4257 *
4258 * @param array $formValues
4259 */
4260 public function preProcessOrderBy(&$formValues) {
4261 // Object to show/hide form elements
4262 $_showHide = new CRM_Core_ShowHideBlocks('', '');
4263
4264 $_showHide->addShow('optionField_1');
4265
4266 // Cycle through order_by options; skip any empty ones, and hide them as well
4267 $n = 1;
4268
4269 if (!empty($formValues['order_bys'])) {
4270 foreach ($formValues['order_bys'] as $order_by) {
4271 if ($order_by['column'] && $order_by['column'] != '-') {
4272 $_showHide->addShow('optionField_' . $n);
4273 $orderBys[$n] = $order_by;
4274 $n++;
4275 }
4276 }
4277 }
4278 for ($i = $n; $i <= 5; $i++) {
4279 if ($i > 1) {
4280 $_showHide->addHide('optionField_' . $i);
4281 }
4282 }
4283
4284 // overwrite order_by options with modified values
4285 if (!empty($orderBys)) {
4286 $formValues['order_bys'] = $orderBys;
4287 }
4288 else {
4289 $formValues['order_bys'] = [1 => ['column' => '-']];
4290 }
4291
4292 // assign show/hide data to template
4293 $_showHide->addToTemplate();
4294 }
4295
4296 /**
4297 * Check if table name has columns in SELECT clause.
4298 *
4299 * @param string $tableName
4300 * Name of table (index of $this->_columns array).
4301 *
4302 * @return bool
4303 */
4304 public function isTableSelected($tableName) {
4305 return in_array($tableName, $this->selectedTables());
4306 }
4307
4308 /**
4309 * Check if table name has columns in WHERE or HAVING clause.
4310 *
4311 * @param string $tableName
4312 * Name of table (index of $this->_columns array).
4313 *
4314 * @return bool
4315 */
4316 public function isTableFiltered($tableName) {
4317 // Cause the array to be generated if not previously done.
4318 if (!$this->_selectedTables && !$this->filteredTables) {
4319 $this->selectedTables();
4320 }
4321 return in_array($tableName, $this->filteredTables);
4322 }
4323
4324 /**
4325 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
4326 *
4327 * If the array is unset it will be built.
4328 *
4329 * @return array
4330 * selectedTables
4331 */
4332 public function selectedTables() {
4333 if (!$this->_selectedTables) {
4334 $orderByColumns = [];
4335 if (array_key_exists('order_bys', $this->_params) &&
4336 is_array($this->_params['order_bys'])
4337 ) {
4338 foreach ($this->_params['order_bys'] as $orderBy) {
4339 $orderByColumns[] = $orderBy['column'];
4340 }
4341 }
4342
4343 foreach ($this->_columns as $tableName => $table) {
4344 if (array_key_exists('fields', $table)) {
4345 foreach ($table['fields'] as $fieldName => $field) {
4346 if (!empty($field['required']) ||
4347 !empty($this->_params['fields'][$fieldName])
4348 ) {
4349 $this->_selectedTables[] = $tableName;
4350 break;
4351 }
4352 }
4353 }
4354 if (array_key_exists('order_bys', $table)) {
4355 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4356 if (in_array($orderByName, $orderByColumns)) {
4357 $this->_selectedTables[] = $tableName;
4358 break;
4359 }
4360 }
4361 }
4362 if (array_key_exists('filters', $table)) {
4363 foreach ($table['filters'] as $filterName => $filter) {
4364 $filterOp = $this->_params["{$filterName}_op"] ?? '';
4365 if ((isset($this->_params["{$filterName}_value"])
4366 && !CRM_Utils_System::isNull($this->_params["{$filterName}_value"]))
4367 || !empty($this->_params["{$filterName}_relative"])
4368 || $filterOp === 'nll'
4369 || $filterOp === 'nnll'
4370 ) {
4371 $this->_selectedTables[] = $tableName;
4372 $this->filteredTables[] = $tableName;
4373 break;
4374 }
4375 }
4376 }
4377 }
4378 }
4379 return $this->_selectedTables;
4380 }
4381
4382 /**
4383 * Add campaign fields.
4384 * @param string $entityTable
4385 * @param bool $groupBy
4386 * Add GroupBy? Not appropriate for detail report.
4387 * @param bool $orderBy
4388 * Add OrderBy? Not appropriate for detail report.
4389 * @param bool $filters
4390 *
4391 */
4392 public function addCampaignFields($entityTable = 'civicrm_contribution', $groupBy = FALSE, $orderBy = FALSE, $filters = TRUE) {
4393 // Check if CiviCampaign is a) enabled and b) has active campaigns
4394 $config = CRM_Core_Config::singleton();
4395 $campaignEnabled = in_array('CiviCampaign', $config->enableComponents);
4396 if ($campaignEnabled) {
4397 $getCampaigns = CRM_Campaign_BAO_Campaign::getPermissionedCampaigns(NULL, NULL, FALSE, FALSE, TRUE);
4398 // If we have a campaign, build out the relevant elements
4399 if (!empty($getCampaigns['campaigns'])) {
4400 $this->campaigns = $getCampaigns['campaigns'];
4401 asort($this->campaigns);
4402 $this->_columns[$entityTable]['fields']['campaign_id'] = ['title' => ts('Campaign'), 'default' => 'false'];
4403 if ($filters) {
4404 $this->_columns[$entityTable]['filters']['campaign_id'] = [
4405 'title' => ts('Campaign'),
4406 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
4407 'options' => $this->campaigns,
4408 'type' => CRM_Utils_Type::T_INT,
4409 ];
4410 }
4411
4412 if ($groupBy) {
4413 $this->_columns[$entityTable]['group_bys']['campaign_id'] = ['title' => ts('Campaign')];
4414 }
4415
4416 if ($orderBy) {
4417 $this->_columns[$entityTable]['order_bys']['campaign_id'] = ['title' => ts('Campaign')];
4418 }
4419 }
4420 }
4421 }
4422
4423 /**
4424 * Add address fields.
4425 *
4426 * @deprecated - use getAddressColumns which is a more accurate description
4427 * and also accepts an array of options rather than a long list
4428 *
4429 * adding address fields to construct function in reports
4430 *
4431 * @param bool $groupBy
4432 * Add GroupBy? Not appropriate for detail report.
4433 * @param bool $orderBy
4434 * Add GroupBy? Not appropriate for detail report.
4435 * @param bool $filters
4436 * @param array $defaults
4437 *
4438 * @return array
4439 * address fields for construct clause
4440 */
4441 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = ['country_id' => TRUE]) {
4442 $defaultAddressFields = [
4443 'street_address' => ts('Street Address'),
4444 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4445 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4446 'supplemental_address_3' => ts('Supplementary Address Field 3'),
4447 'street_number' => ts('Street Number'),
4448 'street_name' => ts('Street Name'),
4449 'street_unit' => ts('Street Unit'),
4450 'city' => ts('City'),
4451 'postal_code' => ts('Postal Code'),
4452 'postal_code_suffix' => ts('Postal Code Suffix'),
4453 'country_id' => ts('Country'),
4454 'state_province_id' => ts('State/Province'),
4455 'county_id' => ts('County'),
4456 ];
4457 $addressFields = [
4458 'civicrm_address' => [
4459 'dao' => 'CRM_Core_DAO_Address',
4460 'fields' => [
4461 'address_name' => [
4462 'title' => ts('Address Name'),
4463 'default' => $defaults['name'] ?? FALSE,
4464 'name' => 'name',
4465 ],
4466 ],
4467 'grouping' => 'location-fields',
4468 ],
4469 ];
4470 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4471 $addressFields['civicrm_address']['fields'][$fieldName] = [
4472 'title' => $fieldLabel,
4473 'default' => $defaults[$fieldName] ?? FALSE,
4474 ];
4475 }
4476
4477 $street_address_filters = $general_address_filters = [];
4478 if ($filters) {
4479 // Address filter depends on whether street address parsing is enabled.
4480 // (CRM-18696)
4481 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
4482 'address_options'
4483 );
4484 if ($addressOptions['street_address_parsing']) {
4485 $street_address_filters = [
4486 'street_number' => [
4487 'title' => ts('Street Number'),
4488 'type' => CRM_Utils_Type::T_INT,
4489 'name' => 'street_number',
4490 ],
4491 'street_name' => [
4492 'title' => ts('Street Name'),
4493 'name' => 'street_name',
4494 'type' => CRM_Utils_Type::T_STRING,
4495 ],
4496 ];
4497 }
4498 else {
4499 $street_address_filters = [
4500 'street_address' => [
4501 'title' => ts('Street Address'),
4502 'type' => CRM_Utils_Type::T_STRING,
4503 'name' => 'street_address',
4504 ],
4505 ];
4506 }
4507 $general_address_filters = [
4508 'postal_code' => [
4509 'title' => ts('Postal Code'),
4510 'type' => CRM_Utils_Type::T_STRING,
4511 'name' => 'postal_code',
4512 ],
4513 'city' => [
4514 'title' => ts('City'),
4515 'type' => CRM_Utils_Type::T_STRING,
4516 'name' => 'city',
4517 ],
4518 'country_id' => [
4519 'name' => 'country_id',
4520 'title' => ts('Country'),
4521 'type' => CRM_Utils_Type::T_INT,
4522 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
4523 'options' => CRM_Core_PseudoConstant::country(),
4524 ],
4525 'state_province_id' => [
4526 'name' => 'state_province_id',
4527 'title' => ts('State/Province'),
4528 'type' => CRM_Utils_Type::T_INT,
4529 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
4530 'options' => [],
4531 ],
4532 'county_id' => [
4533 'name' => 'county_id',
4534 'title' => ts('County'),
4535 'type' => CRM_Utils_Type::T_INT,
4536 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
4537 'options' => [],
4538 ],
4539 ];
4540 }
4541 $addressFields['civicrm_address']['filters'] = array_merge(
4542 $street_address_filters,
4543 $general_address_filters);
4544
4545 if ($orderBy) {
4546 $addressFields['civicrm_address']['order_bys'] = [
4547 'street_name' => ['title' => ts('Street Name')],
4548 'street_number' => ['title' => ts('Odd / Even Street Number')],
4549 'street_address' => NULL,
4550 'city' => NULL,
4551 'postal_code' => NULL,
4552 ];
4553 }
4554
4555 if ($groupBy) {
4556 $addressFields['civicrm_address']['group_bys'] = [
4557 'street_address' => NULL,
4558 'city' => NULL,
4559 'postal_code' => NULL,
4560 'state_province_id' => [
4561 'title' => ts('State/Province'),
4562 ],
4563 'country_id' => [
4564 'title' => ts('Country'),
4565 ],
4566 'county_id' => [
4567 'title' => ts('County'),
4568 ],
4569 ];
4570 }
4571 return $addressFields;
4572 }
4573
4574 /**
4575 * Do AlterDisplay processing on Address Fields.
4576 * If there are multiple address field values then
4577 * on basis of provided separator the code values are translated into respective labels
4578 *
4579 * @param array $row
4580 * @param array $rows
4581 * @param int $rowNum
4582 * @param string $baseUrl
4583 * @param string $linkText
4584 * @param string $separator
4585 *
4586 * @return bool
4587 */
4588 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText, $separator = ',') {
4589 $criteriaQueryParams = CRM_Report_Utils_Report::getPreviewCriteriaQueryParams($this->_defaults, $this->_params);
4590 $entryFound = FALSE;
4591 $columnMap = [
4592 'civicrm_address_country_id' => 'country',
4593 'civicrm_address_county_id' => 'county',
4594 'civicrm_address_state_province_id' => 'stateProvince',
4595 ];
4596 foreach ($columnMap as $fieldName => $fnName) {
4597 if (array_key_exists($fieldName, $row)) {
4598 if ($values = $row[$fieldName]) {
4599 $values = (array) explode($separator, $values);
4600 $rows[$rowNum][$fieldName] = [];
4601 $addressField = $fnName == 'stateProvince' ? 'state' : $fnName;
4602 foreach ($values as $value) {
4603 $rows[$rowNum][$fieldName][] = CRM_Core_PseudoConstant::$fnName($value);
4604 }
4605 $rows[$rowNum][$fieldName] = implode($separator, $rows[$rowNum][$fieldName]);
4606 if ($baseUrl) {
4607 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
4608 sprintf("reset=1&force=1&%s&%s_op=in&%s_value=%s",
4609 $criteriaQueryParams,
4610 str_replace('civicrm_address_', '', $fieldName),
4611 str_replace('civicrm_address_', '', $fieldName),
4612 implode(',', $values)
4613 ), $this->_absoluteUrl, $this->_id
4614 );
4615 $rows[$rowNum]["{$fieldName}_link"] = $url;
4616 $rows[$rowNum]["{$fieldName}_hover"] = ts("%1 for this %2.", [1 => $linkText, 2 => $addressField]);
4617 }
4618 }
4619 $entryFound = TRUE;
4620 }
4621 }
4622
4623 return $entryFound;
4624 }
4625
4626 /**
4627 * Do AlterDisplay processing on Address Fields.
4628 *
4629 * @param array $row
4630 * @param array $rows
4631 * @param int $rowNum
4632 * @param string $baseUrl
4633 * @param string $linkText
4634 *
4635 * @return bool
4636 */
4637 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4638 $entryFound = FALSE;
4639 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4640 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4641 $addLinks = ['gender_id' => 'Gender'];
4642 foreach (['prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language'] as $fieldName) {
4643 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4644 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4645 $rowValues = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
4646 $rowLabels = [];
4647 foreach ($rowValues as $rowValue) {
4648 if ($rowValue) {
4649 $rowLabels[] = CRM_Core_PseudoConstant::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4650 }
4651 }
4652 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4653 if ($baseUrl && ($title = CRM_Utils_Array::value($fieldName, $addLinks)) != FALSE) {
4654 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4655 }
4656 }
4657 $entryFound = TRUE;
4658 }
4659 }
4660 $yesNoFields = [
4661 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'do_not_trade', 'is_opt_out',
4662 ];
4663 foreach ($yesNoFields as $fieldName) {
4664 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4665 // Since these are essentially 'negative fields' it feels like it
4666 // makes sense to only highlight the exceptions hence no 'No'.
4667 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ? ts('Yes') : '';
4668 $entryFound = TRUE;
4669 }
4670 }
4671
4672 // Handle employer id
4673 if (array_key_exists('civicrm_contact_employer_id', $row)) {
4674 $employerId = $row['civicrm_contact_employer_id'];
4675 if ($employerId) {
4676 $rows[$rowNum]['civicrm_contact_employer_id'] = CRM_Contact_BAO_Contact::displayName($employerId);
4677 $rows[$rowNum]['civicrm_contact_employer_id_link'] = CRM_Utils_System::url('civicrm/contact/view', 'reset=1&cid=' . $employerId, $this->_absoluteUrl);
4678 $rows[$rowNum]['civicrm_contact_employer_id_hover'] = ts('View Contact Summary for Employer.');
4679 $entryFound = TRUE;
4680 }
4681 }
4682
4683 return $entryFound;
4684 }
4685
4686 /**
4687 * Adjusts dates passed in to YEAR() for fiscal year.
4688 *
4689 * @param string $fieldName
4690 *
4691 * @return string
4692 */
4693 public function fiscalYearOffset($fieldName) {
4694 $config = CRM_Core_Config::singleton();
4695 $fy = $config->fiscalYearStart;
4696 if (CRM_Utils_Array::value('yid_op', $this->_params) == 'calendar' ||
4697 ($fy['d'] == 1 && $fy['M'] == 1)
4698 ) {
4699 return "YEAR( $fieldName )";
4700 }
4701 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4702 ($fy['d'] > 1 ? (" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4703 }
4704
4705 /**
4706 * Add Address into From Table if required.
4707 *
4708 * Prefix will be added to both tables as
4709 * it is assumed you are using it to get address of a secondary contact.
4710 *
4711 * @param string $prefix
4712 * @param array $extra Additional options.
4713 * Not currently used in core but may be used in override extensions.
4714 */
4715 protected function joinAddressFromContact($prefix = '', $extra = []) {
4716 $defaults = ['primary_only' => TRUE];
4717 $params = array_merge($defaults, $extra);
4718 $addressTables = ['civicrm_address', 'civicrm_country', 'civicrm_worldregion', 'civicrm_state_province'];
4719 $isJoinRequired = $this->_addressField;
4720 foreach ($addressTables as $addressTable) {
4721 if ($this->isTableSelected($prefix . $addressTable)) {
4722 $isJoinRequired = TRUE;
4723 }
4724 }
4725 if ($isJoinRequired) {
4726 $fromJoin = "
4727 LEFT JOIN civicrm_address {$this->_aliases[$prefix . 'civicrm_address']}
4728 ON ({$this->_aliases[$prefix . 'civicrm_contact']}.id =
4729 {$this->_aliases[$prefix . 'civicrm_address']}.contact_id)";
4730 if ($params['primary_only']) {
4731 $fromJoin .= " AND
4732 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1\n";
4733 }
4734 $this->_from .= $fromJoin;
4735 }
4736 }
4737
4738 /**
4739 * Add Country into From Table if required.
4740 *
4741 * Prefix will be added to both tables as
4742 * it is assumed you are using it to get address of a secondary contact.
4743 *
4744 * @param string $prefix
4745 * @param array $extra Additional options.
4746 * Not currently used in core but may be used in override extensions.
4747 */
4748 protected function joinCountryFromAddress($prefix = '', $extra = []) {
4749 $defaults = ['primary_only' => TRUE];
4750 $params = array_merge($defaults, $extra);
4751 // include country field if country column is to be included
4752 if ($this->isTableSelected($prefix . 'civicrm_country') || $this->isTableSelected($prefix . 'civicrm_worldregion')) {
4753 if (empty($this->_aliases[$prefix . 'civicrm_country'])) {
4754 $this->_aliases[$prefix . 'civicrm_country'] = $prefix . '_report_country';
4755 }
4756 $fromJoin = "
4757 LEFT JOIN civicrm_country {$this->_aliases[$prefix . 'civicrm_country']}
4758 ON {$this->_aliases[$prefix . 'civicrm_address']}.country_id = {$this->_aliases[$prefix . 'civicrm_country']}.id";
4759 if ($params['primary_only']) {
4760 $fromJoin .= " AND
4761 {$this->_aliases[$prefix . 'civicrm_address']}.is_primary = 1 ";
4762 }
4763 $this->_from .= $fromJoin;
4764 }
4765 }
4766
4767 /**
4768 * Add Phone into From Table if required.
4769 *
4770 * Prefix will be added to both tables as
4771 * it is assumed you are using it to get address of a secondary contact.
4772 *
4773 * @param string $prefix
4774 * @param array $extra Additional options.
4775 * Not currently used in core but may be used in override extensions.
4776 */
4777 protected function joinPhoneFromContact($prefix = '', $extra = []) {
4778 $defaults = ['primary_only' => TRUE];
4779 $params = array_merge($defaults, $extra);
4780 // include phone field if phone column is to be included
4781 if ($this->isTableSelected($prefix . 'civicrm_phone')) {
4782 $fromJoin = "
4783 LEFT JOIN civicrm_phone {$this->_aliases[$prefix . 'civicrm_phone']}
4784 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_phone']}.contact_id";
4785 if ($params['primary_only']) {
4786 $fromJoin .= " AND
4787 {$this->_aliases[$prefix . 'civicrm_phone']}.is_primary = 1\n";
4788 }
4789 $this->_from .= $fromJoin;
4790 }
4791 }
4792
4793 /**
4794 * Add Email into From Table if required.
4795 *
4796 * Prefix will be added to both tables as
4797 * it is assumed you are using it to get address of a secondary contact.
4798 *
4799 * @param string $prefix
4800 * @param array $extra Additional options.
4801 * Not currently used in core but may be used in override extensions.
4802 */
4803 protected function joinEmailFromContact($prefix = '', $extra = []) {
4804 $defaults = ['primary_only' => TRUE];
4805 $params = array_merge($defaults, $extra);
4806 // include email field if email column is to be included
4807 if ($this->isTableSelected($prefix . 'civicrm_email')) {
4808 $fromJoin = "
4809 LEFT JOIN civicrm_email {$this->_aliases[$prefix . 'civicrm_email']}
4810 ON {$this->_aliases[$prefix . 'civicrm_contact']}.id = {$this->_aliases[$prefix . 'civicrm_email']}.contact_id";
4811 if ($params['primary_only']) {
4812 $fromJoin .= " AND
4813 {$this->_aliases[$prefix . 'civicrm_email']}.is_primary = 1 ";
4814 }
4815 $this->_from .= $fromJoin;
4816 }
4817 }
4818
4819 /**
4820 * Add Financial Transaction into From Table if required.
4821 */
4822 public function addFinancialTrxnFromClause() {
4823 if ($this->isTableSelected('civicrm_financial_trxn')) {
4824 $this->_from .= "
4825 LEFT JOIN civicrm_entity_financial_trxn eftcc
4826 ON ({$this->_aliases['civicrm_contribution']}.id = eftcc.entity_id AND
4827 eftcc.entity_table = 'civicrm_contribution')
4828 LEFT JOIN civicrm_financial_trxn {$this->_aliases['civicrm_financial_trxn']}
4829 ON {$this->_aliases['civicrm_financial_trxn']}.id = eftcc.financial_trxn_id \n";
4830 }
4831 }
4832
4833 /**
4834 * Get phone columns to add to array.
4835 *
4836 * @param array $options
4837 * - prefix Prefix to add to table (in case of more than one instance of the table)
4838 * - prefix_label Label to give columns from this phone table instance
4839 *
4840 * @return array
4841 * phone columns definition
4842 */
4843 public function getPhoneColumns($options = []) {
4844 $defaultOptions = [
4845 'prefix' => '',
4846 'prefix_label' => '',
4847 ];
4848
4849 $options = array_merge($defaultOptions, $options);
4850
4851 $fields = [
4852 $options['prefix'] . 'civicrm_phone' => [
4853 'dao' => 'CRM_Core_DAO_Phone',
4854 'fields' => [
4855 $options['prefix'] . 'phone' => [
4856 'title' => $options['prefix_label'] . ts('Phone'),
4857 'name' => 'phone',
4858 ],
4859 ],
4860 ],
4861 ];
4862 return $fields;
4863 }
4864
4865 /**
4866 * Get a standard set of contact fields.
4867 * @deprecated - use getColumns('Contact') instead
4868 * @return array
4869 */
4870 public function getBasicContactFields() {
4871 return [
4872 'sort_name' => [
4873 'title' => ts('Contact Name'),
4874 'required' => TRUE,
4875 'default' => TRUE,
4876 ],
4877 'id' => [
4878 'no_display' => TRUE,
4879 'required' => TRUE,
4880 ],
4881 'prefix_id' => [
4882 'title' => ts('Contact Prefix'),
4883 ],
4884 'first_name' => [
4885 'title' => ts('First Name'),
4886 ],
4887 'nick_name' => [
4888 'title' => ts('Nick Name'),
4889 ],
4890 'middle_name' => [
4891 'title' => ts('Middle Name'),
4892 ],
4893 'last_name' => [
4894 'title' => ts('Last Name'),
4895 ],
4896 'suffix_id' => [
4897 'title' => ts('Contact Suffix'),
4898 ],
4899 'source' => ['title' => ts('Contact Source')],
4900 'postal_greeting_display' => ['title' => ts('Postal Greeting')],
4901 'email_greeting_display' => ['title' => ts('Email Greeting')],
4902 'addressee_display' => ['title' => ts('Addressee')],
4903 'contact_type' => [
4904 'title' => ts('Contact Type'),
4905 ],
4906 'contact_sub_type' => [
4907 'title' => ts('Contact Subtype'),
4908 ],
4909 'gender_id' => [
4910 'title' => ts('Gender'),
4911 ],
4912 'birth_date' => [
4913 'title' => ts('Birth Date'),
4914 ],
4915 'age' => [
4916 'title' => ts('Age'),
4917 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4918 ],
4919 'job_title' => [
4920 'title' => ts('Contact Job title'),
4921 ],
4922 'organization_name' => [
4923 'title' => ts('Organization Name'),
4924 ],
4925 'external_identifier' => [
4926 'title' => ts('Contact identifier from external system'),
4927 ],
4928 'do_not_email' => [],
4929 'do_not_phone' => [],
4930 'do_not_mail' => [],
4931 'do_not_sms' => [],
4932 'do_not_trade' => [],
4933 'is_opt_out' => [],
4934 'is_deceased' => [],
4935 'preferred_language' => [],
4936 'employer_id' => [
4937 'title' => ts('Current Employer'),
4938 ],
4939 ];
4940 }
4941
4942 /**
4943 * Get a standard set of contact filters.
4944 *
4945 * @param array $defaults
4946 *
4947 * @return array
4948 */
4949 public function getBasicContactFilters($defaults = []) {
4950 return [
4951 'sort_name' => [
4952 'title' => ts('Contact Name'),
4953 ],
4954 'source' => [
4955 'title' => ts('Contact Source'),
4956 'type' => CRM_Utils_Type::T_STRING,
4957 ],
4958 'id' => [
4959 'title' => ts('Contact ID'),
4960 'no_display' => TRUE,
4961 ],
4962 'gender_id' => [
4963 'title' => ts('Gender'),
4964 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
4965 'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
4966 ],
4967 'birth_date' => [
4968 'title' => ts('Birth Date'),
4969 'operatorType' => CRM_Report_Form::OP_DATE,
4970 ],
4971 'contact_type' => [
4972 'title' => ts('Contact Type'),
4973 ],
4974 'contact_sub_type' => [
4975 'title' => ts('Contact Subtype'),
4976 ],
4977 'modified_date' => [
4978 'title' => ts('Contact Modified'),
4979 'operatorType' => CRM_Report_Form::OP_DATE,
4980 'type' => CRM_Utils_Type::T_DATE,
4981 ],
4982 'is_deceased' => [
4983 'title' => ts('Deceased'),
4984 'type' => CRM_Utils_Type::T_BOOLEAN,
4985 'default' => CRM_Utils_Array::value('deceased', $defaults, 0),
4986 ],
4987 'do_not_email' => [
4988 'title' => ts('Do not email'),
4989 'type' => CRM_Utils_Type::T_BOOLEAN,
4990 ],
4991 'do_not_phone' => [
4992 'title' => ts('Do not phone'),
4993 'type' => CRM_Utils_Type::T_BOOLEAN,
4994 ],
4995 'do_not_mail' => [
4996 'title' => ts('Do not mail'),
4997 'type' => CRM_Utils_Type::T_BOOLEAN,
4998 ],
4999 'do_not_sms' => [
5000 'title' => ts('Do not SMS'),
5001 'type' => CRM_Utils_Type::T_BOOLEAN,
5002 ],
5003 'do_not_trade' => [
5004 'title' => ts('Do not Trade'),
5005 'type' => CRM_Utils_Type::T_BOOLEAN,
5006 ],
5007 'is_opt_out' => [
5008 'title' => ts('Do not bulk email'),
5009 'type' => CRM_Utils_Type::T_BOOLEAN,
5010 ],
5011 'preferred_language' => [
5012 'title' => ts('Preferred Language'),
5013 ],
5014 'is_deleted' => [
5015 'no_display' => TRUE,
5016 'default' => 0,
5017 'type' => CRM_Utils_Type::T_BOOLEAN,
5018 ],
5019 ];
5020 }
5021
5022 /**
5023 * Add contact to group.
5024 *
5025 * @param int $groupID
5026 */
5027 public function add2group($groupID) {
5028 if (is_numeric($groupID) && isset($this->_aliases['civicrm_contact'])) {
5029 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
5030 $select = preg_replace('/SELECT(\s+SQL_CALC_FOUND_ROWS)?\s+/i', $select, $this->_select);
5031 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
5032 $sql = str_replace('WITH ROLLUP', '', $sql);
5033 if (!$this->optimisedForOnlyFullGroupBy) {
5034 CRM_Core_DAO::disableFullGroupByMode();
5035 }
5036 $dao = CRM_Core_DAO::executeQuery($sql);
5037 CRM_Core_DAO::reenableFullGroupByMode();
5038
5039 $contact_ids = [];
5040 // Add resulting contacts to group
5041 while ($dao->fetch()) {
5042 if ($dao->addtogroup_contact_id) {
5043 $contact_ids[$dao->addtogroup_contact_id] = $dao->addtogroup_contact_id;
5044 }
5045 }
5046
5047 if (!empty($contact_ids)) {
5048 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
5049 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
5050 }
5051 else {
5052 CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
5053 }
5054 }
5055 }
5056
5057 /**
5058 * Apply common settings to entityRef fields.
5059 *
5060 * @param array $field
5061 * @param string $table
5062 */
5063 public function setEntityRefDefaults(&$field, $table) {
5064 $field['attributes'] = $field['attributes'] ? $field['attributes'] : [];
5065 $field['attributes'] += [
5066 'entity' => CRM_Core_DAO_AllCoreTables::getEntityNameForTable($table),
5067 'multiple' => TRUE,
5068 'placeholder' => ts('- select -'),
5069 ];
5070 }
5071
5072 /**
5073 * Add link fields to the row.
5074 *
5075 * Function adds the _link & _hover fields to the row.
5076 *
5077 * @param array $row
5078 * @param string $baseUrl
5079 * @param string $linkText
5080 * @param string $value
5081 * @param string $fieldName
5082 * @param string $tablePrefix
5083 * @param string $fieldLabel
5084 *
5085 * @return mixed
5086 */
5087 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
5088 $criteriaQueryParams = CRM_Report_Utils_Report::getPreviewCriteriaQueryParams($this->_defaults, $this->_params);
5089 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
5090 "reset=1&force=1&{$criteriaQueryParams}&" .
5091 $fieldName . "_op=in&{$fieldName}_value={$value}",
5092 $this->_absoluteUrl, $this->_id
5093 );
5094 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
5095 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
5096 [1 => $linkText, 2 => $fieldLabel]
5097 );
5098 }
5099
5100 /**
5101 * Get label for show results buttons.
5102 *
5103 * @return string
5104 */
5105 public function getResultsLabel() {
5106 $showResultsLabel = $this->resultsDisplayed() ? ts('Refresh results') : ts('View results');
5107 return $showResultsLabel;
5108 }
5109
5110 /**
5111 * Determine the output mode from the url or input.
5112 *
5113 * Output could be
5114 * - pdf : Render as pdf
5115 * - csv : Render as csv
5116 * - print : Render in print format
5117 * - save : save the report and display the new report
5118 * - copy : save the report as a new instance and display that.
5119 * - group : go to the add to group screen.
5120 *
5121 * Potentially chart variations could also be included but the complexity
5122 * is that we might print a bar chart as a pdf.
5123 */
5124 protected function setOutputMode() {
5125 $this->_outputMode = str_replace('report_instance.', '', CRM_Utils_Request::retrieve(
5126 'output',
5127 'String',
5128 CRM_Core_DAO::$_nullObject,
5129 FALSE,
5130 CRM_Utils_Array::value('task', $this->_params)
5131 ));
5132 // if contacts are added to group
5133 if (!empty($this->_params['groups']) && empty($this->_outputMode)) {
5134 $this->_outputMode = 'group';
5135 }
5136 if (isset($this->_params['task'])) {
5137 unset($this->_params['task']);
5138 }
5139 }
5140
5141 /**
5142 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
5143 *
5144 * @param $tempTable
5145 * @param $columnName
5146 */
5147 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
5148 // add new column with date value for the datetime field
5149 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
5150 CRM_Core_DAO::executeQuery($tempQuery);
5151 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
5152 CRM_Core_DAO::executeQuery($updateQuery);
5153 $this->_selectClauses[] = "{$columnName}_date";
5154 $this->_select .= ", {$columnName}_date";
5155 $this->_sections["{$columnName}_date"] = $this->_sections["{$columnName}"];
5156 unset($this->_sections["{$columnName}"]);
5157 $this->assign('sections', $this->_sections);
5158 }
5159
5160 /**
5161 * Get an array of the columns that have been selected for display.
5162 *
5163 * @return array
5164 */
5165 public function getSelectColumns() {
5166 $selectColumns = [];
5167 foreach ($this->_columns as $tableName => $table) {
5168 if (array_key_exists('fields', $table)) {
5169 foreach ($table['fields'] as $fieldName => $field) {
5170 if (!empty($field['required']) ||
5171 !empty($this->_params['fields'][$fieldName])
5172 ) {
5173
5174 $selectColumns["{$tableName}_{$fieldName}"] = 1;
5175 }
5176 }
5177 }
5178 }
5179 return $selectColumns;
5180 }
5181
5182 /**
5183 * Add location tables to the query if they are used for filtering.
5184 *
5185 * This is for when we are running the query separately for filtering and retrieving display fields.
5186 */
5187 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
5188 if ($this->isTableFiltered('civicrm_email')) {
5189 $this->_from .= "
5190 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
5191 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
5192 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
5193 }
5194 if ($this->isTableFiltered('civicrm_phone')) {
5195 $this->_from .= "
5196 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
5197 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
5198 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
5199 }
5200 if ($this->isTableFiltered('civicrm_address')) {
5201 $this->_from .= "
5202 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
5203 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
5204 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
5205 }
5206 }
5207
5208 /**
5209 * Set the base table for the FROM clause.
5210 *
5211 * Sets up the from clause, allowing for the possibility it might be a
5212 * temp table pre-filtered by groups if a group filter is in use.
5213 *
5214 * @param string $baseTable
5215 * @param string $field
5216 * @param null $tableAlias
5217 */
5218 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
5219 if (!$tableAlias) {
5220 $tableAlias = $this->_aliases[$baseTable];
5221 }
5222 $this->_from = $this->_from = " FROM $baseTable $tableAlias ";
5223 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
5224 $this->_from .= " {$this->_aclFrom} ";
5225 }
5226
5227 /**
5228 * Join the temp table contacting contacts who are members of the filtered groups.
5229 *
5230 * If we are using an IN filter we use an inner join, otherwise a left join.
5231 *
5232 * @param string $baseTable
5233 * @param string $field
5234 * @param string $tableAlias
5235 */
5236 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
5237 if ($this->groupTempTable) {
5238 if ($this->_params['gid_op'] == 'in') {
5239 $this->_from = " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
5240 ON group_temp_table.contact_id = $tableAlias.{$field} ";
5241 }
5242 else {
5243 $this->_from .= "
5244 LEFT JOIN $this->groupTempTable group_temp_table
5245 ON $tableAlias.{$field} = group_temp_table.contact_id ";
5246 }
5247 }
5248 }
5249
5250 /**
5251 * Get all labels for fields that are used in a group concat.
5252 *
5253 * @param string $options
5254 * comma separated option values.
5255 * @param string $baoName
5256 * The BAO name for the field.
5257 * @param string $fieldName
5258 * The name of the field for which labels should be retrieved.
5259 *
5260 * return string
5261 */
5262 public function getLabels($options, $baoName, $fieldName) {
5263 $types = explode(',', $options);
5264 $labels = [];
5265 foreach ($types as $value) {
5266 $labels[$value] = CRM_Core_PseudoConstant::getLabel($baoName, $fieldName, $value);
5267 }
5268 return implode(', ', array_filter($labels));
5269 }
5270
5271 /**
5272 * Add statistics columns.
5273 *
5274 * If a group by is in play then add columns for the statistics fields.
5275 *
5276 * This would lead to a new field in the $row such as $fieldName_sum and a new, matching
5277 * column header field.
5278 *
5279 * @param array $field
5280 * @param string $tableName
5281 * @param string $fieldName
5282 * @param array $select
5283 *
5284 * @return array
5285 */
5286 protected function addStatisticsToSelect($field, $tableName, $fieldName, $select) {
5287 foreach ($field['statistics'] as $stat => $label) {
5288 $alias = "{$tableName}_{$fieldName}_{$stat}";
5289 switch (strtolower($stat)) {
5290 case 'max':
5291 case 'sum':
5292 $select[] = "$stat({$field['dbAlias']}) as $alias";
5293 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5294 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5295 $this->_statFields[$label] = $alias;
5296 $this->_selectAliases[] = $alias;
5297 break;
5298
5299 case 'count':
5300 $select[] = "COUNT({$field['dbAlias']}) as $alias";
5301 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5302 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
5303 $this->_statFields[$label] = $alias;
5304 $this->_selectAliases[] = $alias;
5305 break;
5306
5307 case 'count_distinct':
5308 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
5309 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5310 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
5311 $this->_statFields[$label] = $alias;
5312 $this->_selectAliases[] = $alias;
5313 break;
5314
5315 case 'avg':
5316 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
5317 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
5318 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
5319 $this->_statFields[$label] = $alias;
5320 $this->_selectAliases[] = $alias;
5321 break;
5322 }
5323 }
5324 return $select;
5325 }
5326
5327 /**
5328 * Add a basic field to the select clause.
5329 *
5330 * @param string $tableName
5331 * @param string $fieldName
5332 * @param array $field
5333 * @param string $select
5334 * @return array
5335 */
5336 protected function addBasicFieldToSelect($tableName, $fieldName, $field, $select) {
5337 $alias = "{$tableName}_{$fieldName}";
5338 $select[] = "{$field['dbAlias']} as $alias";
5339 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $field['title'] ?? NULL;
5340 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = $field['type'] ?? NULL;
5341 $this->_selectAliases[] = $alias;
5342 return $select;
5343 }
5344
5345 /**
5346 * Set table alias.
5347 *
5348 * @param array $table
5349 * @param string $tableName
5350 *
5351 * @return string
5352 * Alias for table.
5353 */
5354 protected function setTableAlias($table, $tableName) {
5355 if (!isset($table['alias'])) {
5356 $this->_columns[$tableName]['alias'] = substr($tableName, 8) .
5357 '_civireport';
5358 }
5359 else {
5360 $this->_columns[$tableName]['alias'] = $table['alias'] . '_civireport';
5361 }
5362
5363 $this->_aliases[$tableName] = $this->_columns[$tableName]['alias'];
5364 return $this->_aliases[$tableName];
5365 }
5366
5367 /**
5368 * Function to add columns to reports.
5369 *
5370 * This is ported from extended reports, which also adds join filters to the options.
5371 *
5372 * @param string $type
5373 * @param array $options
5374 * - prefix - A string to prepend to the table name
5375 * - prefix_label A string to prepend to the fields
5376 * - fields (bool) - should the fields for this table be made available
5377 * - group_by (bool) - should the group bys for this table be made available.
5378 * - order_by (bool) - should the group bys for this table be made available.
5379 * - filters (bool) - should the filters for this table by made available.
5380 * - fields_defaults (array) array of fields that should be displayed by default.
5381 * - filters_defaults (array) array of fields that should be filtered by default.
5382 * - join_filters (array) fields available for filtering joins (requires additional custom code).
5383 * - join_fields (array) fields available from join (requires additional custom code).
5384 * - group_by_defaults (array) array of group bys that should be applied by default.
5385 * - order_by_defaults (array) array of order bys that should be applied by default.
5386 * - custom_fields (array) array of entity types for custom fields (not usually required).
5387 * - contact_type (string) optional restriction on contact type for some tables.
5388 * - fields_excluded (array) fields that are in the generic set for the table but not in the report.
5389 *
5390 * @return array
5391 */
5392 protected function getColumns($type, $options = []) {
5393 $defaultOptions = [
5394 'prefix' => '',
5395 'prefix_label' => '',
5396 'fields' => TRUE,
5397 'group_bys' => FALSE,
5398 'order_bys' => TRUE,
5399 'filters' => TRUE,
5400 'join_filters' => FALSE,
5401 'fields_defaults' => [],
5402 'filters_defaults' => [],
5403 'group_bys_defaults' => [],
5404 'order_bys_defaults' => [],
5405 ];
5406 $options = array_merge($defaultOptions, $options);
5407
5408 $fn = 'get' . $type . 'Columns';
5409 return $this->$fn($options);
5410 }
5411
5412 /**
5413 * Get columns for contact table.
5414 *
5415 * @param array $options
5416 *
5417 * @return array
5418 */
5419 protected function getContactColumns($options = []) {
5420 $defaultOptions = [
5421 'custom_fields' => ['Individual', 'Contact', 'Organization'],
5422 'fields_defaults' => ['display_name', 'id'],
5423 'order_bys_defaults' => ['sort_name ASC'],
5424 'contact_type' => NULL,
5425 ];
5426
5427 $options = array_merge($defaultOptions, $options);
5428
5429 $tableAlias = $options['prefix'] . 'contact';
5430
5431 $spec = [
5432 $options['prefix'] . 'display_name' => [
5433 'name' => 'display_name',
5434 'title' => $options['prefix_label'] . ts('Contact Name'),
5435 'is_fields' => TRUE,
5436 ],
5437 $options['prefix'] . 'sort_name' => [
5438 'name' => 'sort_name',
5439 'title' => $options['prefix_label'] . ts('Contact Name (in sort format)'),
5440 'is_fields' => TRUE,
5441 'is_filters' => TRUE,
5442 'is_order_bys' => TRUE,
5443 ],
5444 $options['prefix'] . 'id' => [
5445 'name' => 'id',
5446 'title' => $options['prefix_label'] . ts('Contact ID'),
5447 'alter_display' => 'alterContactID',
5448 'type' => CRM_Utils_Type::T_INT,
5449 'is_order_bys' => TRUE,
5450 'is_group_bys' => TRUE,
5451 'is_fields' => TRUE,
5452 'is_filters' => TRUE,
5453 ],
5454 $options['prefix'] . 'external_identifier' => [
5455 'name' => 'external_identifier',
5456 'title' => $options['prefix_label'] . ts('External ID'),
5457 'type' => CRM_Utils_Type::T_INT,
5458 'is_fields' => TRUE,
5459 ],
5460 $options['prefix'] . 'contact_type' => [
5461 'title' => $options['prefix_label'] . ts('Contact Type'),
5462 'name' => 'contact_type',
5463 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
5464 'options' => CRM_Contact_BAO_Contact::buildOptions('contact_type'),
5465 'is_fields' => TRUE,
5466 'is_filters' => TRUE,
5467 'is_group_bys' => TRUE,
5468 ],
5469 $options['prefix'] . 'contact_sub_type' => [
5470 'title' => $options['prefix_label'] . ts('Contact Sub Type'),
5471 'name' => 'contact_sub_type',
5472 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
5473 'options' => CRM_Contact_BAO_Contact::buildOptions('contact_sub_type'),
5474 'is_fields' => TRUE,
5475 'is_filters' => TRUE,
5476 'is_group_bys' => TRUE,
5477 ],
5478 $options['prefix'] . 'is_deleted' => [
5479 'title' => $options['prefix_label'] . ts('Is deleted'),
5480 'name' => 'is_deleted',
5481 'type' => CRM_Utils_Type::T_BOOLEAN,
5482 'is_fields' => FALSE,
5483 'is_filters' => TRUE,
5484 'is_group_bys' => FALSE,
5485 ],
5486 $options['prefix'] . 'external_identifier' => [
5487 'title' => $options['prefix_label'] . ts('Contact identifier from external system'),
5488 'name' => 'external_identifier',
5489 'is_fields' => TRUE,
5490 'is_filters' => FALSE,
5491 'is_group_bys' => FALSE,
5492 'is_order_bys' => TRUE,
5493 ],
5494 $options['prefix'] . 'preferred_language' => [
5495 'title' => $options['prefix_label'] . ts('Preferred Language'),
5496 'name' => 'preferred_language',
5497 'is_fields' => TRUE,
5498 'is_filters' => TRUE,
5499 'is_group_bys' => TRUE,
5500 'is_order_bys' => TRUE,
5501 ],
5502 $options['prefix'] . 'preferred_communication_method' => [
5503 'title' => $options['prefix_label'] . ts('Preferred Communication Method'),
5504 'alter_display' => 'alterCommunicationtMethod',
5505 'name' => 'preferred_communication_method',
5506 'is_fields' => TRUE,
5507 'is_filters' => FALSE,
5508 'is_group_bys' => FALSE,
5509 'is_order_bys' => FALSE,
5510 ],
5511 ];
5512 foreach ([
5513 'postal_greeting_display' => 'Postal Greeting',
5514 'email_greeting_display' => 'Email Greeting',
5515 'addressee_display' => 'Addressee',
5516 ] as $field => $title) {
5517 $spec[$options['prefix'] . $field] = [
5518 'title' => $options['prefix_label'] . ts($title),
5519 'name' => $field,
5520 'is_fields' => TRUE,
5521 'is_filters' => FALSE,
5522 'is_group_bys' => FALSE,
5523 ];
5524 }
5525 foreach (['do_not_email', 'do_not_phone', 'do_not_mail', 'do_not_sms', 'do_not_trade', 'is_opt_out'] as $field) {
5526 $spec[$options['prefix'] . $field] = [
5527 'name' => $field,
5528 'type' => CRM_Utils_Type::T_BOOLEAN,
5529 'is_fields' => TRUE,
5530 'is_filters' => TRUE,
5531 'is_group_bys' => FALSE,
5532 ];
5533 }
5534 $individualFields = [
5535 $options['prefix'] . 'first_name' => [
5536 'name' => 'first_name',
5537 'title' => $options['prefix_label'] . ts('First Name'),
5538 'is_fields' => TRUE,
5539 'is_filters' => TRUE,
5540 'is_order_bys' => TRUE,
5541 ],
5542 $options['prefix'] . 'middle_name' => [
5543 'name' => 'middle_name',
5544 'title' => $options['prefix_label'] . ts('Middle Name'),
5545 'is_fields' => TRUE,
5546 ],
5547 $options['prefix'] . 'last_name' => [
5548 'name' => 'last_name',
5549 'title' => $options['prefix_label'] . ts('Last Name'),
5550 'default_order' => 'ASC',
5551 'is_fields' => TRUE,
5552 ],
5553 $options['prefix'] . 'nick_name' => [
5554 'name' => 'nick_name',
5555 'title' => $options['prefix_label'] . ts('Nick Name'),
5556 'is_fields' => TRUE,
5557 ],
5558 $options['prefix'] . 'prefix_id' => [
5559 'name' => 'prefix_id',
5560 'title' => $options['prefix_label'] . ts('Prefix'),
5561 'options' => CRM_Contact_BAO_Contact::buildOptions('prefix_id'),
5562 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
5563 'is_fields' => TRUE,
5564 'is_filters' => TRUE,
5565 ],
5566 $options['prefix'] . 'suffix_id' => [
5567 'name' => 'suffix_id',
5568 'title' => $options['prefix_label'] . ts('Suffix'),
5569 'options' => CRM_Contact_BAO_Contact::buildOptions('suffix_id'),
5570 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
5571 'is_fields' => TRUE,
5572 'is_filters' => TRUE,
5573 ],
5574 $options['prefix'] . 'gender_id' => [
5575 'name' => 'gender_id',
5576 'title' => $options['prefix_label'] . ts('Gender'),
5577 'options' => CRM_Contact_BAO_Contact::buildOptions('gender_id'),
5578 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
5579 'is_fields' => TRUE,
5580 'is_filters' => TRUE,
5581 ],
5582 'birth_date' => [
5583 'title' => $options['prefix_label'] . ts('Birth Date'),
5584 'operatorType' => CRM_Report_Form::OP_DATE,
5585 'type' => CRM_Utils_Type::T_DATE,
5586 'is_fields' => TRUE,
5587 'is_filters' => TRUE,
5588 ],
5589 'age' => [
5590 'title' => $options['prefix_label'] . ts('Age'),
5591 'dbAlias' => 'TIMESTAMPDIFF(YEAR, ' . $tableAlias . '_civireport.birth_date, CURDATE())',
5592 'type' => CRM_Utils_Type::T_INT,
5593 'is_fields' => TRUE,
5594 ],
5595 $options['prefix'] . 'is_deceased' => [
5596 'title' => $options['prefix_label'] . ts('Is deceased'),
5597 'name' => 'is_deceased',
5598 'type' => CRM_Utils_Type::T_BOOLEAN,
5599 'is_fields' => FALSE,
5600 'is_filters' => TRUE,
5601 'is_group_bys' => FALSE,
5602 ],
5603 $options['prefix'] . 'job_title' => [
5604 'name' => 'job_title',
5605 'is_fields' => TRUE,
5606 'is_filters' => FALSE,
5607 'is_group_bys' => FALSE,
5608 ],
5609 $options['prefix'] . 'employer_id' => [
5610 'title' => $options['prefix_label'] . ts('Current Employer'),
5611 'type' => CRM_Utils_Type::T_INT,
5612 'name' => 'employer_id',
5613 'is_fields' => TRUE,
5614 'is_filters' => FALSE,
5615 'is_group_bys' => TRUE,
5616 ],
5617 ];
5618 if (!$options['contact_type'] || $options['contact_type'] === 'Individual') {
5619 $spec = array_merge($spec, $individualFields);
5620 }
5621
5622 if (!empty($options['custom_fields'])) {
5623 $this->_customGroupExtended[$options['prefix'] . 'civicrm_contact'] = [
5624 'extends' => $options['custom_fields'],
5625 'title' => $options['prefix_label'],
5626 'filters' => $options['filters'],
5627 'prefix' => $options['prefix'],
5628 'prefix_label' => $options['prefix_label'],
5629 ];
5630 }
5631
5632 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_contact', 'CRM_Contact_DAO_Contact', $tableAlias, $this->getDefaultsFromOptions($options), $options);
5633 }
5634
5635 /**
5636 * Get address columns to add to array.
5637 *
5638 * @param array $options
5639 * - prefix Prefix to add to table (in case of more than one instance of the table)
5640 * - prefix_label Label to give columns from this address table instance
5641 * - group_bys enable these fields for group by - default false
5642 * - order_bys enable these fields for order by
5643 * - filters enable these fields for filtering
5644 *
5645 * @return array address columns definition
5646 */
5647 protected function getAddressColumns($options = []) {
5648 $defaultOptions = [
5649 'prefix' => '',
5650 'prefix_label' => '',
5651 'fields' => TRUE,
5652 'group_bys' => FALSE,
5653 'order_bys' => TRUE,
5654 'filters' => TRUE,
5655 'join_filters' => FALSE,
5656 'fields_defaults' => [],
5657 'filters_defaults' => [],
5658 'group_bys_defaults' => [],
5659 'order_bys_defaults' => [],
5660 ];
5661
5662 $options = array_merge($defaultOptions, $options);
5663 $defaults = $this->getDefaultsFromOptions($options);
5664 $tableAlias = $options['prefix'] . 'address';
5665
5666 $spec = [
5667 $options['prefix'] . 'name' => [
5668 'title' => $options['prefix_label'] . ts('Address Name'),
5669 'name' => 'name',
5670 'is_fields' => TRUE,
5671 ],
5672 $options['prefix'] . 'street_number' => [
5673 'name' => 'street_number',
5674 'title' => $options['prefix_label'] . ts('Street Number'),
5675 'type' => 1,
5676 'is_fields' => TRUE,
5677 ],
5678 $options['prefix'] . 'odd_street_number' => [
5679 'title' => ts('Odd / Even Street Number'),
5680 'name' => 'odd_street_number',
5681 'type' => CRM_Utils_Type::T_INT,
5682 'no_display' => TRUE,
5683 'required' => TRUE,
5684 'dbAlias' => "({$tableAlias}_civireport.street_number % 2)",
5685 'is_fields' => TRUE,
5686 'is_order_bys' => TRUE,
5687 ],
5688 $options['prefix'] . 'street_name' => [
5689 'name' => 'street_name',
5690 'title' => $options['prefix_label'] . ts('Street Name'),
5691 'type' => 1,
5692 'is_fields' => TRUE,
5693 'is_filters' => TRUE,
5694 'operator' => 'like',
5695 'is_order_bys' => TRUE,
5696 ],
5697 $options['prefix'] . 'street_address' => [
5698 'title' => $options['prefix_label'] . ts('Street Address'),
5699 'name' => 'street_address',
5700 'is_fields' => TRUE,
5701 'is_filters' => TRUE,
5702 'is_group_bys' => TRUE,
5703 ],
5704 $options['prefix'] . 'supplemental_address_1' => [
5705 'title' => $options['prefix_label'] . ts('Supplementary Address Field 1'),
5706 'name' => 'supplemental_address_1',
5707 'is_fields' => TRUE,
5708 ],
5709 $options['prefix'] . 'supplemental_address_2' => [
5710 'title' => $options['prefix_label'] . ts('Supplementary Address Field 2'),
5711 'name' => 'supplemental_address_2',
5712 'is_fields' => TRUE,
5713 ],
5714 $options['prefix'] . 'supplemental_address_3' => [
5715 'title' => $options['prefix_label'] . ts('Supplementary Address Field 3'),
5716 'name' => 'supplemental_address_3',
5717 'is_fields' => TRUE,
5718 ],
5719 $options['prefix'] . 'street_number' => [
5720 'name' => 'street_number',
5721 'title' => $options['prefix_label'] . ts('Street Number'),
5722 'type' => 1,
5723 'is_order_bys' => TRUE,
5724 'is_filters' => TRUE,
5725 'is_fields' => TRUE,
5726 ],
5727 $options['prefix'] . 'street_unit' => [
5728 'name' => 'street_unit',
5729 'title' => $options['prefix_label'] . ts('Street Unit'),
5730 'type' => 1,
5731 'is_fields' => TRUE,
5732 ],
5733 $options['prefix'] . 'city' => [
5734 'title' => $options['prefix_label'] . ts('City'),
5735 'name' => 'city',
5736 'operator' => 'like',
5737 'is_fields' => TRUE,
5738 'is_filters' => TRUE,
5739 'is_group_bys' => TRUE,
5740 'is_order_bys' => TRUE,
5741 ],
5742 $options['prefix'] . 'postal_code' => [
5743 'title' => $options['prefix_label'] . ts('Postal Code'),
5744 'name' => 'postal_code',
5745 'type' => 2,
5746 'is_fields' => TRUE,
5747 'is_filters' => TRUE,
5748 'is_group_bys' => TRUE,
5749 'is_order_bys' => TRUE,
5750 ],
5751 $options['prefix'] . 'postal_code_suffix' => [
5752 'title' => $options['prefix_label'] . ts('Postal Code Suffix'),
5753 'name' => 'postal_code_suffix',
5754 'type' => 2,
5755 'is_fields' => TRUE,
5756 'is_filters' => TRUE,
5757 'is_group_bys' => TRUE,
5758 'is_order_bys' => TRUE,
5759 ],
5760 $options['prefix'] . 'county_id' => [
5761 'title' => $options['prefix_label'] . ts('County'),
5762 'alter_display' => 'alterCountyID',
5763 'name' => 'county_id',
5764 'type' => CRM_Utils_Type::T_INT,
5765 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
5766 'options' => CRM_Core_PseudoConstant::county(),
5767 'is_fields' => TRUE,
5768 'is_filters' => TRUE,
5769 'is_group_bys' => TRUE,
5770 ],
5771 $options['prefix'] . 'state_province_id' => [
5772 'title' => $options['prefix_label'] . ts('State/Province'),
5773 'alter_display' => 'alterStateProvinceID',
5774 'name' => 'state_province_id',
5775 'type' => CRM_Utils_Type::T_INT,
5776 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
5777 'options' => CRM_Core_PseudoConstant::stateProvince(),
5778 'is_fields' => TRUE,
5779 'is_filters' => TRUE,
5780 'is_group_bys' => TRUE,
5781 ],
5782 $options['prefix'] . 'country_id' => [
5783 'title' => $options['prefix_label'] . ts('Country'),
5784 'alter_display' => 'alterCountryID',
5785 'name' => 'country_id',
5786 'is_fields' => TRUE,
5787 'is_filters' => TRUE,
5788 'is_group_bys' => TRUE,
5789 'type' => CRM_Utils_Type::T_INT,
5790 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
5791 'options' => CRM_Core_PseudoConstant::country(),
5792 ],
5793 $options['prefix'] . 'location_type_id' => [
5794 'name' => 'location_type_id',
5795 'title' => $options['prefix_label'] . ts('Location Type'),
5796 'type' => CRM_Utils_Type::T_INT,
5797 'is_fields' => TRUE,
5798 'alter_display' => 'alterLocationTypeID',
5799 ],
5800 $options['prefix'] . 'id' => [
5801 'title' => $options['prefix_label'] . ts('ID'),
5802 'name' => 'id',
5803 'is_fields' => TRUE,
5804 ],
5805 $options['prefix'] . 'is_primary' => [
5806 'name' => 'is_primary',
5807 'title' => $options['prefix_label'] . ts('Primary Address?'),
5808 'type' => CRM_Utils_Type::T_BOOLEAN,
5809 'is_fields' => TRUE,
5810 ],
5811 ];
5812 return $this->buildColumns($spec, $options['prefix'] . 'civicrm_address', 'CRM_Core_DAO_Address', $tableAlias, $defaults, $options);
5813 }
5814
5815 /**
5816 * Build the columns.
5817 *
5818 * The normal report class needs you to remember to do a few things that are often erratic
5819 *
5820 * 1) use a unique key for any field that might not be unique (e.g. start date, label)
5821 * - this class will prepend an alias to the key & set the 'name' if you don't set it yourself.
5822 * You can suppress the alias with 'no_field_disambiguation' if transitioning existing reports. This
5823 * means any saved filters / fields on saved report instances. This will mean that matching names from
5824 * different tables may be ambigious, but it will smooth any code transition.
5825 * - note that it assumes the value being passed in is the actual table field name
5826 *
5827 * 2) set the field & set it to no display if you don't want the field but you might want to use the field in other
5828 * contexts - the code looks up the fields array for data - so it both defines the field spec & the fields you want to show
5829 *
5830 * 3) this function also sets the 'metadata' array - the extended report class now uses this in place
5831 * of the fields array to reduce the issues caused when metadata is needed but 'fields' are not defined. Code in
5832 * the core classes can start to move towards that.
5833 *
5834 * @param array $specs
5835 * @param string $tableName
5836 * @param string $daoName
5837 * @param string $tableAlias
5838 * @param array $defaults
5839 * @param array $options
5840 *
5841 * @return array
5842 */
5843 protected function buildColumns($specs, $tableName, $daoName = NULL, $tableAlias = NULL, $defaults = [], $options = []) {
5844 if (!$tableAlias) {
5845 $tableAlias = str_replace('civicrm_', '', $tableName);
5846 }
5847 $types = ['filters', 'group_bys', 'order_bys', 'join_filters'];
5848 $columns = [$tableName => array_fill_keys($types, [])];
5849 // The code that uses this no longer cares if it is a DAO or BAO so just call it a DAO.
5850 $columns[$tableName]['dao'] = $daoName;
5851 $columns[$tableName]['alias'] = $tableAlias;
5852
5853 foreach ($specs as $specName => $spec) {
5854 if (empty($spec['name'])) {
5855 $spec['name'] = $specName;
5856 }
5857
5858 $fieldAlias = (empty($options['no_field_disambiguation']) ? $tableAlias . '_' : '') . $specName;
5859 $columns[$tableName]['metadata'][$fieldAlias] = $spec;
5860 $columns[$tableName]['fields'][$fieldAlias] = $spec;
5861 if (isset($defaults['fields_defaults']) && in_array($spec['name'], $defaults['fields_defaults'])) {
5862 $columns[$tableName]['fields'][$fieldAlias]['default'] = TRUE;
5863 }
5864
5865 if (!$spec['is_fields'] || (isset($options['fields_excluded']) && in_array($specName, $options['fields_excluded']))) {
5866 $columns[$tableName]['fields'][$fieldAlias]['no_display'] = TRUE;
5867 }
5868
5869 if (isset($options['fields_required']) && in_array($specName, $options['fields_required'])) {
5870 $columns[$tableName]['fields'][$fieldAlias]['required'] = TRUE;
5871 }
5872
5873 foreach ($types as $type) {
5874 if ($options[$type] && !empty($spec['is_' . $type])) {
5875 $columns[$tableName][$type][$fieldAlias] = $spec;
5876 if (isset($defaults[$type . '_defaults']) && isset($defaults[$type . '_defaults'][$spec['name']])) {
5877 $columns[$tableName][$type][$fieldAlias]['default'] = $defaults[$type . '_defaults'][$spec['name']];
5878 }
5879 }
5880 }
5881 }
5882 if (isset($options['grouping'])) {
5883 $columns[$tableName]['grouping'] = $options['grouping'];
5884 $columns[$tableName]['group_title'] = $options['group_title'] ?? '';
5885 }
5886 return $columns;
5887 }
5888
5889 /**
5890 * Store group bys into array - so we can check elsewhere what is grouped.
5891 */
5892 protected function storeGroupByArray() {
5893
5894 if (empty($this->_params['group_bys'])
5895 || !is_array($this->_params['group_bys'])) {
5896 $this->_params['group_bys'] = [];
5897 }
5898
5899 foreach ($this->_columns as $tableName => $table) {
5900 $table = $this->_columns[$tableName];
5901 if (array_key_exists('group_bys', $table)) {
5902 foreach ($table['group_bys'] as $fieldName => $fieldData) {
5903 $field = $this->_columns[$tableName]['metadata'][$fieldName];
5904 if (!empty($this->_params['group_bys'][$fieldName]) || !empty($fieldData['required'])) {
5905 if (!empty($field['chart'])) {
5906 $this->assign('chartSupported', TRUE);
5907 }
5908
5909 if (!empty($table['group_bys'][$fieldName]['frequency']) &&
5910 !empty($this->_params['group_bys_freq'][$fieldName])
5911 ) {
5912
5913 switch ($this->_params['group_bys_freq'][$fieldName]) {
5914 case 'FISCALYEAR':
5915 $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = self::fiscalYearOffset($field['dbAlias']);
5916 break;
5917
5918 case 'YEAR':
5919 $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = " YEAR({$field['dbAlias']})";
5920 break;
5921
5922 case 'QUARTER':
5923 $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = "YEAR({$field['dbAlias']}), QUARTER({$field['dbAlias']})";
5924 break;
5925
5926 case 'YEARWEEK':
5927 $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = "YEARWEEK({$field['dbAlias']})";
5928 break;
5929
5930 case 'MONTH':
5931 $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = "EXTRACT(YEAR_MONTH FROM {$field['dbAlias']})";
5932 break;
5933
5934 case 'DATE':
5935 $this->_groupByArray[$tableName . '_' . $fieldName . '_start'] = "DATE({$field['dbAlias']})";
5936 break;
5937 }
5938 }
5939 else {
5940 if (!in_array($field['dbAlias'], $this->_groupByArray)) {
5941 $this->_groupByArray[$tableName . '_' . $fieldName] = $field['dbAlias'];
5942 }
5943 }
5944 }
5945 }
5946
5947 }
5948 }
5949 }
5950
5951 /**
5952 * @param $options
5953 *
5954 * @return array
5955 */
5956 protected function getDefaultsFromOptions($options) {
5957 $defaults = [
5958 'fields_defaults' => $options['fields_defaults'],
5959 'filters_defaults' => $options['filters_defaults'],
5960 'group_bys_defaults' => $options['group_bys_defaults'],
5961 'order_bys_defaults' => $options['order_bys_defaults'],
5962 ];
5963 return $defaults;
5964 }
5965
5966 /**
5967 * Get the select clause for a field, wrapping in GROUP_CONCAT if appropriate.
5968 *
5969 * Full group by mode dictates that a field must either be in the group by function or
5970 * wrapped in a aggregate function. Here we wrap the field in GROUP_CONCAT if it is not in the
5971 * group concat.
5972 *
5973 * @param string $tableName
5974 * @param string $fieldName
5975 * @param string $field
5976 * @return string
5977 */
5978 protected function getSelectClauseWithGroupConcatIfNotGroupedBy($tableName, &$fieldName, &$field) {
5979 if ($this->groupConcatTested && (!empty($this->_groupByArray) || $this->isForceGroupBy)) {
5980 if ((empty($field['statistics']) || in_array('GROUP_CONCAT', $field['statistics']))) {
5981 $label = $field['title'] ?? NULL;
5982 $alias = $field['tplField'] ?? "{$tableName}_{$fieldName}";
5983 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = $label;
5984 $this->_selectAliases[] = $alias;
5985 if (empty($this->_groupByArray[$tableName . '_' . $fieldName])) {
5986 return "GROUP_CONCAT(DISTINCT {$field['dbAlias']}) as $alias";
5987 }
5988 return "({$field['dbAlias']}) as $alias";
5989 }
5990 }
5991 }
5992
5993 /**
5994 * Generate clause for the selected filter.
5995 *
5996 * @param array $field
5997 * Field specification
5998 * @param string $fieldName
5999 * Field name.
6000 *
6001 * @return string
6002 * Relevant where clause.
6003 */
6004 protected function generateFilterClause($field, $fieldName) {
6005 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
6006 if (CRM_Utils_Array::value('operatorType', $field) ==
6007 CRM_Report_Form::OP_MONTH
6008 ) {
6009 $op = $this->_params["{$fieldName}_op"] ?? NULL;
6010 $value = $this->_params["{$fieldName}_value"] ?? NULL;
6011 if (is_array($value) && !empty($value)) {
6012 return "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
6013 '))';
6014 }
6015 }
6016 else {
6017 $relative = $this->_params["{$fieldName}_relative"] ?? NULL;
6018 $from = $this->_params["{$fieldName}_from"] ?? NULL;
6019 $to = $this->_params["{$fieldName}_to"] ?? NULL;
6020 $fromTime = $this->_params["{$fieldName}_from_time"] ?? NULL;
6021 $toTime = $this->_params["{$fieldName}_to_time"] ?? NULL;
6022 return $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
6023 }
6024 }
6025 else {
6026 $op = $this->_params["{$fieldName}_op"] ?? NULL;
6027 if ($op) {
6028 return $this->whereClause($field,
6029 $op,
6030 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
6031 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
6032 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
6033 );
6034 }
6035 }
6036 return '';
6037 }
6038
6039 /**
6040 * Retrieve a suitable object from the factory depending on the report
6041 * parameters, which typically might just be dependent on outputMode.
6042 *
6043 * If there is no suitable output handler, e.g. if outputMode is "copy",
6044 * then this sets it to NULL.
6045 */
6046 public function setOutputHandler() {
6047 $this->outputHandler = \Civi\Report\OutputHandlerFactory::singleton()->create($this);
6048 }
6049
6050 /**
6051 * Send report by email
6052 */
6053 public function sendEmail() {
6054 if (empty($this->outputHandler)) {
6055 // It's possible to end up here with outputMode unset, so we use
6056 // the "print" handler which was the default before, i.e. include
6057 // it as html in the body.
6058 $oldOutputMode = $this->_outputMode ?? NULL;
6059 $this->_outputMode = 'print';
6060 $this->setOutputHandler();
6061 $this->_outputMode = $oldOutputMode;
6062 }
6063
6064 $mailBody = $this->outputHandler->getMailBody();
6065
6066 $attachments = [];
6067 $attachmentFileName = $this->outputHandler->getFileName();
6068 // It's not always in the form of an attachment, e.g. for 'print' the
6069 // output ends up in $mailBody above.
6070 if ($attachmentFileName) {
6071 $fullFilename = CRM_Core_Config::singleton()->templateCompileDir . CRM_Utils_File::makeFileName($attachmentFileName);
6072 file_put_contents($fullFilename, $this->outputHandler->getOutputString());
6073 $attachments[] = [
6074 'fullPath' => $fullFilename,
6075 'mime_type' => $this->outputHandler->getMimeType(),
6076 'cleanName' => $attachmentFileName,
6077 'charset' => $this->outputHandler->getCharset(),
6078 ];
6079 }
6080
6081 // Send the email
6082 // @todo outputMode doesn't seem to get used by mailReport, which is good
6083 // since it shouldn't have any outputMode-related `if` statements in it.
6084 // Someday could remove the param from the function call.
6085 if (CRM_Report_Utils_Report::mailReport($mailBody, $this->_id, $this->_outputMode, $attachments)) {
6086 CRM_Core_Session::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
6087 }
6088 else {
6089 CRM_Core_Session::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
6090 }
6091 }
6092
6093 }