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