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