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