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