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