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