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