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