Merge branch 4.5 into 4.6
[civicrm-core.git] / CRM / Report / Form.php
CommitLineData
6a488035 1<?php
6a488035 2/*
36241b02 3 +--------------------------------------------------------------------+
39de6fd5 4 | CiviCRM version 4.6 |
db4cd986 5 +--------------------------------------------------------------------+
e7112fa7 6 | Copyright CiviCRM LLC (c) 2004-2015 |
db4cd986 7 +--------------------------------------------------------------------+
6a488035
TO
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
36241b02 25 +--------------------------------------------------------------------+
e70a7fc0 26 */
6a488035
TO
27
28/**
7d7c50f9 29 * Class CRM_Report_Form
6a488035
TO
30 */
31class CRM_Report_Form extends CRM_Core_Form {
7da04cde 32 const ROW_COUNT_LIMIT = 50;
6a488035
TO
33
34 /**
35 * Operator types - used for displaying filter elements
36 */
7da04cde 37 const
9d72cede 38 OP_INT = 1,
6a488035 39 OP_STRING = 2,
9d72cede 40 OP_DATE = 4,
6a488035 41 OP_DATETIME = 5,
9d72cede 42 OP_FLOAT = 8,
6a488035
TO
43 OP_SELECT = 64,
44 OP_MULTISELECT = 65,
45 OP_MULTISELECT_SEPARATOR = 66,
2107cde9
CW
46 OP_MONTH = 128,
47 OP_ENTITYREF = 256;
6a488035
TO
48
49 /**
50 * The id of the report instance
51 *
52 * @var integer
53 */
54 protected $_id;
55
56 /**
57 * The id of the report template
58 *
59 * @var integer;
60 */
61 protected $_templateID;
62
63 /**
64 * The report title
65 *
66 * @var string
67 */
68 protected $_title;
69 protected $_noFields = FALSE;
70
71 /**
72 * The set of all columns in the report. An associative array
537c70b8 73 * with column name as the key and attributes as the value
6a488035
TO
74 *
75 * @var array
76 */
77 protected $_columns = array();
78
79 /**
80 * The set of filters in the report
81 *
82 * @var array
83 */
84 protected $_filters = array();
85
86 /**
87 * The set of optional columns in the report
88 *
89 * @var array
90 */
91 protected $_options = array();
92
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 /**
07f44165 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 1322 /**
07f44165 1323 * This adds the tab referred to as Title and Format, rendered through Instance.tpl.
0b62c1ab 1324 *
07f44165
EM
1325 * @todo call this tab into the report template in the same way as OrderBy etc, ie
1326 * by adding a description of the tab to $this->tabs, causing the tab to be added in
1327 * Criteria.tpl.
0b62c1ab 1328 */
00be9182 1329 public function buildInstanceAndButtons() {
6a488035
TO
1330 CRM_Report_Form_Instance::buildForm($this);
1331
1332 $label = $this->_id ? ts('Update Report') : ts('Create Report');
1333
1334 $this->addElement('submit', $this->_instanceButtonName, $label);
1335 $this->addElement('submit', $this->_printButtonName, ts('Print Report'));
1336 $this->addElement('submit', $this->_pdfButtonName, ts('PDF'));
1337
1338 if ($this->_id) {
9d72cede
EM
1339 $this->addElement('submit', $this->_createNewButtonName,
1340 ts('Save a Copy') . '...');
6a488035 1341 }
c9cf6554 1342 $this->assign('instanceForm', $this->_instanceForm);
6a488035
TO
1343
1344 $label = $this->_id ? ts('Print Report') : ts('Print Preview');
1345 $this->addElement('submit', $this->_printButtonName, $label);
1346
1347 $label = $this->_id ? ts('PDF') : ts('Preview PDF');
1348 $this->addElement('submit', $this->_pdfButtonName, $label);
1349
1350 $label = $this->_id ? ts('Export to CSV') : ts('Preview CSV');
1351
1352 if ($this->_csvSupported) {
1353 $this->addElement('submit', $this->_csvButtonName, $label);
1354 }
1355
9d72cede
EM
1356 if (CRM_Core_Permission::check('administer Reports') &&
1357 $this->_add2groupSupported
1358 ) {
6a488035 1359 $this->addElement('select', 'groups', ts('Group'),
9d72cede
EM
1360 array('' => ts('Add Contacts to Group')) +
1361 CRM_Core_PseudoConstant::nestedGroup(),
24431f7b 1362 array('class' => 'crm-select2 crm-action-menu action-icon-plus huge')
6a488035
TO
1363 );
1364 $this->assign('group', TRUE);
1365 }
1366
24431f7b 1367 $this->addElement('submit', $this->_groupButtonName, '', array('style' => 'display: none;'));
6a488035
TO
1368
1369 $this->addChartOptions();
1370 $this->addButtons(array(
1371 array(
1372 'type' => 'submit',
1373 'name' => ts('Preview Report'),
1374 'isDefault' => TRUE,
1375 ),
1376 )
1377 );
1378 }
1379
0b62c1ab
EM
1380 /**
1381 * Main build form function.
1382 */
00be9182 1383 public function buildQuickForm() {
6a488035
TO
1384 $this->addColumns();
1385
1386 $this->addFilters();
1387
1388 $this->addOptions();
1389
1390 $this->addGroupBys();
1391
1392 $this->addOrderBys();
1393
1394 $this->buildInstanceAndButtons();
1395
0b62c1ab 1396 // Add form rule for report.
6a488035 1397 if (is_callable(array(
9d72cede 1398 $this,
21dfd5f5 1399 'formRule',
9d72cede 1400 ))) {
6a488035
TO
1401 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1402 }
0b62c1ab 1403 $this->assignTabs();
6a488035
TO
1404 }
1405
74cf4551 1406 /**
537c70b8 1407 * A form rule function to ensure that fields selected in group_by
4f1f1f2a
CW
1408 * (if any) should only be the ones present in display/select fields criteria;
1409 * note: works if and only if any custom field selected in group_by.
0b62c1ab 1410 *
537c70b8 1411 * @param array $fields
74cf4551
EM
1412 * @param array $ignoreFields
1413 *
1414 * @return array
1415 */
00be9182 1416 public function customDataFormRule($fields, $ignoreFields = array()) {
6a488035 1417 $errors = array();
9d72cede
EM
1418 if (!empty($this->_customGroupExtends) && $this->_customGroupGroupBy &&
1419 !empty($fields['group_bys'])
1420 ) {
6a488035 1421 foreach ($this->_columns as $tableName => $table) {
9d72cede
EM
1422 if ((substr($tableName, 0, 13) == 'civicrm_value' ||
1423 substr($tableName, 0, 12) == 'custom_value') &&
1424 !empty($this->_columns[$tableName]['fields'])
1425 ) {
6a488035
TO
1426 foreach ($this->_columns[$tableName]['fields'] as $fieldName => $field) {
1427 if (array_key_exists($fieldName, $fields['group_bys']) &&
1428 !array_key_exists($fieldName, $fields['fields'])
1429 ) {
1430 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1431 }
1432 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1433 foreach ($fields['fields'] as $fld => $val) {
9d72cede
EM
1434 if (!array_key_exists($fld, $fields['group_bys']) &&
1435 !in_array($fld, $ignoreFields)
1436 ) {
6a488035
TO
1437 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1438 }
1439 }
1440 }
1441 }
1442 }
1443 }
1444 }
1445 return $errors;
1446 }
1447
74cf4551 1448 /**
0b62c1ab
EM
1449 * Get operators to display on form.
1450 *
1451 * Note: $fieldName param allows inheriting class to build operationPairs specific to a field.
1452 *
74cf4551 1453 * @param string $type
8a925f33 1454 * @param string $fieldName
74cf4551
EM
1455 *
1456 * @return array
1457 */
00be9182 1458 public function getOperationPair($type = "string", $fieldName = NULL) {
6a488035
TO
1459 // FIXME: At some point we should move these key-val pairs
1460 // to option_group and option_value table.
6a488035 1461 switch ($type) {
160d32e1
E
1462 case CRM_Report_Form::OP_INT:
1463 case CRM_Report_Form::OP_FLOAT:
bed98343 1464
6c552737 1465 $result = array(
bc3f7f04 1466 'lte' => ts('Is less than or equal to'),
6a488035
TO
1467 'gte' => ts('Is greater than or equal to'),
1468 'bw' => ts('Is between'),
1469 'eq' => ts('Is equal to'),
1470 'lt' => ts('Is less than'),
1471 'gt' => ts('Is greater than'),
1472 'neq' => ts('Is not equal to'),
1473 'nbw' => ts('Is not between'),
1474 'nll' => ts('Is empty (Null)'),
1475 'nnll' => ts('Is not empty (Null)'),
1476 );
6c552737 1477 return $result;
6a488035 1478
160d32e1 1479 case CRM_Report_Form::OP_SELECT:
6c552737 1480 $result = array(
bc3f7f04 1481 'eq' => ts('Is equal to'),
1482 );
6c552737 1483 return $result;
6a488035 1484
160d32e1
E
1485 case CRM_Report_Form::OP_MONTH:
1486 case CRM_Report_Form::OP_MULTISELECT:
2107cde9 1487 case CRM_Report_Form::OP_ENTITYREF:
bed98343 1488
6c552737 1489 $result = array(
bc3f7f04 1490 'in' => ts('Is one of'),
6a488035
TO
1491 'notin' => ts('Is not one of'),
1492 );
6c552737 1493 return $result;
6a488035 1494
160d32e1 1495 case CRM_Report_Form::OP_DATE:
bed98343 1496
6c552737 1497 $result = array(
bc3f7f04 1498 'nll' => ts('Is empty (Null)'),
6a488035
TO
1499 'nnll' => ts('Is not empty (Null)'),
1500 );
6c552737 1501 return $result;
6a488035 1502
160d32e1 1503 case CRM_Report_Form::OP_MULTISELECT_SEPARATOR:
6a488035
TO
1504 // use this operator for the values, concatenated with separator. For e.g if
1505 // multiple options for a column is stored as ^A{val1}^A{val2}^A
6c552737 1506 $result = array(
bc3f7f04 1507 'mhas' => ts('Is one of'),
67788963 1508 'mnot' => ts('Is not one of'),
bc3f7f04 1509 );
6c552737 1510 return $result;
6a488035
TO
1511
1512 default:
1513 // type is string
6c552737 1514 $result = array(
bc3f7f04 1515 'has' => ts('Contains'),
6a488035
TO
1516 'sw' => ts('Starts with'),
1517 'ew' => ts('Ends with'),
1518 'nhas' => ts('Does not contain'),
1519 'eq' => ts('Is equal to'),
1520 'neq' => ts('Is not equal to'),
1521 'nll' => ts('Is empty (Null)'),
1522 'nnll' => ts('Is not empty (Null)'),
1523 );
6c552737 1524 return $result;
6a488035
TO
1525 }
1526 }
1527
07f44165
EM
1528 /**
1529 * Build the tag filter field to display on the filters tab.
1530 */
00be9182 1531 public function buildTagFilter() {
ed795723 1532 $contactTags = CRM_Core_BAO_Tag::getTags($this->_tagFilterTable);
6a488035
TO
1533 if (!empty($contactTags)) {
1534 $this->_columns['civicrm_tag'] = array(
1535 'dao' => 'CRM_Core_DAO_Tag',
9d72cede
EM
1536 'filters' => array(
1537 'tagid' => array(
6a488035
TO
1538 'name' => 'tag_id',
1539 'title' => ts('Tag'),
1540 'tag' => TRUE,
1541 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
1542 'options' => $contactTags,
1543 ),
1544 ),
1545 );
1546 }
1547 }
1548
688d37c6 1549 /**
0b62c1ab 1550 * Adds group filters to _columns (called from _Construct).
6a488035 1551 */
00be9182 1552 public function buildGroupFilter() {
6a488035 1553 $this->_columns['civicrm_group']['filters'] = array(
9d72cede 1554 'gid' => array(
6a488035
TO
1555 'name' => 'group_id',
1556 'title' => ts('Group'),
1557 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
1558 'group' => TRUE,
16e2e80c 1559 'options' => CRM_Core_PseudoConstant::nestedGroup(),
6a488035
TO
1560 ),
1561 );
1562 if (empty($this->_columns['civicrm_group']['dao'])) {
1563 $this->_columns['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1564 }
1565 if (empty($this->_columns['civicrm_group']['alias'])) {
1566 $this->_columns['civicrm_group']['alias'] = 'cgroup';
1567 }
1568 }
1569
74cf4551 1570 /**
07f44165
EM
1571 * Get SQL operator from form text version.
1572 *
74cf4551
EM
1573 * @param string $operator
1574 *
1575 * @return string
1576 */
00be9182 1577 public function getSQLOperator($operator = "like") {
6a488035
TO
1578 switch ($operator) {
1579 case 'eq':
1580 return '=';
1581
1582 case 'lt':
1583 return '<';
1584
1585 case 'lte':
1586 return '<=';
1587
1588 case 'gt':
1589 return '>';
1590
1591 case 'gte':
1592 return '>=';
1593
1594 case 'ne':
1595 case 'neq':
1596 return '!=';
1597
1598 case 'nhas':
1599 return 'NOT LIKE';
1600
1601 case 'in':
1602 return 'IN';
1603
1604 case 'notin':
1605 return 'NOT IN';
1606
1607 case 'nll':
1608 return 'IS NULL';
1609
1610 case 'nnll':
1611 return 'IS NOT NULL';
1612
1613 default:
1614 // type is string
1615 return 'LIKE';
1616 }
1617 }
1618
74cf4551 1619 /**
f587aa17 1620 * Generate where clause.
07f44165 1621 *
8a925f33 1622 * This can be overridden in reports for special treatment of a field
f587aa17 1623 *
537c70b8 1624 * @param array $field Field specifications
8a925f33 1625 * @param string $op Query operator (not an exact match to sql)
f587aa17
EM
1626 * @param mixed $value
1627 * @param float $min
1628 * @param float $max
74cf4551
EM
1629 *
1630 * @return null|string
1631 */
8a925f33 1632 public function whereClause(&$field, $op, $value, $min, $max) {
6a488035
TO
1633
1634 $type = CRM_Utils_Type::typeToString(CRM_Utils_Array::value('type', $field));
1635 $clause = NULL;
1636
1637 switch ($op) {
1638 case 'bw':
1639 case 'nbw':
1640 if (($min !== NULL && strlen($min) > 0) ||
1641 ($max !== NULL && strlen($max) > 0)
1642 ) {
9d72cede
EM
1643 $min = CRM_Utils_Type::escape($min, $type);
1644 $max = CRM_Utils_Type::escape($max, $type);
6a488035
TO
1645 $clauses = array();
1646 if ($min) {
1647 if ($op == 'bw') {
1648 $clauses[] = "( {$field['dbAlias']} >= $min )";
1649 }
1650 else {
1651 $clauses[] = "( {$field['dbAlias']} < $min )";
1652 }
1653 }
1654 if ($max) {
1655 if ($op == 'bw') {
1656 $clauses[] = "( {$field['dbAlias']} <= $max )";
1657 }
1658 else {
1659 $clauses[] = "( {$field['dbAlias']} > $max )";
1660 }
1661 }
1662
1663 if (!empty($clauses)) {
1664 if ($op == 'bw') {
1665 $clause = implode(' AND ', $clauses);
1666 }
1667 else {
1668 $clause = implode(' OR ', $clauses);
1669 }
1670 }
1671 }
1672 break;
1673
1674 case 'has':
1675 case 'nhas':
1676 if ($value !== NULL && strlen($value) > 0) {
1677 $value = CRM_Utils_Type::escape($value, $type);
1678 if (strpos($value, '%') === FALSE) {
1679 $value = "'%{$value}%'";
1680 }
1681 else {
1682 $value = "'{$value}'";
1683 }
29fc2b79 1684 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1685 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1686 }
1687 break;
1688
1689 case 'in':
1690 case 'notin':
2107cde9
CW
1691 if (is_string($value) && strlen($value)) {
1692 $value = explode(',', $value);
1693 }
6a488035 1694 if ($value !== NULL && is_array($value) && count($value) > 0) {
29fc2b79 1695 $sqlOP = $this->getSQLOperator($op);
9d72cede
EM
1696 if (CRM_Utils_Array::value('type', $field) ==
1697 CRM_Utils_Type::T_STRING
1698 ) {
f587aa17 1699 //cycle through selections and escape values
6a488035
TO
1700 foreach ($value as $key => $selection) {
1701 $value[$key] = CRM_Utils_Type::escape($selection, $type);
1702 }
971d41b1
CW
1703 $clause
1704 = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) .
9d72cede 1705 "') )";
6a488035
TO
1706 }
1707 else {
1708 // for numerical values
9d72cede
EM
1709 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) .
1710 ")";
6a488035
TO
1711 }
1712 if ($op == 'notin') {
1713 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1714 }
1715 else {
1716 $clause = "( " . $clause . " )";
1717 }
1718 }
1719 break;
1720
1721 case 'mhas':
1722 // mhas == multiple has
1723 if ($value !== NULL && count($value) > 0) {
29fc2b79 1724 $sqlOP = $this->getSQLOperator($op);
971d41b1
CW
1725 $clause
1726 = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) .
9d72cede 1727 "[[:>:]]'";
6a488035
TO
1728 }
1729 break;
77b97be7 1730
67788963
J
1731 case 'mnot':
1732 // mnot == multiple is not one of
1733 if ($value !== NULL && count($value) > 0) {
1734 $sqlOP = $this->getSQLOperator($op);
971d41b1
CW
1735 $clause
1736 = "( {$field['dbAlias']} NOT REGEXP '[[:<:]]" . implode('|', $value) .
9d72cede 1737 "[[:>:]]' OR {$field['dbAlias']} IS NULL )";
67788963
J
1738 }
1739 break;
6a488035
TO
1740
1741 case 'sw':
1742 case 'ew':
1743 if ($value !== NULL && strlen($value) > 0) {
1744 $value = CRM_Utils_Type::escape($value, $type);
1745 if (strpos($value, '%') === FALSE) {
1746 if ($op == 'sw') {
1747 $value = "'{$value}%'";
1748 }
1749 else {
1750 $value = "'%{$value}'";
1751 }
1752 }
1753 else {
1754 $value = "'{$value}'";
1755 }
29fc2b79 1756 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1757 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1758 }
1759 break;
1760
1761 case 'nll':
1762 case 'nnll':
29fc2b79 1763 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1764 $clause = "( {$field['dbAlias']} $sqlOP )";
1765 break;
1766
1767 default:
1768 if ($value !== NULL && strlen($value) > 0) {
1769 if (isset($field['clause'])) {
1770 // FIXME: we not doing escape here. Better solution is to use two
1771 // different types - data-type and filter-type
0e6e8724 1772 $clause = $field['clause'];
6a488035
TO
1773 }
1774 else {
1775 $value = CRM_Utils_Type::escape($value, $type);
29fc2b79 1776 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1777 if ($field['type'] == CRM_Utils_Type::T_STRING) {
1778 $value = "'{$value}'";
1779 }
1780 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1781 }
1782 }
1783 break;
1784 }
1785
a7488080 1786 if (!empty($field['group']) && $clause) {
6a488035
TO
1787 $clause = $this->whereGroupClause($field, $value, $op);
1788 }
a7488080 1789 elseif (!empty($field['tag']) && $clause) {
6a488035
TO
1790 // not using left join in query because if any contact
1791 // belongs to more than one tag, results duplicate
1792 // entries.
1793 $clause = $this->whereTagClause($field, $value, $op);
1794 }
114a2c85 1795 elseif (!empty($field['membership_org']) && $clause) {
f587aa17 1796 $clause = $this->whereMembershipOrgClause($value, $op);
114a2c85
DG
1797 }
1798 elseif (!empty($field['membership_type']) && $clause) {
f587aa17 1799 $clause = $this->whereMembershipTypeClause($value, $op);
114a2c85 1800 }
6a488035
TO
1801 return $clause;
1802 }
1803
74cf4551 1804 /**
07f44165
EM
1805 * Get SQL where clause for a date field.
1806 *
100fef9d 1807 * @param string $fieldName
74cf4551 1808 * @param $relative
f587aa17
EM
1809 * @param string $from
1810 * @param string $to
07f44165
EM
1811 * @param string $type
1812 * @param string $fromTime
1813 * @param string $toTime
74cf4551
EM
1814 *
1815 * @return null|string
1816 */
971d41b1 1817 public function dateClause(
7d8c1168
TO
1818 $fieldName,
1819 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
6a488035
TO
1820 ) {
1821 $clauses = array();
160d32e1 1822 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form::OP_DATE)))) {
29fc2b79 1823 $sqlOP = $this->getSQLOperator($relative);
6a488035
TO
1824 return "( {$fieldName} {$sqlOP} )";
1825 }
1826
29fc2b79 1827 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
6a488035
TO
1828
1829 if ($from) {
1830 $from = ($type == CRM_Utils_Type::T_DATE) ? substr($from, 0, 8) : $from;
1831 $clauses[] = "( {$fieldName} >= $from )";
1832 }
1833
1834 if ($to) {
1835 $to = ($type == CRM_Utils_Type::T_DATE) ? substr($to, 0, 8) : $to;
1836 $clauses[] = "( {$fieldName} <= {$to} )";
1837 }
1838
1839 if (!empty($clauses)) {
1840 return implode(' AND ', $clauses);
1841 }
1842
1843 return NULL;
1844 }
9d72cede
EM
1845
1846 /**
42b5c549
EM
1847 * Possibly unused function.
1848 *
9d72cede
EM
1849 * @todo - could not find any instances where this is called
1850 *
537c70b8 1851 * @param bool $relative
7e06c9f5 1852 * @param string $from
7d7c50f9 1853 * @param string $to
9d72cede
EM
1854 *
1855 * @return string|NULL
1856 */
00be9182 1857 public function dateDisplay($relative, $from, $to) {
29fc2b79 1858 list($from, $to) = $this->getFromTo($relative, $from, $to);
6a488035
TO
1859
1860 if ($from) {
1861 $clauses[] = CRM_Utils_Date::customFormat($from, NULL, array('m', 'M'));
1862 }
1863 else {
1864 $clauses[] = 'Past';
1865 }
1866
1867 if ($to) {
1868 $clauses[] = CRM_Utils_Date::customFormat($to, NULL, array('m', 'M'));
1869 }
1870 else {
1871 $clauses[] = 'Today';
1872 }
1873
1874 if (!empty($clauses)) {
1875 return implode(' - ', $clauses);
1876 }
1877
1878 return NULL;
1879 }
1880
74cf4551 1881 /**
42b5c549
EM
1882 * Get values for from and to for date ranges.
1883 *
f587aa17
EM
1884 * @param bool $relative
1885 * @param string $from
1886 * @param string $to
9907633b
EM
1887 * @param string $fromTime
1888 * @param string $toTime
74cf4551
EM
1889 *
1890 * @return array
1891 */
9907633b
EM
1892 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
1893 if (empty($toTime)) {
1894 $toTime = '235959';
6a488035
TO
1895 }
1896 //FIX ME not working for relative
1897 if ($relative) {
1898 list($term, $unit) = CRM_Utils_System::explode('.', $relative, 2);
1899 $dateRange = CRM_Utils_Date::relativeToAbsolute($term, $unit);
1900 $from = substr($dateRange['from'], 0, 8);
1901 //Take only Date Part, Sometime Time part is also present in 'to'
1902 $to = substr($dateRange['to'], 0, 8);
1903 }
9907633b
EM
1904 $from = CRM_Utils_Date::processDate($from, $fromTime);
1905 $to = CRM_Utils_Date::processDate($to, $toTime);
6a488035
TO
1906 return array($from, $to);
1907 }
1908
74cf4551 1909 /**
4b62bc4f
EM
1910 * Alter display of rows.
1911 *
1912 * Iterate through the rows retrieved via SQL and make changes for display purposes,
1913 * such as rendering contacts as links.
1914 *
1915 * @param array $rows
1916 * Rows generated by SQL, with an array for each row.
74cf4551 1917 */
00be9182 1918 public function alterDisplay(&$rows) {
6a488035
TO
1919 }
1920
74cf4551 1921 /**
42b5c549
EM
1922 * Alter the way in which custom data fields are displayed.
1923 *
1924 * @param array $rows
74cf4551 1925 */
00be9182 1926 public function alterCustomDataDisplay(&$rows) {
6a488035
TO
1927 // custom code to alter rows having custom values
1928 if (empty($this->_customGroupExtends)) {
1929 return;
1930 }
1931
1932 $customFieldIds = array();
1933 foreach ($this->_params['fields'] as $fieldAlias => $value) {
1934 if ($fieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
1935 $customFieldIds[$fieldAlias] = $fieldId;
1936 }
1937 }
1938 if (empty($customFieldIds)) {
1939 return;
1940 }
1941
1942 $customFields = $fieldValueMap = array();
9d72cede
EM
1943 $customFieldCols = array(
1944 'column_name',
1945 'data_type',
1946 'html_type',
1947 'option_group_id',
21dfd5f5 1948 'id',
9d72cede 1949 );
6a488035
TO
1950
1951 // skip for type date and ContactReference since date format is already handled
1952 $query = "
1953SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1954FROM civicrm_custom_field cf
1955INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1956LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1957WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
1958 cg.is_active = 1 AND
1959 cf.is_active = 1 AND
1960 cf.is_searchable = 1 AND
1961 cf.data_type NOT IN ('ContactReference', 'Date') AND
1962 cf.id IN (" . implode(",", $customFieldIds) . ")";
1963
1964 $dao = CRM_Core_DAO::executeQuery($query);
1965 while ($dao->fetch()) {
1966 foreach ($customFieldCols as $key) {
9d72cede
EM
1967 $customFields[$dao->table_name . '_custom_' .
1968 $dao->id][$key] = $dao->$key;
6a488035
TO
1969 }
1970 if ($dao->option_group_id) {
1971 $fieldValueMap[$dao->option_group_id][$dao->value] = $dao->label;
1972 }
1973 }
1974 $dao->free();
1975
1976 $entryFound = FALSE;
1977 foreach ($rows as $rowNum => $row) {
1978 foreach ($row as $tableCol => $val) {
1979 if (array_key_exists($tableCol, $customFields)) {
1980 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1981 $entryFound = TRUE;
1982 }
1983 }
1984
1985 // skip looking further in rows, if first row itself doesn't
1986 // have the column we need
1987 if (!$entryFound) {
1988 break;
1989 }
1990 }
1991 }
1992
74cf4551
EM
1993 /**
1994 * @param $value
1995 * @param $customField
1996 * @param $fieldValueMap
1997 *
971d41b1 1998 * @return float|string|void
74cf4551 1999 */
00be9182 2000 public function formatCustomValues($value, $customField, $fieldValueMap) {
6a488035 2001 if (CRM_Utils_System::isNull($value)) {
bed98343 2002 return NULL;
6a488035
TO
2003 }
2004
2005 $htmlType = $customField['html_type'];
2006
2007 switch ($customField['data_type']) {
2008 case 'Boolean':
2009 if ($value == '1') {
2010 $retValue = ts('Yes');
2011 }
2012 else {
2013 $retValue = ts('No');
2014 }
2015 break;
2016
2017 case 'Link':
2018 $retValue = CRM_Utils_System::formatWikiURL($value);
2019 break;
2020
2021 case 'File':
2022 $retValue = $value;
2023 break;
2024
2025 case 'Memo':
2026 $retValue = $value;
2027 break;
2028
2029 case 'Float':
2030 if ($htmlType == 'Text') {
9d72cede 2031 $retValue = (float) $value;
6a488035
TO
2032 break;
2033 }
2034 case 'Money':
2035 if ($htmlType == 'Text') {
6a488035
TO
2036 $retValue = CRM_Utils_Money::format($value, NULL, '%a');
2037 break;
2038 }
2039 case 'String':
2040 case 'Int':
2041 if (in_array($htmlType, array(
9d72cede 2042 'Text',
21dfd5f5 2043 'TextArea',
9d72cede 2044 ))) {
6a488035
TO
2045 $retValue = $value;
2046 break;
2047 }
2048 case 'StateProvince':
2049 case 'Country':
2050
2051 switch ($htmlType) {
2052 case 'Multi-Select Country':
2053 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2054 $customData = array();
2055 foreach ($value as $val) {
2056 if ($val) {
2057 $customData[] = CRM_Core_PseudoConstant::country($val, FALSE);
2058 }
2059 }
2060 $retValue = implode(', ', $customData);
2061 break;
2062
2063 case 'Select Country':
2064 $retValue = CRM_Core_PseudoConstant::country($value, FALSE);
2065 break;
2066
2067 case 'Select State/Province':
2068 $retValue = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
2069 break;
2070
2071 case 'Multi-Select State/Province':
2072 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2073 $customData = array();
2074 foreach ($value as $val) {
2075 if ($val) {
2076 $customData[] = CRM_Core_PseudoConstant::stateProvince($val, FALSE);
2077 }
2078 }
2079 $retValue = implode(', ', $customData);
2080 break;
2081
2082 case 'Select':
2083 case 'Radio':
2084 case 'Autocomplete-Select':
2085 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
2086 break;
2087
2088 case 'CheckBox':
2089 case 'AdvMulti-Select':
2090 case 'Multi-Select':
2091 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2092 $customData = array();
2093 foreach ($value as $val) {
2094 if ($val) {
2095 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
2096 }
2097 }
2098 $retValue = implode(', ', $customData);
2099 break;
2100
2101 default:
2102 $retValue = $value;
2103 }
2104 break;
2105
2106 default:
2107 $retValue = $value;
2108 }
2109
2110 return $retValue;
2111 }
2112
74cf4551
EM
2113 /**
2114 * @param $rows
2115 */
00be9182 2116 public function removeDuplicates(&$rows) {
6a488035
TO
2117 if (empty($this->_noRepeats)) {
2118 return;
2119 }
2120 $checkList = array();
2121
2122 foreach ($rows as $key => $list) {
2123 foreach ($list as $colName => $colVal) {
8f1445ea 2124 if (array_key_exists($colName, $checkList) &&
9d72cede
EM
2125 $checkList[$colName] == $colVal
2126 ) {
6a488035
TO
2127 $rows[$key][$colName] = "";
2128 }
2129 if (in_array($colName, $this->_noRepeats)) {
2130 $checkList[$colName] = $colVal;
2131 }
2132 }
2133 }
2134 }
2135
74cf4551
EM
2136 /**
2137 * @param $row
2138 * @param $fields
2139 * @param bool $subtotal
2140 */
00be9182 2141 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
6a488035
TO
2142 foreach ($row as $colName => $colVal) {
2143 if (in_array($colName, $fields)) {
6a488035
TO
2144 }
2145 elseif (isset($this->_columnHeaders[$colName])) {
2146 if ($subtotal) {
2147 $row[$colName] = "Subtotal";
2148 $subtotal = FALSE;
2149 }
2150 else {
2151 unset($row[$colName]);
2152 }
2153 }
2154 }
2155 }
2156
74cf4551
EM
2157 /**
2158 * @param $rows
2159 *
2160 * @return bool
2161 */
00be9182 2162 public function grandTotal(&$rows) {
6a488035
TO
2163 if (!$this->_rollup || ($this->_rollup == '') ||
2164 ($this->_limit && count($rows) >= self::ROW_COUNT_LIMIT)
2165 ) {
2166 return FALSE;
2167 }
2168 $lastRow = array_pop($rows);
2169
6a488035
TO
2170 foreach ($this->_columnHeaders as $fld => $val) {
2171 if (!in_array($fld, $this->_statFields)) {
2172 if (!$this->_grandFlag) {
2173 $lastRow[$fld] = "Grand Total";
2174 $this->_grandFlag = TRUE;
2175 }
2176 else {
2177 $lastRow[$fld] = "";
2178 }
2179 }
2180 }
2181
2182 $this->assign('grandStat', $lastRow);
2183 return TRUE;
2184 }
2185
74cf4551
EM
2186 /**
2187 * @param $rows
2188 * @param bool $pager
2189 */
00be9182 2190 public function formatDisplay(&$rows, $pager = TRUE) {
6a488035
TO
2191 // set pager based on if any limit was applied in the query.
2192 if ($pager) {
2193 $this->setPager();
2194 }
2195
2196 // allow building charts if any
2197 if (!empty($this->_params['charts']) && !empty($rows)) {
2198 $this->buildChart($rows);
2199 $this->assign('chartEnabled', TRUE);
9d72cede
EM
2200 $this->_chartId = "{$this->_params['charts']}_" .
2201 ($this->_id ? $this->_id : substr(get_class($this), 16)) . '_' .
2202 session_id();
6a488035
TO
2203 $this->assign('chartId', $this->_chartId);
2204 }
2205
2206 // unset columns not to be displayed.
2207 foreach ($this->_columnHeaders as $key => $value) {
a7488080 2208 if (!empty($value['no_display'])) {
6a488035
TO
2209 unset($this->_columnHeaders[$key]);
2210 }
2211 }
2212
2213 // unset columns not to be displayed.
2214 if (!empty($rows)) {
2215 foreach ($this->_noDisplay as $noDisplayField) {
2216 foreach ($rows as $rowNum => $row) {
2217 unset($this->_columnHeaders[$noDisplayField]);
2218 }
2219 }
2220 }
2221
2222 // build array of section totals
2223 $this->sectionTotals();
2224
2225 // process grand-total row
2226 $this->grandTotal($rows);
2227
2228 // use this method for formatting rows for display purpose.
2229 $this->alterDisplay($rows);
2230 CRM_Utils_Hook::alterReportVar('rows', $rows, $this);
2231
2232 // use this method for formatting custom rows for display purpose.
2233 $this->alterCustomDataDisplay($rows);
2234 }
2235
74cf4551
EM
2236 /**
2237 * @param $rows
2238 */
00be9182 2239 public function buildChart(&$rows) {
6a488035
TO
2240 // override this method for building charts.
2241 }
2242
2243 // select() method below has been added recently (v3.3), and many of the report templates might
2244 // still be having their own select() method. We should fix them as and when encountered and move
2245 // towards generalizing the select() method below.
971d41b1
CW
2246
2247 /**
2248 * Generate the SELECT clause and set class variable $_select
2249 */
00be9182 2250 public function select() {
1f220d30 2251 $select = $this->_selectAliases = array();
6a488035
TO
2252
2253 foreach ($this->_columns as $tableName => $table) {
2254 if (array_key_exists('fields', $table)) {
2255 foreach ($table['fields'] as $fieldName => $field) {
2256 if ($tableName == 'civicrm_address') {
2257 $this->_addressField = TRUE;
2258 }
2259 if ($tableName == 'civicrm_email') {
2260 $this->_emailField = TRUE;
2261 }
2262 if ($tableName == 'civicrm_phone') {
2263 $this->_phoneField = TRUE;
2264 }
2265
9d72cede
EM
2266 if (!empty($field['required']) ||
2267 !empty($this->_params['fields'][$fieldName])
2268 ) {
6a488035
TO
2269
2270 // 1. In many cases we want select clause to be built in slightly different way
2271 // for a particular field of a particular type.
2272 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2273 // as needed.
2274 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2275 if ($selectClause) {
2276 $select[] = $selectClause;
2277 continue;
2278 }
2279
2280 // include statistics columns only if set
a7488080 2281 if (!empty($field['statistics'])) {
6a488035
TO
2282 foreach ($field['statistics'] as $stat => $label) {
2283 $alias = "{$tableName}_{$fieldName}_{$stat}";
2284 switch (strtolower($stat)) {
2285 case 'max':
2286 case 'sum':
2287 $select[] = "$stat({$field['dbAlias']}) as $alias";
2288 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2289 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
9e6d7767 2290 $this->_statFields[$label] = $alias;
6a488035
TO
2291 $this->_selectAliases[] = $alias;
2292 break;
2293
2294 case 'count':
2295 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2296 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2297 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
9e6d7767 2298 $this->_statFields[$label] = $alias;
6a488035
TO
2299 $this->_selectAliases[] = $alias;
2300 break;
2301
1bfaf6a6
DS
2302 case 'count_distinct':
2303 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2304 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2305 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
2306 $this->_statFields[$label] = $alias;
2307 $this->_selectAliases[] = $alias;
2308 break;
2309
6a488035
TO
2310 case 'avg':
2311 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2312 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2313 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
9e6d7767 2314 $this->_statFields[$label] = $alias;
6a488035
TO
2315 $this->_selectAliases[] = $alias;
2316 break;
2317 }
2318 }
2319 }
2320 else {
2321 $alias = "{$tableName}_{$fieldName}";
2322 $select[] = "{$field['dbAlias']} as $alias";
2323 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
2324 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
2325 $this->_selectAliases[] = $alias;
2326 }
2327 }
2328 }
2329 }
2330
2331 // select for group bys
2332 if (array_key_exists('group_bys', $table)) {
2333 foreach ($table['group_bys'] as $fieldName => $field) {
2334
2335 if ($tableName == 'civicrm_address') {
2336 $this->_addressField = TRUE;
2337 }
2338 if ($tableName == 'civicrm_email') {
2339 $this->_emailField = TRUE;
2340 }
2341 if ($tableName == 'civicrm_phone') {
2342 $this->_phoneField = TRUE;
2343 }
2344 // 1. In many cases we want select clause to be built in slightly different way
2345 // for a particular field of a particular type.
2346 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2347 // as needed.
2348 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2349 if ($selectClause) {
2350 $select[] = $selectClause;
2351 continue;
2352 }
2353
9d72cede
EM
2354 if (!empty($this->_params['group_bys']) &&
2355 !empty($this->_params['group_bys'][$fieldName]) &&
2356 !empty($this->_params['group_bys_freq'])
2357 ) {
6a488035
TO
2358 switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
2359 case 'YEARWEEK':
9d72cede
EM
2360 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2361 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2362 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
6a488035
TO
2363 $field['title'] = 'Week';
2364 break;
2365
2366 case 'YEAR':
9d72cede
EM
2367 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2368 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2369 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
6a488035
TO
2370 $field['title'] = 'Year';
2371 break;
2372
2373 case 'MONTH':
9d72cede
EM
2374 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2375 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2376 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
6a488035
TO
2377 $field['title'] = 'Month';
2378 break;
2379
2380 case 'QUARTER':
9d72cede
EM
2381 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2382 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2383 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
6a488035
TO
2384 $field['title'] = 'Quarter';
2385 break;
2386 }
2387 // for graphs and charts -
a7488080 2388 if (!empty($this->_params['group_bys_freq'][$fieldName])) {
6a488035 2389 $this->_interval = $field['title'];
971d41b1
CW
2390 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title']
2391 = $field['title'] . ' Beginning';
6a488035
TO
2392 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2393 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
2394
7d7c50f9 2395 // just to make sure these values are transferred to rows.
6a488035
TO
2396 // since we 'll need them for calculation purpose,
2397 // e.g making subtotals look nicer or graphs
2398 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2399 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2400 }
2401 }
2402 }
2403 }
2404 }
2405
1f220d30 2406 $this->_selectClauses = $select;
6a488035
TO
2407 $this->_select = "SELECT " . implode(', ', $select) . " ";
2408 }
2409
74cf4551 2410 /**
100fef9d 2411 * @param string $tableName
74cf4551 2412 * @param $tableKey
100fef9d 2413 * @param string $fieldName
74cf4551
EM
2414 * @param $field
2415 *
2416 * @return bool
2417 */
00be9182 2418 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
6a488035
TO
2419 return FALSE;
2420 }
2421
00be9182 2422 public function where() {
adfe2750 2423 $this->storeWhereHavingClauseArray();
2424
2425 if (empty($this->_whereClauses)) {
2426 $this->_where = "WHERE ( 1 ) ";
2427 $this->_having = "";
2428 }
2429 else {
2430 $this->_where = "WHERE " . implode(' AND ', $this->_whereClauses);
2431 }
2432
2433 if ($this->_aclWhere) {
2434 $this->_where .= " AND {$this->_aclWhere} ";
2435 }
2436
2437 if (!empty($this->_havingClauses)) {
2438 // use this clause to construct group by clause.
2439 $this->_having = "HAVING " . implode(' AND ', $this->_havingClauses);
2440 }
2441 }
2442
2443 /**
2444 * Store Where clauses into an array - breaking out this step makes
2445 * over-riding more flexible as the clauses can be used in constructing a
2446 * temp table that may not be part of the final where clause or added
2447 * in other functions
2448 */
00be9182 2449 public function storeWhereHavingClauseArray() {
6a488035
TO
2450 foreach ($this->_columns as $tableName => $table) {
2451 if (array_key_exists('filters', $table)) {
2452 foreach ($table['filters'] as $fieldName => $field) {
d12de91c 2453 // respect pseudofield to filter spec so fields can be marked as
2454 // not to be handled here
9d72cede 2455 if (!empty($field['pseudofield'])) {
d12de91c 2456 continue;
2457 }
6a488035
TO
2458 $clause = NULL;
2459 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
9d72cede
EM
2460 if (CRM_Utils_Array::value('operatorType', $field) ==
2461 CRM_Report_Form::OP_MONTH
2462 ) {
6a488035
TO
2463 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2464 $value = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
2465 if (is_array($value) && !empty($value)) {
971d41b1
CW
2466 $clause
2467 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
9d72cede 2468 '))';
6a488035
TO
2469 }
2470 }
2471 else {
2472 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
9d72cede
EM
2473 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
2474 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
6a488035 2475 $fromTime = CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params);
9d72cede
EM
2476 $toTime = CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params);
2477 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
6a488035
TO
2478 }
2479 }
2480 else {
2481 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2482 if ($op) {
2483 $clause = $this->whereClause($field,
adfe2750 2484 $op,
2485 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
2486 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
2487 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
6a488035
TO
2488 );
2489 }
2490 }
2491
2492 if (!empty($clause)) {
a7488080 2493 if (!empty($field['having'])) {
adfe2750 2494 $this->_havingClauses[] = $clause;
6a488035
TO
2495 }
2496 else {
adfe2750 2497 $this->_whereClauses[] = $clause;
6a488035
TO
2498 }
2499 }
2500 }
2501 }
2502 }
2503
6a488035 2504 }
9d72cede 2505
00be9182 2506 public function processReportMode() {
6a488035
TO
2507 $buttonName = $this->controller->getButtonName();
2508
884605ca
DL
2509 $output = CRM_Utils_Request::retrieve(
2510 'output',
2511 'String',
2512 CRM_Core_DAO::$_nullObject
6a488035
TO
2513 );
2514
971d41b1
CW
2515 $this->_sendmail
2516 = CRM_Utils_Request::retrieve(
884605ca
DL
2517 'sendmail',
2518 'Boolean',
2519 CRM_Core_DAO::$_nullObject
2520 );
6a488035
TO
2521
2522 $this->_absoluteUrl = FALSE;
2523 $printOnly = FALSE;
2524 $this->assign('printOnly', FALSE);
2525
9d72cede
EM
2526 if ($this->_printButtonName == $buttonName || $output == 'print' ||
2527 ($this->_sendmail && !$output)
2528 ) {
6a488035
TO
2529 $this->assign('printOnly', TRUE);
2530 $printOnly = TRUE;
2531 $this->assign('outputMode', 'print');
2532 $this->_outputMode = 'print';
2533 if ($this->_sendmail) {
2534 $this->_absoluteUrl = TRUE;
9d72cede 2535 }
6a488035
TO
2536 }
2537 elseif ($this->_pdfButtonName == $buttonName || $output == 'pdf') {
2538 $this->assign('printOnly', TRUE);
2539 $printOnly = TRUE;
2540 $this->assign('outputMode', 'pdf');
2541 $this->_outputMode = 'pdf';
2542 $this->_absoluteUrl = TRUE;
2543 }
2544 elseif ($this->_csvButtonName == $buttonName || $output == 'csv') {
2545 $this->assign('printOnly', TRUE);
2546 $printOnly = TRUE;
2547 $this->assign('outputMode', 'csv');
2548 $this->_outputMode = 'csv';
2549 $this->_absoluteUrl = TRUE;
2550 }
2551 elseif ($this->_groupButtonName == $buttonName || $output == 'group') {
2552 $this->assign('outputMode', 'group');
2553 $this->_outputMode = 'group';
2554 }
2555 elseif ($output == 'create_report' && $this->_criteriaForm) {
2556 $this->assign('outputMode', 'create_report');
2557 $this->_outputMode = 'create_report';
2558 }
2559 else {
2560 $this->assign('outputMode', 'html');
2561 $this->_outputMode = 'html';
2562 }
2563
2564 // Get today's date to include in printed reports
2565 if ($printOnly) {
2566 $reportDate = CRM_Utils_Date::customFormat(date('Y-m-d H:i'));
2567 $this->assign('reportDate', $reportDate);
2568 }
2569 }
2570
9657ccf2
EM
2571 /**
2572 * Post Processing function for Form (postProcessCommon should be used to set other variables from input as the api accesses that function)
2573 */
00be9182 2574 public function beginPostProcess() {
c58f66e0 2575 $this->setParams($this->controller->exportValues($this->_name));
6a488035
TO
2576
2577 if (empty($this->_params) &&
2578 $this->_force
2579 ) {
c58f66e0 2580 $this->setParams($this->_formValues);
6a488035
TO
2581 }
2582
2583 // hack to fix params when submitted from dashboard, CRM-8532
2584 // fields array is missing because form building etc is skipped
2585 // in dashboard mode for report
c58f66e0 2586 //@todo - this could be done in the dashboard no we have a setter
a7488080 2587 if (empty($this->_params['fields']) && !$this->_noFields) {
c58f66e0 2588 $this->setParams($this->_formValues);
6a488035
TO
2589 }
2590
2591 $this->_formValues = $this->_params;
2592 if (CRM_Core_Permission::check('administer Reports') &&
2593 isset($this->_id) &&
9d72cede
EM
2594 ($this->_instanceButtonName ==
2595 $this->controller->getButtonName() . '_save' ||
6a488035
TO
2596 $this->_chartButtonName == $this->controller->getButtonName()
2597 )
2598 ) {
2599 $this->assign('updateReportButton', TRUE);
2600 }
2601 $this->processReportMode();
c58f66e0
E
2602 $this->beginPostProcessCommon();
2603 }
2604
2605 /**
100fef9d 2606 * BeginPostProcess function run in both report mode and non-report mode (api)
c58f66e0 2607 */
00be9182 2608 public function beginPostProcessCommon() {
c58f66e0 2609
6a488035
TO
2610 }
2611
74cf4551
EM
2612 /**
2613 * @param bool $applyLimit
2614 *
2615 * @return string
2616 */
00be9182 2617 public function buildQuery($applyLimit = TRUE) {
6a488035
TO
2618 $this->select();
2619 $this->from();
2620 $this->customDataFrom();
2621 $this->where();
2622 $this->groupBy();
2623 $this->orderBy();
2624
2625 // order_by columns not selected for display need to be included in SELECT
2626 $unselectedSectionColumns = $this->unselectedSectionColumns();
2627 foreach ($unselectedSectionColumns as $alias => $section) {
2628 $this->_select .= ", {$section['dbAlias']} as {$alias}";
2629 }
2630
8cc574cf 2631 if ($applyLimit && empty($this->_params['charts'])) {
6a488035
TO
2632 $this->limit();
2633 }
2634 CRM_Utils_Hook::alterReportVar('sql', $this, $this);
2635
2636 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2637 return $sql;
2638 }
2639
00be9182 2640 public function groupBy() {
6a488035 2641 $groupBys = array();
a7488080 2642 if (!empty($this->_params['group_bys']) &&
6a488035
TO
2643 is_array($this->_params['group_bys']) &&
2644 !empty($this->_params['group_bys'])
2645 ) {
2646 foreach ($this->_columns as $tableName => $table) {
2647 if (array_key_exists('group_bys', $table)) {
2648 foreach ($table['group_bys'] as $fieldName => $field) {
a7488080 2649 if (!empty($this->_params['group_bys'][$fieldName])) {
6a488035
TO
2650 $groupBys[] = $field['dbAlias'];
2651 }
2652 }
2653 }
2654 }
2655 }
2656
2657 if (!empty($groupBys)) {
2658 $this->_groupBy = "GROUP BY " . implode(', ', $groupBys);
2659 }
2660 }
2661
00be9182 2662 public function orderBy() {
9d72cede 2663 $this->_orderBy = "";
6a488035
TO
2664 $this->_sections = array();
2665 $this->storeOrderByArray();
9d72cede 2666 if (!empty($this->_orderByArray) && !$this->_rollup == 'WITH ROLLUP') {
6a488035
TO
2667 $this->_orderBy = "ORDER BY " . implode(', ', $this->_orderByArray);
2668 }
2669 $this->assign('sections', $this->_sections);
2670 }
f2947aea 2671
688d37c6 2672 /**
6a488035
TO
2673 * In some cases other functions want to know which fields are selected for ordering by
2674 * Separating this into a separate function allows it to be called separately from constructing
2675 * the order by clause
2676 */
00be9182 2677 public function storeOrderByArray() {
9d72cede 2678 $orderBys = array();
6a488035 2679
a7488080 2680 if (!empty($this->_params['order_bys']) &&
6a488035
TO
2681 is_array($this->_params['order_bys']) &&
2682 !empty($this->_params['order_bys'])
2683 ) {
2684
9907633b 2685 // Process order_bys in user-specified order
6a488035
TO
2686 foreach ($this->_params['order_bys'] as $orderBy) {
2687 $orderByField = array();
2688 foreach ($this->_columns as $tableName => $table) {
2689 if (array_key_exists('order_bys', $table)) {
2690 // For DAO columns defined in $this->_columns
2691 $fields = $table['order_bys'];
2692 }
2693 elseif (array_key_exists('extends', $table)) {
2694 // For custom fields referenced in $this->_customGroupExtends
1efec7ff 2695 $fields = CRM_Utils_Array::value('fields', $table, array());
6a488035 2696 }
6f993086
AH
2697 else {
2698 continue;
2699 }
6a488035
TO
2700 if (!empty($fields) && is_array($fields)) {
2701 foreach ($fields as $fieldName => $field) {
2702 if ($fieldName == $orderBy['column']) {
f2947aea 2703 $orderByField = array_merge($field, $orderBy);
6a488035
TO
2704 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2705 break 2;
2706 }
2707 }
2708 }
2709 }
2710
2711 if (!empty($orderByField)) {
f2947aea 2712 $this->_orderByFields[] = $orderByField;
6a488035
TO
2713 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2714
2715 // Record any section headers for assignment to the template
a7488080 2716 if (!empty($orderBy['section'])) {
b5801e1d 2717 $orderByField['pageBreak'] = CRM_Utils_Array::value('pageBreak', $orderBy);
6a488035
TO
2718 $this->_sections[$orderByField['tplField']] = $orderByField;
2719 }
2720 }
2721 }
2722 }
2723
2724 $this->_orderByArray = $orderBys;
2725
2726 $this->assign('sections', $this->_sections);
2727 }
2728
74cf4551
EM
2729 /**
2730 * @return array
2731 */
00be9182 2732 public function unselectedSectionColumns() {
6a488035
TO
2733 $selectColumns = array();
2734 foreach ($this->_columns as $tableName => $table) {
2735 if (array_key_exists('fields', $table)) {
2736 foreach ($table['fields'] as $fieldName => $field) {
9d72cede
EM
2737 if (!empty($field['required']) ||
2738 !empty($this->_params['fields'][$fieldName])
2739 ) {
6a488035
TO
2740
2741 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2742 }
2743 }
2744 }
2745 }
f2947aea 2746
6a488035
TO
2747 if (is_array($this->_sections)) {
2748 return array_diff_key($this->_sections, $selectColumns);
2749 }
2750 else {
2751 return array();
2752 }
2753 }
2754
74cf4551
EM
2755 /**
2756 * @param $sql
2757 * @param $rows
2758 */
00be9182 2759 public function buildRows($sql, &$rows) {
6a488035
TO
2760 $dao = CRM_Core_DAO::executeQuery($sql);
2761 if (!is_array($rows)) {
2762 $rows = array();
2763 }
2764
2765 // use this method to modify $this->_columnHeaders
2766 $this->modifyColumnHeaders();
2767
2768 $unselectedSectionColumns = $this->unselectedSectionColumns();
2769
2770 while ($dao->fetch()) {
2771 $row = array();
2772 foreach ($this->_columnHeaders as $key => $value) {
2773 if (property_exists($dao, $key)) {
2774 $row[$key] = $dao->$key;
2775 }
2776 }
2777
2778 // section headers not selected for display need to be added to row
2779 foreach ($unselectedSectionColumns as $key => $values) {
2780 if (property_exists($dao, $key)) {
2781 $row[$key] = $dao->$key;
2782 }
2783 }
2784
2785 $rows[] = $row;
2786 }
2787 }
2788
2789 /**
2790 * When "order by" fields are marked as sections, this assigns to the template
2791 * an array of total counts for each section. This data is used by the Smarty
2792 * plugin {sectionTotal}
2793 */
00be9182 2794 public function sectionTotals() {
6a488035
TO
2795
2796 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2797 if (empty($this->_selectAliases)) {
2798 return;
2799 }
2800
2801 if (!empty($this->_sections)) {
2802 // build the query with no LIMIT clause
2803 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select);
2804 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2805
2806 // pull section aliases out of $this->_sections
2807 $sectionAliases = array_keys($this->_sections);
2808
2809 $ifnulls = array();
2810 foreach (array_merge($sectionAliases, $this->_selectAliases) as $alias) {
2811 $ifnulls[] = "ifnull($alias, '') as $alias";
2812 }
2813
971d41b1
CW
2814 // Group (un-limited) report by all aliases and get counts. This might
2815 // be done more efficiently when the contents of $sql are known, ie. by
2816 // overriding this method in the report class.
6a488035 2817
9d72cede
EM
2818 $query = "select " . implode(", ", $ifnulls) .
2819 ", count(*) as ct from ($sql) as subquery group by " .
2820 implode(", ", $sectionAliases);
6a488035
TO
2821
2822 // initialize array of total counts
2823 $totals = array();
2824 $dao = CRM_Core_DAO::executeQuery($query);
2825 while ($dao->fetch()) {
2826
2827 // let $this->_alterDisplay translate any integer ids to human-readable values.
2828 $rows[0] = $dao->toArray();
2829 $this->alterDisplay($rows);
2830 $row = $rows[0];
2831
2832 // add totals for all permutations of section values
9d72cede
EM
2833 $values = array();
2834 $i = 1;
6a488035
TO
2835 $aliasCount = count($sectionAliases);
2836 foreach ($sectionAliases as $alias) {
2837 $values[] = $row[$alias];
2838 $key = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values);
2839 if ($i == $aliasCount) {
2840 // the last alias is the lowest-level section header; use count as-is
2841 $totals[$key] = $dao->ct;
2842 }
2843 else {
2844 // other aliases are higher level; roll count into their total
2845 $totals[$key] += $dao->ct;
2846 }
2847 }
2848 }
2849 $this->assign('sectionTotals', $totals);
2850 }
2851 }
2852
00be9182 2853 public function modifyColumnHeaders() {
6a488035
TO
2854 // use this method to modify $this->_columnHeaders
2855 }
2856
74cf4551
EM
2857 /**
2858 * @param $rows
2859 */
00be9182 2860 public function doTemplateAssignment(&$rows) {
6a488035
TO
2861 $this->assign_by_ref('columnHeaders', $this->_columnHeaders);
2862 $this->assign_by_ref('rows', $rows);
2863 $this->assign('statistics', $this->statistics($rows));
2864 }
2865
74cf4551 2866 /**
4f1f1f2a 2867 * override this method to build your own statistics
74cf4551
EM
2868 * @param $rows
2869 *
2870 * @return array
2871 */
00be9182 2872 public function statistics(&$rows) {
6a488035
TO
2873 $statistics = array();
2874
2875 $count = count($rows);
2876
2877 if ($this->_rollup && ($this->_rollup != '') && $this->_grandFlag) {
2878 $count++;
2879 }
2880
2881 $this->countStat($statistics, $count);
2882
2883 $this->groupByStat($statistics);
2884
2885 $this->filterStat($statistics);
2886
2887 return $statistics;
2888 }
2889
74cf4551
EM
2890 /**
2891 * @param $statistics
2892 * @param $count
2893 */
00be9182 2894 public function countStat(&$statistics, $count) {
9d72cede
EM
2895 $statistics['counts']['rowCount'] = array(
2896 'title' => ts('Row(s) Listed'),
2897 'value' => $count,
6a488035
TO
2898 );
2899
2900 if ($this->_rowsFound && ($this->_rowsFound > $count)) {
9d72cede
EM
2901 $statistics['counts']['rowsFound'] = array(
2902 'title' => ts('Total Row(s)'),
2903 'value' => $this->_rowsFound,
6a488035
TO
2904 );
2905 }
2906 }
2907
74cf4551
EM
2908 /**
2909 * @param $statistics
2910 */
00be9182 2911 public function groupByStat(&$statistics) {
a7488080 2912 if (!empty($this->_params['group_bys']) &&
6a488035
TO
2913 is_array($this->_params['group_bys']) &&
2914 !empty($this->_params['group_bys'])
2915 ) {
2916 foreach ($this->_columns as $tableName => $table) {
2917 if (array_key_exists('group_bys', $table)) {
2918 foreach ($table['group_bys'] as $fieldName => $field) {
a7488080 2919 if (!empty($this->_params['group_bys'][$fieldName])) {
6a488035
TO
2920 $combinations[] = $field['title'];
2921 }
2922 }
2923 }
2924 }
9d72cede
EM
2925 $statistics['groups'][] = array(
2926 'title' => ts('Grouping(s)'),
2927 'value' => implode(' & ', $combinations),
6a488035
TO
2928 );
2929 }
2930 }
2931
74cf4551
EM
2932 /**
2933 * @param $statistics
2934 */
00be9182 2935 public function filterStat(&$statistics) {
6a488035
TO
2936 foreach ($this->_columns as $tableName => $table) {
2937 if (array_key_exists('filters', $table)) {
2938 foreach ($table['filters'] as $fieldName => $field) {
9d72cede
EM
2939 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE &&
2940 CRM_Utils_Array::value('operatorType', $field) !=
2941 CRM_Report_Form::OP_MONTH
2942 ) {
971d41b1
CW
2943 list($from, $to)
2944 = $this->getFromTo(
8f1445ea
DL
2945 CRM_Utils_Array::value("{$fieldName}_relative", $this->_params),
2946 CRM_Utils_Array::value("{$fieldName}_from", $this->_params),
2947 CRM_Utils_Array::value("{$fieldName}_to", $this->_params),
2948 CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params),
2949 CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params)
2950 );
0d8afee2 2951 $from_time_format = !empty($this->_params["{$fieldName}_from_time"]) ? 'h' : 'd';
9d72cede 2952 $from = CRM_Utils_Date::customFormat($from, NULL, array($from_time_format));
6a488035 2953
0d8afee2 2954 $to_time_format = !empty($this->_params["{$fieldName}_to_time"]) ? 'h' : 'd';
9d72cede 2955 $to = CRM_Utils_Date::customFormat($to, NULL, array($to_time_format));
6a488035
TO
2956
2957 if ($from || $to) {
2958 $statistics['filters'][] = array(
2959 'title' => $field['title'],
10a5be27 2960 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
6a488035
TO
2961 );
2962 }
2963 elseif (in_array($rel = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params),
9d72cede
EM
2964 array_keys($this->getOperationPair(CRM_Report_Form::OP_DATE))
2965 )) {
160d32e1 2966 $pair = $this->getOperationPair(CRM_Report_Form::OP_DATE);
6a488035
TO
2967 $statistics['filters'][] = array(
2968 'title' => $field['title'],
2969 'value' => $pair[$rel],
2970 );
2971 }
2972 }
2973 else {
2974 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2975 $value = NULL;
2976 if ($op) {
1b36206c 2977 $pair = $this->getOperationPair(
8f1445ea
DL
2978 CRM_Utils_Array::value('operatorType', $field),
2979 $fieldName
6a488035
TO
2980 );
2981 $min = CRM_Utils_Array::value("{$fieldName}_min", $this->_params);
2982 $max = CRM_Utils_Array::value("{$fieldName}_max", $this->_params);
2983 $val = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
2107cde9
CW
2984 if (in_array($op, array('bw', 'nbw')) && ($min || $max)) {
2985 $value = "{$pair[$op]} $min " . ts('and') . " $max";
2986 }
d3e86119 2987 elseif ($val && CRM_Utils_Array::value('operatorType', $field) & self::OP_ENTITYREF) {
2107cde9 2988 $this->setEntityRefDefaults($field, $tableName);
9d72cede
EM
2989 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
2990 array('id' => $val) +
2991 CRM_Utils_Array::value('api', $field['attributes'], array()));
2107cde9
CW
2992 $values = array();
2993 foreach ($result['values'] as $v) {
2994 $values[] = $v['label'];
2995 }
2996 $value = "{$pair[$op]} " . implode(', ', $values);
6a488035
TO
2997 }
2998 elseif ($op == 'nll' || $op == 'nnll') {
2999 $value = $pair[$op];
3000 }
3001 elseif (is_array($val) && (!empty($val))) {
f974e915 3002 $options = CRM_Utils_Array::value('options', $field, array());
6a488035
TO
3003 foreach ($val as $key => $valIds) {
3004 if (isset($options[$valIds])) {
3005 $val[$key] = $options[$valIds];
3006 }
3007 }
9d72cede
EM
3008 $pair[$op] = (count($val) == 1) ? (($op == 'notin' || $op ==
3009 'mnot') ? ts('Is Not') : ts('Is')) : CRM_Utils_Array::value($op, $pair);
3010 $val = implode(', ', $val);
3011 $value = "{$pair[$op]} " . $val;
6a488035 3012 }
9d72cede
EM
3013 elseif (!is_array($val) && (!empty($val) || $val == '0') &&
3014 isset($field['options']) &&
6a488035
TO
3015 is_array($field['options']) && !empty($field['options'])
3016 ) {
9d72cede
EM
3017 $value = CRM_Utils_Array::value($op, $pair) . " " .
3018 CRM_Utils_Array::value($val, $field['options'], $val);
6a488035
TO
3019 }
3020 elseif ($val) {
3021 $value = CRM_Utils_Array::value($op, $pair) . " " . $val;
3022 }
3023 }
3024 if ($value) {
9d72cede
EM
3025 $statistics['filters'][] = array(
3026 'title' => CRM_Utils_Array::value('title', $field),
3027 'value' => $value,
6a488035
TO
3028 );
3029 }
3030 }
3031 }
3032 }
3033 }
3034 }
3035
74cf4551 3036 /**
7d7c50f9
EM
3037 * End post processing.
3038 *
3039 * @param array|null $rows
74cf4551 3040 */
00be9182 3041 public function endPostProcess(&$rows = NULL) {
9d72cede 3042 if ($this->_storeResultSet) {
ae555e90
DS
3043 $this->_resultSet = $rows;
3044 }
3045
6a488035
TO
3046 if ($this->_outputMode == 'print' ||
3047 $this->_outputMode == 'pdf' ||
3048 $this->_sendmail
3049 ) {
3050
3051 $content = $this->compileContent();
3052 $url = CRM_Utils_System::url("civicrm/report/instance/{$this->_id}",
9d72cede 3053 "reset=1", TRUE
6a488035
TO
3054 );
3055
3056 if ($this->_sendmail) {
3057 $config = CRM_Core_Config::singleton();
3058 $attachments = array();
3059
3060 if ($this->_outputMode == 'csv') {
971d41b1
CW
3061 $content
3062 = $this->_formValues['report_header'] . '<p>' . ts('Report URL') .
9d72cede
EM
3063 ": {$url}</p>" . '<p>' .
3064 ts('The report is attached as a CSV file.') . '</p>' .
3065 $this->_formValues['report_footer'];
3066
3067 $csvFullFilename = $config->templateCompileDir .
3068 CRM_Utils_File::makeFileName('CiviReport.csv');
6a488035
TO
3069 $csvContent = CRM_Report_Utils_Report::makeCsv($this, $rows);
3070 file_put_contents($csvFullFilename, $csvContent);
3071 $attachments[] = array(
3072 'fullPath' => $csvFullFilename,
3073 'mime_type' => 'text/csv',
3074 'cleanName' => 'CiviReport.csv',
3075 );
3076 }
3077 if ($this->_outputMode == 'pdf') {
3078 // generate PDF content
9d72cede
EM
3079 $pdfFullFilename = $config->templateCompileDir .
3080 CRM_Utils_File::makeFileName('CiviReport.pdf');
6a488035
TO
3081 file_put_contents($pdfFullFilename,
3082 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf",
3083 TRUE, array('orientation' => 'landscape')
3084 )
3085 );
3086 // generate Email Content
971d41b1
CW
3087 $content
3088 = $this->_formValues['report_header'] . '<p>' . ts('Report URL') .
9d72cede
EM
3089 ": {$url}</p>" . '<p>' .
3090 ts('The report is attached as a PDF file.') . '</p>' .
3091 $this->_formValues['report_footer'];
6a488035
TO
3092
3093 $attachments[] = array(
3094 'fullPath' => $pdfFullFilename,
3095 'mime_type' => 'application/pdf',
3096 'cleanName' => 'CiviReport.pdf',
3097 );
3098 }
3099
3100 if (CRM_Report_Utils_Report::mailReport($content, $this->_id,
9d72cede
EM
3101 $this->_outputMode, $attachments
3102 )
3103 ) {
6a488035
TO
3104 CRM_Core_Session::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3105 }
3106 else {
3107 CRM_Core_Session::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3108 }
824aede6 3109 return TRUE;
6a488035
TO
3110 }
3111 elseif ($this->_outputMode == 'print') {
3112 echo $content;
3113 }
3114 else {
3115 if ($chartType = CRM_Utils_Array::value('charts', $this->_params)) {
3116 $config = CRM_Core_Config::singleton();
3117 //get chart image name
3118 $chartImg = $this->_chartId . '.png';
3119 //get image url path
971d41b1
CW
3120 $uploadUrl
3121 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL) .
9d72cede 3122 'openFlashChart/';
6a488035
TO
3123 $uploadUrl .= $chartImg;
3124 //get image doc path to overwrite
971d41b1
CW
3125 $uploadImg
3126 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir) .
9d72cede 3127 'openFlashChart/' . $chartImg;
6a488035
TO
3128 //Load the image
3129 $chart = imagecreatefrompng($uploadUrl);
2fe3c48d 3130 //convert it into formatted png
6a488035
TO
3131 header('Content-type: image/png');
3132 //overwrite with same image
3133 imagepng($chart, $uploadImg);
3134 //delete the object
3135 imagedestroy($chart);
3136 }
3137 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3138 }
3139 CRM_Utils_System::civiExit();
3140 }
3141 elseif ($this->_outputMode == 'csv') {
3142 CRM_Report_Utils_Report::export2csv($this, $rows);
3143 }
3144 elseif ($this->_outputMode == 'group') {
3145 $group = $this->_params['groups'];
3146 $this->add2group($group);
3147 }
3148 elseif ($this->_instanceButtonName == $this->controller->getButtonName()) {
3149 CRM_Report_Form_Instance::postProcess($this);
3150 }
3151 elseif ($this->_createNewButtonName == $this->controller->getButtonName() ||
9d72cede
EM
3152 $this->_outputMode == 'create_report'
3153 ) {
6a488035
TO
3154 $this->_createNew = TRUE;
3155 CRM_Report_Form_Instance::postProcess($this);
3156 }
3157 }
8f1445ea 3158
8a925f33 3159 /**
7d7c50f9
EM
3160 * Set store result set indicator to TRUE.
3161 *
8a925f33
EM
3162 * @todo explain what this does
3163 */
00be9182 3164 public function storeResultSet() {
ae555e90
DS
3165 $this->_storeResultSet = TRUE;
3166 }
3167
74cf4551 3168 /**
7d7c50f9
EM
3169 * Get result set.
3170 *
74cf4551
EM
3171 * @return bool
3172 */
00be9182 3173 public function getResultSet() {
ae555e90
DS
3174 return $this->_resultSet;
3175 }
3176
74cf4551 3177 /**
fe482240 3178 * Use the form name to create the tpl file name.
74cf4551
EM
3179 *
3180 * @return string
74cf4551 3181 */
00be9182 3182 public function getTemplateFileName() {
6a488035 3183 $defaultTpl = parent::getTemplateFileName();
9d72cede 3184 $template = CRM_Core_Smarty::singleton();
6a488035
TO
3185 if (!$template->template_exists($defaultTpl)) {
3186 $defaultTpl = 'CRM/Report/Form.tpl';
3187 }
3188 return $defaultTpl;
3189 }
3190
688d37c6 3191 /**
fe482240 3192 * Compile the report content.
688d37c6 3193 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
6a488035 3194 *
74cf4551
EM
3195 * @return string
3196 */
00be9182 3197 public function compileContent() {
8aac22c8 3198 $templateFile = $this->getHookedTemplateFileName();
9d72cede
EM
3199 return $this->_formValues['report_header'] .
3200 CRM_Core_Form::$_template->fetch($templateFile) .
3201 $this->_formValues['report_footer'];
6a488035
TO
3202 }
3203
3204
00be9182 3205 public function postProcess() {
6a488035
TO
3206 // get ready with post process params
3207 $this->beginPostProcess();
3208
3209 // build query
3210 $sql = $this->buildQuery();
3211
3212 // build array of result based on column headers. This method also allows
3213 // modifying column headers before using it to build result set i.e $rows.
3214 $rows = array();
3215 $this->buildRows($sql, $rows);
3216
3217 // format result set.
3218 $this->formatDisplay($rows);
3219
3220 // assign variables to templates
3221 $this->doTemplateAssignment($rows);
3222
3223 // do print / pdf / instance stuff if needed
3224 $this->endPostProcess($rows);
3225 }
3226
74cf4551
EM
3227 /**
3228 * @param int $rowCount
688d37c6 3229 * @return array
74cf4551 3230 */
00be9182 3231 public function limit($rowCount = self::ROW_COUNT_LIMIT) {
6a488035
TO
3232 // lets do the pager if in html mode
3233 $this->_limit = NULL;
77b97be7 3234
dbb4a0f9
PN
3235 // CRM-14115, over-ride row count if rowCount is specified in URL
3236 if ($this->_dashBoardRowCount) {
3237 $rowCount = $this->_dashBoardRowCount;
3238 }
6a488035
TO
3239 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
3240 $this->_select = str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select);
3241
3242 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
3243
8a925f33
EM
3244 // @todo all http vars should be extracted in the preProcess
3245 // - not randomly in the class
6a488035
TO
3246 if (!$pageId && !empty($_POST)) {
3247 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
8a925f33 3248 $pageId = max((int) $_POST['crmPID_B'], 1);
6a488035
TO
3249 }
3250 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
8a925f33 3251 $pageId = max((int) $_POST['crmPID'], 1);
6a488035
TO
3252 }
3253 unset($_POST['crmPID_B'], $_POST['crmPID']);
3254 }
3255
3256 $pageId = $pageId ? $pageId : 1;
3257 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
3258 $offset = ($pageId - 1) * $rowCount;
3259
bf00d1b6
DL
3260 $offset = CRM_Utils_Type::escape($offset, 'Int');
3261 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
3262
dd3a4117 3263 $this->_limit = " LIMIT $offset, $rowCount";
6a488035
TO
3264 return array($offset, $rowCount);
3265 }
9d72cede
EM
3266 if ($this->_limitValue) {
3267 if ($this->_offsetValue) {
6f900755
E
3268 $this->_limit = " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3269 }
3270 else {
3271 $this->_limit = " LIMIT " . $this->_limitValue;
3272 }
3273 }
6a488035
TO
3274 }
3275
74cf4551
EM
3276 /**
3277 * @param int $rowCount
3278 */
00be9182 3279 public function setPager($rowCount = self::ROW_COUNT_LIMIT) {
dbb4a0f9
PN
3280
3281 // CRM-14115, over-ride row count if rowCount is specified in URL
3282 if ($this->_dashBoardRowCount) {
3283 $rowCount = $this->_dashBoardRowCount;
3284 }
3285
6a488035 3286 if ($this->_limit && ($this->_limit != '')) {
9d72cede 3287 $sql = "SELECT FOUND_ROWS();";
6a488035 3288 $this->_rowsFound = CRM_Core_DAO::singleValueQuery($sql);
9d72cede 3289 $params = array(
6a488035
TO
3290 'total' => $this->_rowsFound,
3291 'rowCount' => $rowCount,
3292 'status' => ts('Records') . ' %%StatusMessage%%',
3293 'buttonBottom' => 'PagerBottomButton',
3294 'buttonTop' => 'PagerTopButton',
3295 'pageID' => $this->get(CRM_Utils_Pager::PAGE_ID),
3296 );
3297
3298 $pager = new CRM_Utils_Pager($params);
3299 $this->assign_by_ref('pager', $pager);
ecc20f0e 3300 $this->ajaxResponse['totalRows'] = $this->_rowsFound;
6a488035
TO
3301 }
3302 }
3303
74cf4551
EM
3304 /**
3305 * @param $field
3306 * @param $value
3307 * @param $op
3308 *
3309 * @return string
3310 */
00be9182 3311 public function whereGroupClause($field, $value, $op) {
6a488035
TO
3312
3313 $smartGroupQuery = "";
3314
3315 $group = new CRM_Contact_DAO_Group();
3316 $group->is_active = 1;
3317 $group->find();
3318 $smartGroups = array();
3319 while ($group->fetch()) {
9d72cede
EM
3320 if (in_array($group->id, $this->_params['gid_value']) &&
3321 $group->saved_search_id
3322 ) {
6a488035
TO
3323 $smartGroups[] = $group->id;
3324 }
3325 }
3326
3327 CRM_Contact_BAO_GroupContactCache::check($smartGroups);
3328
3329 $smartGroupQuery = '';
3330 if (!empty($smartGroups)) {
3331 $smartGroups = implode(',', $smartGroups);
3332 $smartGroupQuery = " UNION DISTINCT
3333 SELECT DISTINCT smartgroup_contact.contact_id
3334 FROM civicrm_group_contact_cache smartgroup_contact
3335 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3336 }
3337
29fc2b79 3338 $sqlOp = $this->getSQLOperator($op);
6a488035
TO
3339 if (!is_array($value)) {
3340 $value = array($value);
3341 }
3342 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3343
3344 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3345 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3346 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3347 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3348 {$smartGroupQuery} ) ";
3349 }
3350
74cf4551
EM
3351 /**
3352 * @param $field
3353 * @param $value
3354 * @param $op
3355 *
3356 * @return string
3357 */
00be9182 3358 public function whereTagClause($field, $value, $op) {
6a488035
TO
3359 // not using left join in query because if any contact
3360 // belongs to more than one tag, results duplicate
3361 // entries.
29fc2b79 3362 $sqlOp = $this->getSQLOperator($op);
6a488035
TO
3363 if (!is_array($value)) {
3364 $value = array($value);
3365 }
3366 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
ed795723
JM
3367 $entity_table = $this->_tagFilterTable;
3368 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
6a488035
TO
3369 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3370 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
ed795723 3371 WHERE entity_table = '$entity_table' AND {$clause} ) ";
6a488035
TO
3372 }
3373
f587aa17
EM
3374 /**
3375 * Generate membership organization clause.
3376 *
3377 * @param mixed $value
3378 * @param string $op SQL Operator
3379 *
3380 * @return string
3381 */
3382 public function whereMembershipOrgClause($value, $op) {
114a2c85
DG
3383 $sqlOp = $this->getSQLOperator($op);
3384 if (!is_array($value)) {
3385 $value = array($value);
3386 }
258e2add 3387
114a2c85
DG
3388 $tmp_membership_org_sql_list = implode(', ', $value);
3389 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
97709b72 3390 SELECT DISTINCT mem.contact_id
258e2add 3391 FROM civicrm_membership mem
97709b72 3392 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
258e2add 3393 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
9d72cede
EM
3394 WHERE mt.member_of_contact_id IN (" .
3395 $tmp_membership_org_sql_list . ")
97709b72
DG
3396 AND mt.is_active = '1'
3397 AND mem_status.is_current_member = '1'
3398 AND mem_status.is_active = '1' ) ";
9d72cede 3399 }
114a2c85 3400
f587aa17 3401 /**
fe482240 3402 * Generate Membership Type SQL Clause.
f587aa17
EM
3403 * @param mixed $value
3404 * @param string $op
3405 *
3406 * @return string
3407 * SQL query string
3408 */
3409 public function whereMembershipTypeClause($value, $op) {
114a2c85
DG
3410 $sqlOp = $this->getSQLOperator($op);
3411 if (!is_array($value)) {
3412 $value = array($value);
3413 }
258e2add 3414
9d72cede 3415 $tmp_membership_sql_list = implode(', ', $value);
114a2c85 3416 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
97709b72 3417 SELECT DISTINCT mem.contact_id
258e2add 3418 FROM civicrm_membership mem
3419 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3420 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
9d72cede
EM
3421 WHERE mem.membership_type_id IN (" .
3422 $tmp_membership_sql_list . ")
97709b72
DG
3423 AND mt.is_active = '1'
3424 AND mem_status.is_current_member = '1'
3425 AND mem_status.is_active = '1' ) ";
114a2c85 3426 }
258e2add 3427
74cf4551
EM
3428 /**
3429 * @param string $tableAlias
3430 */
00be9182 3431 public function buildACLClause($tableAlias = 'contact_a') {
6a488035
TO
3432 list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
3433 }
3434
74cf4551
EM
3435 /**
3436 * @param bool $addFields
3437 * @param array $permCustomGroupIds
3438 */
00be9182 3439 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
6a488035
TO
3440 if (empty($this->_customGroupExtends)) {
3441 return;
3442 }
3443 if (!is_array($this->_customGroupExtends)) {
3444 $this->_customGroupExtends = array($this->_customGroupExtends);
3445 }
3446 $customGroupWhere = '';
3447 if (!empty($permCustomGroupIds)) {
9d72cede
EM
3448 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3449 ") AND";
6a488035
TO
3450 }
3451 $sql = "
3452SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3453 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3454FROM civicrm_custom_group cg
3455INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3456WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
3457 {$customGroupWhere}
3458 cg.is_active = 1 AND
3459 cf.is_active = 1 AND
3460 cf.is_searchable = 1
3461ORDER BY cg.weight, cf.weight";
3462 $customDAO = CRM_Core_DAO::executeQuery($sql);
3463
3464 $curTable = NULL;
3465 while ($customDAO->fetch()) {
3466 if ($customDAO->table_name != $curTable) {
3467 $curTable = $customDAO->table_name;
3468 $curFields = $curFilters = array();
3469
3470 // dummy dao object
3471 $this->_columns[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3472 $this->_columns[$curTable]['extends'] = $customDAO->extends;
3473 $this->_columns[$curTable]['grouping'] = $customDAO->table_name;
3474 $this->_columns[$curTable]['group_title'] = $customDAO->title;
3475
3476 foreach (array(
9d72cede
EM
3477 'fields',
3478 'filters',
21dfd5f5 3479 'group_bys',
9d72cede 3480 ) as $colKey) {
6a488035
TO
3481 if (!array_key_exists($colKey, $this->_columns[$curTable])) {
3482 $this->_columns[$curTable][$colKey] = array();
3483 }
3484 }
3485 }
3486 $fieldName = 'custom_' . $customDAO->cf_id;
3487
3488 if ($addFields) {
3489 // this makes aliasing work in favor
3490 $curFields[$fieldName] = array(
3491 'name' => $customDAO->column_name,
3492 'title' => $customDAO->label,
3493 'dataType' => $customDAO->data_type,
3494 'htmlType' => $customDAO->html_type,
3495 );
3496 }
3497 if ($this->_customGroupFilters) {
3498 // this makes aliasing work in favor
3499 $curFilters[$fieldName] = array(
3500 'name' => $customDAO->column_name,
3501 'title' => $customDAO->label,
3502 'dataType' => $customDAO->data_type,
3503 'htmlType' => $customDAO->html_type,
3504 );
3505 }
3506
3507 switch ($customDAO->data_type) {
3508 case 'Date':
3509 // filters
3510 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE;
3511 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_DATE;
3512 // CRM-6946, show time part for datetime date fields
3513 if ($customDAO->time_format) {
3514 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_TIMESTAMP;
3515 }
3516 break;
3517
3518 case 'Boolean':
3519 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT;
9d72cede
EM
3520 $curFilters[$fieldName]['options'] = array(
3521 '' => ts('- select -'),
3522 1 => ts('Yes'),
3523 0 => ts('No'),
6a488035
TO
3524 );
3525 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
3526 break;
3527
3528 case 'Int':
3529 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_INT;
3530 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
3531 break;
3532
3533 case 'Money':
3534 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
3535 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_MONEY;
3536 break;
3537
3538 case 'Float':
3539 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
3540 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_FLOAT;
3541 break;
3542
3543 case 'String':
3544 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3545
3546 if (!empty($customDAO->option_group_id)) {
3547 if (in_array($customDAO->html_type, array(
9d72cede
EM
3548 'Multi-Select',
3549 'AdvMulti-Select',
21dfd5f5 3550 'CheckBox',
9d72cede 3551 ))) {
6a488035
TO
3552 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
3553 }
3554 else {
3555 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
3556 }
3557 if ($this->_customGroupFilters) {
3558 $curFilters[$fieldName]['options'] = array();
9d72cede 3559 $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
3560 1 => array(
3561 $customDAO->option_group_id,
21dfd5f5
TO
3562 'Integer',
3563 ),
86bd39be 3564 ));
6a488035
TO
3565 while ($ogDAO->fetch()) {
3566 $curFilters[$fieldName]['options'][$ogDAO->value] = $ogDAO->label;
3567 }
6e57f5ca 3568 CRM_Utils_Hook::customFieldOptions($customDAO->cf_id, $curFilters[$fieldName]['options'], FALSE);
6a488035
TO
3569 }
3570 }
3571 break;
3572
3573 case 'StateProvince':
3574 if (in_array($customDAO->html_type, array(
21dfd5f5 3575 'Multi-Select State/Province',
9d72cede 3576 ))) {
6a488035
TO
3577 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
3578 }
3579 else {
3580 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
3581 }
3582 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::stateProvince();
3583 break;
3584
3585 case 'Country':
3586 if (in_array($customDAO->html_type, array(
21dfd5f5 3587 'Multi-Select Country',
9d72cede 3588 ))) {
6a488035
TO
3589 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
3590 }
3591 else {
3592 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
3593 }
3594 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::country();
3595 break;
3596
3597 case 'ContactReference':
3598 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3599 $curFilters[$fieldName]['name'] = 'display_name';
3600 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3601
3602 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3603 $curFields[$fieldName]['name'] = 'display_name';
3604 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3605 break;
3606
3607 default:
3608 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3609 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3610 }
3611
3612 if (!array_key_exists('type', $curFields[$fieldName])) {
fc161185 3613 $curFields[$fieldName]['type'] = CRM_Utils_Array::value('type', $curFilters[$fieldName], array());
6a488035
TO
3614 }
3615
3616 if ($addFields) {
3617 $this->_columns[$curTable]['fields'] = array_merge($this->_columns[$curTable]['fields'], $curFields);
3618 }
3619 if ($this->_customGroupFilters) {
3620 $this->_columns[$curTable]['filters'] = array_merge($this->_columns[$curTable]['filters'], $curFilters);
3621 }
3622 if ($this->_customGroupGroupBy) {
3623 $this->_columns[$curTable]['group_bys'] = array_merge($this->_columns[$curTable]['group_bys'], $curFields);
3624 }
3625 }
3626 }
3627
00be9182 3628 public function customDataFrom() {
6a488035
TO
3629 if (empty($this->_customGroupExtends)) {
3630 return;
3631 }
3632 $mapper = CRM_Core_BAO_CustomQuery::$extendsMap;
3633
3634 foreach ($this->_columns as $table => $prop) {
9d72cede
EM
3635 if (substr($table, 0, 13) == 'civicrm_value' ||
3636 substr($table, 0, 12) == 'custom_value'
3637 ) {
6a488035
TO
3638 $extendsTable = $mapper[$prop['extends']];
3639
3640 // check field is in params
3641 if (!$this->isFieldSelected($prop)) {
3642 continue;
3643 }
4c9d78ea 3644 $baseJoin = CRM_Utils_Array::value($prop['extends'], $this->_customGroupExtendsJoin, "{$this->_aliases[$extendsTable]}.id");
6a488035 3645
9d72cede 3646 $customJoin = is_array($this->_customGroupJoin) ? $this->_customGroupJoin[$table] : $this->_customGroupJoin;
6a488035 3647 $this->_from .= "
aa1aa08e 3648{$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
6a488035
TO
3649 // handle for ContactReference
3650 if (array_key_exists('fields', $prop)) {
3651 foreach ($prop['fields'] as $fieldName => $field) {
9d72cede
EM
3652 if (CRM_Utils_Array::value('dataType', $field) ==
3653 'ContactReference'
3654 ) {
6a488035
TO
3655 $columnName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField::getKeyID($fieldName), 'column_name');
3656 $this->_from .= "
3657LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3658 }
3659 }
3660 }
3661 }
3662 }
3663 }
3664
74cf4551
EM
3665 /**
3666 * @param $prop
3667 *
3668 * @return bool
3669 */
00be9182 3670 public function isFieldSelected($prop) {
6a488035
TO
3671 if (empty($prop)) {
3672 return FALSE;
3673 }
3674
3675 if (!empty($this->_params['fields'])) {
3676 foreach (array_keys($prop['fields']) as $fieldAlias) {
3677 $customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias);
3678 if ($customFieldId) {
3679 if (array_key_exists($fieldAlias, $this->_params['fields'])) {
3680 return TRUE;
3681 }
3682
3683 //might be survey response field.
9d72cede
EM
3684 if (!empty($this->_params['fields']['survey_response']) &&
3685 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3686 ) {
6a488035
TO
3687 return TRUE;
3688 }
3689 }
3690 }
3691 }
3692
3693 if (!empty($this->_params['group_bys']) && $this->_customGroupGroupBy) {
3694 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
9d72cede
EM
3695 if (array_key_exists($fieldAlias, $this->_params['group_bys']) &&
3696 CRM_Core_BAO_CustomField::getKeyID($fieldAlias)
3697 ) {
6a488035
TO
3698 return TRUE;
3699 }
3700 }
3701 }
3702
3703 if (!empty($this->_params['order_bys'])) {
3704 foreach (array_keys($prop['fields']) as $fieldAlias) {
3705 foreach ($this->_params['order_bys'] as $orderBy) {
9d72cede
EM
3706 if ($fieldAlias == $orderBy['column'] &&
3707 CRM_Core_BAO_CustomField::getKeyID($fieldAlias)
3708 ) {
6a488035
TO
3709 return TRUE;
3710 }
3711 }
3712 }
3713 }
3714
3715 if (!empty($prop['filters']) && $this->_customGroupFilters) {
3716 foreach ($prop['filters'] as $fieldAlias => $val) {
3717 foreach (array(
9d72cede
EM
3718 'value',
3719 'min',
3720 'max',
3721 'relative',
3722 'from',
21dfd5f5 3723 'to',
9d72cede 3724 ) as $attach) {
6a488035 3725 if (isset($this->_params[$fieldAlias . '_' . $attach]) &&
dfe4b2f5 3726 (!empty($this->_params[$fieldAlias . '_' . $attach])
9d72cede
EM
3727 || ($attach != 'relative' &&
3728 $this->_params[$fieldAlias . '_' . $attach] == '0')
dfe4b2f5 3729 )
9d72cede 3730 ) {
6a488035
TO
3731 return TRUE;
3732 }
3733 }
a7488080 3734 if (!empty($this->_params[$fieldAlias . '_op']) &&
6a488035
TO
3735 in_array($this->_params[$fieldAlias . '_op'], array('nll', 'nnll'))
3736 ) {
3737 return TRUE;
3738 }
3739 }
3740 }
3741
3742 return FALSE;
3743 }
3744
3745 /**
3746 * Check for empty order_by configurations and remove them; also set
3747 * template to hide them.
537c70b8
EM
3748 *
3749 * @param array $formValues
6a488035 3750 */
00be9182 3751 public function preProcessOrderBy(&$formValues) {
6a488035 3752 // Object to show/hide form elements
ae555e90 3753 $_showHide = new CRM_Core_ShowHideBlocks('', '');
6a488035
TO
3754
3755 $_showHide->addShow('optionField_1');
3756
3757 // Cycle through order_by options; skip any empty ones, and hide them as well
3758 $n = 1;
3759
3760 if (!empty($formValues['order_bys'])) {
3761 foreach ($formValues['order_bys'] as $order_by) {
3762 if ($order_by['column'] && $order_by['column'] != '-') {
3763 $_showHide->addShow('optionField_' . $n);
3764 $orderBys[$n] = $order_by;
3765 $n++;
3766 }
3767 }
3768 }
3769 for ($i = $n; $i <= 5; $i++) {
3770 if ($i > 1) {
3771 $_showHide->addHide('optionField_' . $i);
3772 }
3773 }
3774
3775 // overwrite order_by options with modified values
3776 if (!empty($orderBys)) {
3777 $formValues['order_bys'] = $orderBys;
3778 }
3779 else {
3780 $formValues['order_bys'] = array(1 => array('column' => '-'));
3781 }
3782
3783 // assign show/hide data to template
3784 $_showHide->addToTemplate();
3785 }
3786
3787 /**
3788 * Does table name have columns in SELECT clause?
3789 *
7e06c9f5
TO
3790 * @param string $tableName
3791 * Name of table (index of $this->_columns array).
6a488035
TO
3792 *
3793 * @return bool
3794 */
00be9182 3795 public function isTableSelected($tableName) {
6a488035
TO
3796 return in_array($tableName, $this->selectedTables());
3797 }
3798
3799 /**
fe482240 3800 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
6a488035
TO
3801 * (building the array if it's unset)
3802 *
971d41b1
CW
3803 * @return array
3804 * selectedTables
6a488035 3805 */
00be9182 3806 public function selectedTables() {
6a488035
TO
3807 if (!$this->_selectedTables) {
3808 $orderByColumns = array();
9d72cede
EM
3809 if (array_key_exists('order_bys', $this->_params) &&
3810 is_array($this->_params['order_bys'])
3811 ) {
6a488035
TO
3812 foreach ($this->_params['order_bys'] as $orderBy) {
3813 $orderByColumns[] = $orderBy['column'];
3814 }
3815 }
3816
3817 foreach ($this->_columns as $tableName => $table) {
3818 if (array_key_exists('fields', $table)) {
3819 foreach ($table['fields'] as $fieldName => $field) {
9d72cede
EM
3820 if (!empty($field['required']) ||
3821 !empty($this->_params['fields'][$fieldName])
3822 ) {
6a488035
TO
3823 $this->_selectedTables[] = $tableName;
3824 break;
3825 }
3826 }
3827 }
3828 if (array_key_exists('order_bys', $table)) {
3829 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3830 if (in_array($orderByName, $orderByColumns)) {
3831 $this->_selectedTables[] = $tableName;
3832 break;
3833 }
3834 }
3835 }
3836 if (array_key_exists('filters', $table)) {
3837 foreach ($table['filters'] as $filterName => $filter) {
a7488080 3838 if (!empty($this->_params["{$filterName}_value"]) ||
9d72cede
EM
3839 CRM_Utils_Array::value("{$filterName}_op", $this->_params) ==
3840 'nll' ||
3841 CRM_Utils_Array::value("{$filterName}_op", $this->_params) ==
3842 'nnll'
6a488035
TO
3843 ) {
3844 $this->_selectedTables[] = $tableName;
3845 break;
3846 }
3847 }
3848 }
3849 }
3850 }
3851 return $this->_selectedTables;
3852 }
3853
850e4640
E
3854 /**
3855 * @deprecated - use getAddressColumns which is a more accurate description
3856 * and also accepts an array of options rather than a long list
3857 *
c490a46a 3858 * adding address fields to construct function in reports
77b97be7 3859 *
7e06c9f5
TO
3860 * @param bool $groupBy
3861 * Add GroupBy? Not appropriate for detail report.
3862 * @param bool $orderBy
3863 * Add GroupBy? Not appropriate for detail report.
77b97be7
EM
3864 * @param bool $filters
3865 * @param array $defaults
3866 *
a6c01b45
CW
3867 * @return array
3868 * address fields for construct clause
6a488035 3869 */
00be9182 3870 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
6a488035 3871 $addressFields = array(
9d72cede 3872 'civicrm_address' => array(
6a488035 3873 'dao' => 'CRM_Core_DAO_Address',
9d72cede
EM
3874 'fields' => array(
3875 'name' => array(
3876 'title' => ts('Address Name'),
6a488035
TO
3877 'default' => CRM_Utils_Array::value('name', $defaults, FALSE),
3878 ),
9d72cede
EM
3879 'street_address' => array(
3880 'title' => ts('Street Address'),
6a488035
TO
3881 'default' => CRM_Utils_Array::value('street_address', $defaults, FALSE),
3882 ),
9d72cede
EM
3883 'supplemental_address_1' => array(
3884 'title' => ts('Supplementary Address Field 1'),
6a488035
TO
3885 'default' => CRM_Utils_Array::value('supplemental_address_1', $defaults, FALSE),
3886 ),
9d72cede
EM
3887 'supplemental_address_2' => array(
3888 'title' => ts('Supplementary Address Field 2'),
6a488035
TO
3889 'default' => CRM_Utils_Array::value('supplemental_address_2', $defaults, FALSE),
3890 ),
9d72cede 3891 'street_number' => array(
6a488035
TO
3892 'name' => 'street_number',
3893 'title' => ts('Street Number'),
3894 'type' => 1,
3895 'default' => CRM_Utils_Array::value('street_number', $defaults, FALSE),
3896 ),
9d72cede 3897 'street_name' => array(
6a488035
TO
3898 'name' => 'street_name',
3899 'title' => ts('Street Name'),
3900 'type' => 1,
3901 'default' => CRM_Utils_Array::value('street_name', $defaults, FALSE),
3902 ),
9d72cede 3903 'street_unit' => array(
6a488035
TO
3904 'name' => 'street_unit',
3905 'title' => ts('Street Unit'),
3906 'type' => 1,
3907 'default' => CRM_Utils_Array::value('street_unit', $defaults, FALSE),
3908 ),
9d72cede
EM
3909 'city' => array(
3910 'title' => ts('City'),
6a488035
TO
3911 'default' => CRM_Utils_Array::value('city', $defaults, FALSE),
3912 ),
9d72cede
EM
3913 'postal_code' => array(
3914 'title' => ts('Postal Code'),
6a488035 3915 'default' => CRM_Utils_Array::value('postal_code', $defaults, FALSE),
4cbdd2b1 3916 ),
9d72cede
EM
3917 'postal_code_suffix' => array(
3918 'title' => ts('Postal Code Suffix'),
4cbdd2b1 3919 'default' => CRM_Utils_Array::value('postal_code_suffix', $defaults, FALSE),
6a488035 3920 ),
9d72cede
EM
3921 'country_id' => array(
3922 'title' => ts('Country'),
3923 'default' => CRM_Utils_Array::value('country_id', $defaults, FALSE),
3924 ),
3925 'state_province_id' => array(
3926 'title' => ts('State/Province'),
6a488035
TO
3927 'default' => CRM_Utils_Array::value('state_province_id', $defaults, FALSE),
3928 ),
9d72cede
EM
3929 'county_id' => array(
3930 'title' => ts('County'),
3931 'default' => CRM_Utils_Array::value('county_id', $defaults, FALSE),
3932 ),
6a488035
TO
3933 ),
3934 'grouping' => 'location-fields',
3935 ),
3936 );
3937
3938 if ($filters) {
3939 $addressFields['civicrm_address']['filters'] = array(
9d72cede
EM
3940 'street_number' => array(
3941 'title' => ts('Street Number'),
3942 'type' => 1,
3943 'name' => 'street_number',
6a488035 3944 ),
9d72cede
EM
3945 'street_name' => array(
3946 'title' => ts('Street Name'),
3947 'name' => 'street_name',
3948 'operator' => 'like',
6a488035 3949 ),
9d72cede
EM
3950 'postal_code' => array(
3951 'title' => ts('Postal Code'),
3952 'type' => 1,
3953 'name' => 'postal_code',
6a488035 3954 ),
9d72cede
EM
3955 'city' => array(
3956 'title' => ts('City'),
3957 'operator' => 'like',
3958 'name' => 'city',
6a488035 3959 ),
863581d1
CW
3960 'country_id' => array(
3961 'name' => 'country_id',
3962 'title' => ts('Country'),
6a488035 3963 'type' => CRM_Utils_Type::T_INT,
9d72cede 3964 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
c927c151 3965 'options' => CRM_Core_PseudoConstant::country(),
6a488035
TO
3966 ),
3967 'state_province_id' => array(
3968 'name' => 'state_province_id',
3969 'title' => ts('State/Province'),
3970 'type' => CRM_Utils_Type::T_INT,
c927c151
CW
3971 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
3972 'options' => array(),
6a488035 3973 ),
863581d1
CW
3974 'county_id' => array(
3975 'name' => 'county_id',
3976 'title' => ts('County'),
6a488035 3977 'type' => CRM_Utils_Type::T_INT,
c927c151
CW
3978 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
3979 'options' => array(),
6a488035
TO
3980 ),
3981 );
3982 }
3983
3984 if ($orderBy) {
9d72cede
EM
3985 $addressFields['civicrm_address']['order_bys'] = array(
3986 'street_name' => array('title' => ts('Street Name')),
3987 'street_number' => array('title' => 'Odd / Even Street Number'),
3988 'street_address' => NULL,
3989 'city' => NULL,
3990 'postal_code' => NULL,
6a488035
TO
3991 );
3992 }
3993
3994 if ($groupBy) {
3995 $addressFields['civicrm_address']['group_bys'] = array(
3996 'street_address' => NULL,
3997 'city' => NULL,
3998 'postal_code' => NULL,
9d72cede
EM
3999 'state_province_id' => array(
4000 'title' => ts('State/Province'),
6a488035 4001 ),
9d72cede
EM
4002 'country_id' => array(
4003 'title' => ts('Country'),
6a488035 4004 ),
9d72cede
EM
4005 'county_id' => array(
4006 'title' => ts('County'),
6a488035
TO
4007 ),
4008 );
4009 }
4010 return $addressFields;
4011 }
4012
74cf4551 4013 /**
fe482240 4014 * Do AlterDisplay processing on Address Fields.
688d37c6 4015 *
74cf4551
EM
4016 * @param $row
4017 * @param $rows
4018 * @param $rowNum
4019 * @param $baseUrl
4020 * @param $urltxt
4021 *
4022 * @return bool
4023 */
00be9182 4024 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
6a488035
TO
4025 $criteriaQueryParams = CRM_Report_Utils_Report::getPreviewCriteriaQueryParams($this->_defaults, $this->_params);
4026 $entryFound = FALSE;
4027 // handle country
4028 if (array_key_exists('civicrm_address_country_id', $row)) {
4029 if ($value = $row['civicrm_address_country_id']) {
4030 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
4031 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
9d72cede
EM
4032 "reset=1&force=1&{$criteriaQueryParams}&" .
4033 "country_id_op=in&country_id_value={$value}",
4034 $this->_absoluteUrl, $this->_id
6a488035
TO
4035 );
4036 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4037 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
9d72cede 4038 array(1 => $urltxt)
6a488035
TO
4039 );
4040 }
4041
4042 $entryFound = TRUE;
4043 }
4044 if (array_key_exists('civicrm_address_county_id', $row)) {
4045 if ($value = $row['civicrm_address_county_id']) {
4046 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant::county($value, FALSE);
4047 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
9d72cede
EM
4048 "reset=1&force=1&{$criteriaQueryParams}&" .
4049 "county_id_op=in&county_id_value={$value}",
4050 $this->_absoluteUrl, $this->_id
6a488035
TO
4051 );
4052 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4053 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
9d72cede 4054 array(1 => $urltxt)
6a488035
TO
4055 );
4056 }
4057 $entryFound = TRUE;
4058 }
4059 // handle state province
4060 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4061 if ($value = $row['civicrm_address_state_province_id']) {
4062 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
4063
4064 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
9d72cede
EM
4065 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4066 $this->_absoluteUrl, $this->_id
6a488035
TO
4067 );
4068 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4069 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
9d72cede 4070 array(1 => $urltxt)
6a488035
TO
4071 );
4072 }
4073 $entryFound = TRUE;
4074 }
4075
4076 return $entryFound;
4077 }
4078
74cf4551 4079 /**
688d37c6
CW
4080 * Adjusts dates passed in to YEAR() for fiscal year.
4081 *
100fef9d 4082 * @param string $fieldName
74cf4551
EM
4083 *
4084 * @return string
4085 */
00be9182 4086 public function fiscalYearOffset($fieldName) {
6a488035
TO
4087 $config = CRM_Core_Config::singleton();
4088 $fy = $config->fiscalYearStart;
9d72cede
EM
4089 if (CRM_Utils_Array::value('yid_op', $this->_params) == 'calendar' ||
4090 ($fy['d'] == 1 && $fy['M'] == 1)
4091 ) {
6a488035
TO
4092 return "YEAR( $fieldName )";
4093 }
9d72cede
EM
4094 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4095 ($fy['d'] > 1 ? (" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
6a488035
TO
4096 }
4097
688d37c6 4098 /**
fe482240 4099 * Add Address into From Table if required.
6a488035 4100 */
00be9182 4101 public function addAddressFromClause() {
6a488035
TO
4102 // include address field if address column is to be included
4103 if ((isset($this->_addressField) &&
4104 $this->_addressField
4105 ) ||
4106 $this->isTableSelected('civicrm_address')
4107 ) {
4108 $this->_from .= "
4109 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4110 ON ({$this->_aliases['civicrm_contact']}.id =
4111 {$this->_aliases['civicrm_address']}.contact_id) AND
4112 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4113 }
4114 }
4115
850e4640 4116 /**
fe482240 4117 * Add Phone into From Table if required.
850e4640 4118 */
00be9182 4119 public function addPhoneFromClause() {
850e4640
E
4120 // include address field if address column is to be included
4121 if ($this->isTableSelected('civicrm_phone')
4122 ) {
4123 $this->_from .= "
4124 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4125 ON ({$this->_aliases['civicrm_contact']}.id =
4126 {$this->_aliases['civicrm_phone']}.contact_id) AND
4127 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4128 }
4129 }
4130
4131 /**
fe482240 4132 * Get phone columns to add to array.
9d72cede 4133 *
850e4640 4134 * @param array $options
16b10e64
CW
4135 * - prefix Prefix to add to table (in case of more than one instance of the table)
4136 * - prefix_label Label to give columns from this phone table instance
9d72cede 4137 *
a6c01b45
CW
4138 * @return array
4139 * phone columns definition
850e4640 4140 */
00be9182 4141 public function getPhoneColumns($options = array()) {
850e4640
E
4142 $defaultOptions = array(
4143 'prefix' => '',
4144 'prefix_label' => '',
4145 );
4146
9d72cede 4147 $options = array_merge($defaultOptions, $options);
850e4640
E
4148
4149 $fields = array(
4150 $options['prefix'] . 'civicrm_phone' => array(
9d72cede 4151 'dao' => 'CRM_Core_DAO_Phone',
850e4640
E
4152 'fields' => array(
4153 $options['prefix'] . 'phone' => array(
4154 'title' => ts($options['prefix_label'] . 'Phone'),
21dfd5f5 4155 'name' => 'phone',
850e4640
E
4156 ),
4157 ),
4158 ),
4159 );
4160 return $fields;
4161 }
4162
4163 /**
fe482240 4164 * Get address columns to add to array.
9d72cede 4165 *
850e4640 4166 * @param array $options
16b10e64
CW
4167 * - prefix Prefix to add to table (in case of more than one instance of the table)
4168 * - prefix_label Label to give columns from this address table instance
9d72cede 4169 *
a6c01b45
CW
4170 * @return array
4171 * address columns definition
850e4640 4172 */
00be9182 4173 public function getAddressColumns($options = array()) {
c927c151 4174 $options += array(
850e4640
E
4175 'prefix' => '',
4176 'prefix_label' => '',
4177 'group_by' => TRUE,
4178 'order_by' => TRUE,
4179 'filters' => TRUE,
c927c151 4180 'defaults' => array(),
850e4640 4181 );
850e4640
E
4182 return $this->addAddressFields(
4183 $options['group_by'],
4184 $options['order_by'],
4185 $options['filters'],
4186 $options['defaults']
4187 );
850e4640
E
4188 }
4189
74cf4551 4190 /**
100fef9d 4191 * @param int $groupID
74cf4551 4192 */
00be9182 4193 public function add2group($groupID) {
6a488035
TO
4194 if (is_numeric($groupID) && isset($this->_aliases['civicrm_contact'])) {
4195 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4196 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select);
4197
4198 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
e05e0dba 4199 $sql = str_replace('WITH ROLLUP', '', $sql);
6a488035
TO
4200 $dao = CRM_Core_DAO::executeQuery($sql);
4201
4202 $contact_ids = array();
4203 // Add resulting contacts to group
4204 while ($dao->fetch()) {
4205 if ($dao->addtogroup_contact_id) {
4206 $contact_ids[$dao->addtogroup_contact_id] = $dao->addtogroup_contact_id;
4207 }
4208 }
4209
9d72cede 4210 if (!empty($contact_ids)) {
6a488035
TO
4211 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
4212 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4213 }
4214 else {
4215 CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
4216 }
4217 }
4218 }
46065582 4219
688d37c6 4220 /**
fe482240 4221 * function used for showing charts on print screen.
688d37c6 4222 */
00be9182 4223 public static function uploadChartImage() {
46065582 4224 // upload strictly for '.png' images
d04d4eef
PJ
4225 $name = trim(basename(CRM_Utils_Request::retrieve('name', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET')));
4226 if (preg_match('/\.png$/', $name)) {
46065582
PJ
4227 //
4228 // POST data is usually string data, but we are passing a RAW .png
4229 // so PHP is a bit confused and $_POST is empty. But it has saved
4230 // the raw bits into $HTTP_RAW_POST_DATA
4231 //
4232 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4233
4234 // prepare the directory
4235 $config = CRM_Core_Config::singleton();
971d41b1
CW
4236 $defaultPath
4237 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir) .
9d72cede 4238 '/openFlashChart/';
46065582
PJ
4239 if (!file_exists($defaultPath)) {
4240 mkdir($defaultPath, 0777, TRUE);
4241 }
4242
4243 // full path to the saved image including filename
d04d4eef 4244 $destination = $defaultPath . $name;
46065582
PJ
4245
4246 //write and save
4247 $jfh = fopen($destination, 'w') or die("can't open file");
4248 fwrite($jfh, $httpRawPostData);
4249 fclose($jfh);
4250 CRM_Utils_System::civiExit();
4251 }
4252 }
2107cde9
CW
4253
4254 /**
fe482240 4255 * Apply common settings to entityRef fields.
9d72cede 4256 *
2107cde9
CW
4257 * @param array $field
4258 * @param string $table
4259 */
4260 private function setEntityRefDefaults(&$field, $table) {
4261 $field['attributes'] = $field['attributes'] ? $field['attributes'] : array();
4262 $field['attributes'] += array(
4263 'entity' => CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($table)),
4264 'multiple' => TRUE,
4265 'placeholder' => ts('- select -'),
4266 );
4267 }
96025800 4268
232624b1 4269}