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