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