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