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