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