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