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