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