Merge pull request #5387 from monishdeb/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 +--------------------------------------------------------------------+
06b69b18 6 | Copyright CiviCRM LLC (c) 2004-2014 |
db4cd986 7 +--------------------------------------------------------------------+
6a488035
TO
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
36241b02 25 +--------------------------------------------------------------------+
e70a7fc0 26 */
6a488035
TO
27
28/**
7d7c50f9 29 * Class CRM_Report_Form
6a488035
TO
30 */
31class CRM_Report_Form extends CRM_Core_Form {
7da04cde 32 const ROW_COUNT_LIMIT = 50;
6a488035
TO
33
34 /**
35 * Operator types - used for displaying filter elements
36 */
7da04cde 37 const
9d72cede 38 OP_INT = 1,
6a488035 39 OP_STRING = 2,
9d72cede 40 OP_DATE = 4,
6a488035 41 OP_DATETIME = 5,
9d72cede 42 OP_FLOAT = 8,
6a488035
TO
43 OP_SELECT = 64,
44 OP_MULTISELECT = 65,
45 OP_MULTISELECT_SEPARATOR = 66,
2107cde9
CW
46 OP_MONTH = 128,
47 OP_ENTITYREF = 256;
6a488035
TO
48
49 /**
50 * The id of the report instance
51 *
52 * @var integer
53 */
54 protected $_id;
55
56 /**
57 * The id of the report template
58 *
59 * @var integer;
60 */
61 protected $_templateID;
62
63 /**
64 * The report title
65 *
66 * @var string
67 */
68 protected $_title;
69 protected $_noFields = FALSE;
70
71 /**
72 * The set of all columns in the report. An associative array
537c70b8 73 * with column name as the key and attributes as the value
6a488035
TO
74 *
75 * @var array
76 */
77 protected $_columns = array();
78
79 /**
80 * The set of filters in the report
81 *
82 * @var array
83 */
84 protected $_filters = array();
85
86 /**
87 * The set of optional columns in the report
88 *
89 * @var array
90 */
91 protected $_options = array();
92
93 protected $_defaults = array();
94
688d37c6 95 /**
6a488035
TO
96 * By default most reports hide contact id.
97 * Setting this to true makes it available
98 */
99 protected $_exposeContactID = TRUE;
100
101 /**
102 * Set of statistic fields
103 *
104 * @var array
105 */
106 protected $_statFields = array();
107
108 /**
109 * Set of statistics data
110 *
111 * @var array
112 */
113 protected $_statistics = array();
114
115 /**
116 * List of fields not to be repeated during display
117 *
118 * @var array
119 */
120 protected $_noRepeats = array();
121
122 /**
123 * List of fields not to be displayed
124 *
125 * @var array
126 */
127 protected $_noDisplay = array();
128
129 /**
130 * Object type that a custom group extends
131 *
132 * @var null
133 */
134 protected $_customGroupExtends = NULL;
aa1aa08e 135 protected $_customGroupExtendsJoin = array();
6a488035
TO
136 protected $_customGroupFilters = TRUE;
137 protected $_customGroupGroupBy = FALSE;
9d72cede 138 protected $_customGroupJoin = 'LEFT JOIN';
6a488035
TO
139
140 /**
100fef9d 141 * Build tags filter
6a488035
TO
142 */
143 protected $_tagFilter = FALSE;
144
145 /**
ed795723 146 * specify entity table for tags filter
ed795723
JM
147 */
148 protected $_tagFilterTable = 'civicrm_contact';
149
6a488035 150 /**
0b62c1ab 151 * Build groups filter.
6a488035 152 *
f587aa17 153 * @var bool
6a488035
TO
154 */
155 protected $_groupFilter = FALSE;
156
157 /**
158 * Navigation fields
159 *
160 * @var array
161 */
162 public $_navigation = array();
163
164 public $_drilldownReport = array();
165
50951061 166 /**
0b62c1ab
EM
167 * Array of tabs to display on report.
168 *
169 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
170 *
171 * $this->tabs['OrderBy'] = array(
172 * 'title' => ts('Sorting'),
173 * 'tpl' => 'OrderBy',
174 * 'div_label' => 'order-by',
175 * );
50951061
EM
176 *
177 * @var array
178 */
179 protected $tabs = array();
180
6a488035
TO
181 /**
182 * An attribute for checkbox/radio form field layout
183 *
184 * @var array
185 */
186 protected $_fourColumnAttribute = array(
9d72cede
EM
187 '</td><td width="25%">',
188 '</td><td width="25%">',
189 '</td><td width="25%">',
190 '</tr><tr><td>',
6a488035
TO
191 );
192
193 protected $_force = 1;
194
195 protected $_params = NULL;
196 protected $_formValues = NULL;
197 protected $_instanceValues = NULL;
198
199 protected $_instanceForm = FALSE;
200 protected $_criteriaForm = FALSE;
201
202 protected $_instanceButtonName = NULL;
203 protected $_createNewButtonName = NULL;
204 protected $_printButtonName = NULL;
205 protected $_pdfButtonName = NULL;
206 protected $_csvButtonName = NULL;
207 protected $_groupButtonName = NULL;
208 protected $_chartButtonName = NULL;
209 protected $_csvSupported = TRUE;
210 protected $_add2groupSupported = TRUE;
211 protected $_groups = NULL;
9b0380d9 212 protected $_grandFlag = FALSE;
6a488035
TO
213 protected $_rowsFound = NULL;
214 protected $_selectAliases = array();
215 protected $_rollup = NULL;
6f900755 216
f587aa17
EM
217 /**
218 * @var array
219 */
220 protected $_aliases = array();
221
222 /**
223 * @var string
224 */
225 protected $_where;
226
227 /**
228 * @var string
229 */
230 protected $_from;
231
6f900755
E
232 /**
233 * SQL Limit clause
234 * @var string
235 */
6a488035 236 protected $_limit = NULL;
6f900755
E
237
238 /**
239 * This can be set to specify a limit to the number of rows
240 * Since it is currently envisaged as part of the api usage it is only being applied
241 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
242 * of the code (see limit() fn
243 * @var integer
244 */
245 protected $_limitValue = NULL;
246
247 /**
248 * This can be set to specify row offset
249 * See notes on _limitValue
250 * @var integer
251 */
252 protected $_offsetValue = NULL;
cdb44cba
EM
253 /**
254 * @var null
255 */
44d59d04 256 protected $_sections = NULL;
6a488035
TO
257 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
258 protected $_absoluteUrl = FALSE;
259
ae555e90
DS
260 /**
261 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
262 *
263 * @var boolean
264 */
265 protected $_storeResultSet = FALSE;
266
267 /**
268 * When _storeResultSet Flag is set use this var to store result set in form of array
269 *
270 * @var boolean
271 */
272 protected $_resultSet = array();
273
6a488035
TO
274 /**
275 * To what frequency group-by a date column
276 *
277 * @var array
278 */
279 protected $_groupByDateFreq = array(
280 'MONTH' => 'Month',
281 'YEARWEEK' => 'Week',
282 'QUARTER' => 'Quarter',
283 'YEAR' => 'Year',
284 );
285
286 /**
287 * Variables to hold the acl inner join and where clause
288 */
289 protected $_aclFrom = NULL;
290 protected $_aclWhere = NULL;
291
292 /**
293 * Array of DAO tables having columns included in SELECT or ORDER BY clause
294 *
295 * @var array
296 */
297 protected $_selectedTables;
298
c58f66e0 299 /**
537c70b8 300 * Output mode e.g 'print', 'csv', 'pdf'
c58f66e0
E
301 * @var string
302 */
f63fae91 303 protected $_outputMode;
c58f66e0 304
6a488035
TO
305 public $_having = NULL;
306 public $_select = NULL;
1f220d30 307 public $_selectClauses = array();
6a488035
TO
308 public $_columnHeaders = array();
309 public $_orderBy = NULL;
f2947aea 310 public $_orderByFields = array();
9d72cede 311 public $_orderByArray = array();
6a488035 312 public $_groupBy = NULL;
adfe2750 313 public $_whereClauses = array();
314 public $_havingClauses = array();
1c4d8c3e 315
dbb4a0f9 316 /**
100fef9d 317 * DashBoardRowCount Dashboard row count
dbb4a0f9
PN
318 * @var Integer
319 */
320 public $_dashBoardRowCount;
321
c58f66e0
E
322 /**
323 * Is this being called without a form controller (ie. the report is being render outside the normal form
324 * - e.g the api is retrieving the rows
325 * @var boolean
326 */
327 public $noController = FALSE;
328
7a961f19 329 /**
330 * Variable to hold the currency alias
331 */
332 protected $_currencyColumn = NULL;
6a488035 333
2fe3c48d
EM
334 /**
335 * @var string
336 */
337 protected $_interval;
338
339 /**
340 * @var bool
341 */
342 protected $_sendmail;
343
344 /**
345 * @var int
346 */
347 protected $_chartId;
348
9907633b
EM
349 /**
350 * @var int
351 */
44d59d04 352 public $_section;
9907633b
EM
353
354 /**
355 * @var string Report description.
356 */
15ba35a3 357 public $_description;
9907633b
EM
358
359 /**
360 * @var bool Is an address field selected.
361 * This was intended to determine if the address table should be joined in
362 * The isTableSelected function is now preferred for this purpose
363 */
364 protected $_addressField;
365
366 /**
367 * @var bool Is an email field selected.
368 * This was intended to determine if the email table should be joined in
369 * The isTableSelected function is now preferred for this purpose
370 */
371 protected $_emailField;
372
373 /**
374 * @var bool Is a phone field selected.
375 * This was intended to determine if the phone table should be joined in
376 * The isTableSelected function is now preferred for this purpose
377 */
378 protected $_phoneField;
379
380 /**
381 * @var bool Create new report instance? (or update existing) on save.
382 */
383 protected $_createNew;
384
6a488035 385 /**
7d7c50f9 386 * Class constructor.
6a488035 387 */
00be9182 388 public function __construct() {
6a488035
TO
389 parent::__construct();
390
22b67281
CW
391 $this->addClass('crm-report-form');
392
6a488035
TO
393 if ($this->_tagFilter) {
394 $this->buildTagFilter();
395 }
396 if ($this->_exposeContactID) {
397 if (array_key_exists('civicrm_contact', $this->_columns)) {
398 $this->_columns['civicrm_contact']['fields']['exposed_id'] = array(
399 'name' => 'id',
400 'title' => 'Contact ID',
401 'no_repeat' => TRUE,
402 );
403 }
404 }
405
406 if ($this->_groupFilter) {
407 $this->buildGroupFilter();
408 }
409
410 // Get all custom groups
cd43c5e3 411 $allGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id');
6a488035 412
4f8ec8be
DS
413 // Get the custom groupIds for which the user has VIEW permission
414 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
415 // and addCustomDataToColumns() will allow access to all custom groups.
416 $permCustomGroupIds = array();
417 if (!CRM_Core_Permission::check('access all custom data')) {
418 $permCustomGroupIds = CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_custom_group', $allGroups, NULL);
419 // do not allow custom data for reports if user doesn't have
420 // permission to access custom data.
421 if (!empty($this->_customGroupExtends) && empty($permCustomGroupIds)) {
422 $this->_customGroupExtends = array();
423 }
6a488035
TO
424 }
425
426 // merge custom data columns to _columns list, if any
427 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
428
429 // add / modify display columns, filters ..etc
430 CRM_Utils_Hook::alterReportVar('columns', $this->_columns, $this);
7a961f19 431
432 //assign currencyColumn variable to tpl
433 $this->assign('currencyColumn', $this->_currencyColumn);
6a488035
TO
434 }
435
0b62c1ab
EM
436 /**
437 * Shared pre-process function.
438 *
439 * If overriding preProcess function this should still be called.
440 *
441 * @throws \Exception
442 */
00be9182 443 public function preProcessCommon() {
971d41b1
CW
444 $this->_force
445 = CRM_Utils_Request::retrieve(
446 'force',
447 'Boolean',
448 CRM_Core_DAO::$_nullObject
e70a7fc0 449 );
77b97be7 450
971d41b1
CW
451 $this->_dashBoardRowCount
452 = CRM_Utils_Request::retrieve(
453 'rowCount',
454 'Integer',
455 CRM_Core_DAO::$_nullObject
e70a7fc0 456 );
6a488035
TO
457
458 $this->_section = CRM_Utils_Request::retrieve('section', 'Integer', CRM_Core_DAO::$_nullObject);
459
460 $this->assign('section', $this->_section);
461 CRM_Core_Region::instance('page-header')->add(array(
462 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
463 ));
9d72cede 464 if (!$this->noController) {
c58f66e0 465 $this->setID($this->get('instanceId'));
6a488035 466
6a488035 467 if (!$this->_id) {
c58f66e0
E
468 $this->setID(CRM_Report_Utils_Report::getInstanceID());
469 if (!$this->_id) {
9d72cede 470 $this->setID(CRM_Report_Utils_Report::getInstanceIDForPath());
c58f66e0 471 }
6a488035 472 }
6a488035 473
c58f66e0
E
474 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
475 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
476 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
477 }
6a488035
TO
478
479 if ($this->_id) {
480 $this->assign('instanceId', $this->_id);
481 $params = array('id' => $this->_id);
482 $this->_instanceValues = array();
0b25329b 483 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
6a488035
TO
484 $params,
485 $this->_instanceValues
486 );
487 if (empty($this->_instanceValues)) {
488 CRM_Core_Error::fatal("Report could not be loaded.");
489 }
7cab1323 490 $this->_title = $this->_instanceValues['title'];
6a488035
TO
491 if (!empty($this->_instanceValues['permission']) &&
492 (!(CRM_Core_Permission::check($this->_instanceValues['permission']) ||
493 CRM_Core_Permission::check('administer Reports')
494 ))
495 ) {
496 CRM_Utils_System::permissionDenied();
497 CRM_Utils_System::civiExit();
498 }
499
500 $formValues = CRM_Utils_Array::value('form_values', $this->_instanceValues);
501 if ($formValues) {
502 $this->_formValues = unserialize($formValues);
503 }
504 else {
505 $this->_formValues = NULL;
506 }
507
508 // lets always do a force if reset is found in the url.
a7488080 509 if (!empty($_REQUEST['reset'])) {
6a488035
TO
510 $this->_force = 1;
511 }
512
513 // set the mode
514 $this->assign('mode', 'instance');
515 }
c58f66e0 516 elseif (!$this->noController) {
6a488035
TO
517 list($optionValueID, $optionValue) = CRM_Report_Utils_Report::getValueIDFromUrl();
518 $instanceCount = CRM_Report_Utils_Report::getInstanceCount($optionValue);
519 if (($instanceCount > 0) && $optionValueID) {
520 $this->assign('instanceUrl',
521 CRM_Utils_System::url('civicrm/report/list',
522 "reset=1&ovid=$optionValueID"
523 )
524 );
525 }
526 if ($optionValueID) {
527 $this->_description = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
528 }
529
530 // set the mode
531 $this->assign('mode', 'template');
532 }
533
534 // lets display the Report Settings section
535 $this->_instanceForm = $this->_force || $this->_id || (!empty($_POST));
536
537 // Do not display Report Settings section if administer Reports permission is absent OR
538 // if report instance is reserved and administer reserved reports absent
539 if (!CRM_Core_Permission::check('administer Reports') ||
9d72cede
EM
540 ($this->_instanceValues['is_reserved'] &&
541 !CRM_Core_Permission::check('administer reserved reports'))
542 ) {
6a488035
TO
543 $this->_instanceForm = FALSE;
544 }
545
546 $this->assign('criteriaForm', FALSE);
547 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
9d72cede
EM
548 if (CRM_Core_Permission::check('administer Reports') ||
549 CRM_Core_Permission::check('access Report Criteria')
550 ) {
551 if (!$this->_instanceValues['is_reserved'] ||
552 CRM_Core_Permission::check('administer reserved reports')
553 ) {
6a488035
TO
554 $this->assign('criteriaForm', TRUE);
555 $this->_criteriaForm = TRUE;
556 }
557 }
558
559 $this->_instanceButtonName = $this->getButtonName('submit', 'save');
560 $this->_createNewButtonName = $this->getButtonName('submit', 'next');
561 $this->_printButtonName = $this->getButtonName('submit', 'print');
562 $this->_pdfButtonName = $this->getButtonName('submit', 'pdf');
563 $this->_csvButtonName = $this->getButtonName('submit', 'csv');
564 $this->_groupButtonName = $this->getButtonName('submit', 'group');
565 $this->_chartButtonName = $this->getButtonName('submit', 'chart');
566 }
567
0b62c1ab
EM
568 /**
569 * Add bread crumb.
570 */
00be9182 571 public function addBreadCrumb() {
971d41b1
CW
572 $breadCrumbs
573 = array(
8f1445ea
DL
574 array(
575 'title' => ts('Report Templates'),
576 'url' => CRM_Utils_System::url('civicrm/admin/report/template/list', 'reset=1'),
21dfd5f5 577 ),
8f1445ea 578 );
6a488035
TO
579
580 CRM_Utils_System::appendBreadCrumb($breadCrumbs);
581 }
582
0b62c1ab
EM
583 /**
584 * Pre process function.
585 *
586 * Called prior to build form.
587 */
00be9182 588 public function preProcess() {
8f1445ea 589 $this->preProcessCommon();
6a488035 590
6a488035 591 if (!$this->_id) {
29fc2b79 592 $this->addBreadCrumb();
6a488035
TO
593 }
594
595 foreach ($this->_columns as $tableName => $table) {
596 // set alias
597 if (!isset($table['alias'])) {
9d72cede
EM
598 $this->_columns[$tableName]['alias'] = substr($tableName, 8) .
599 '_civireport';
6a488035
TO
600 }
601 else {
602 $this->_columns[$tableName]['alias'] = $table['alias'] . '_civireport';
603 }
604
605 $this->_aliases[$tableName] = $this->_columns[$tableName]['alias'];
606
c75e90fa 607 $daoOrBaoName = NULL;
6a488035
TO
608 // higher preference to bao object
609 if (array_key_exists('bao', $table)) {
c75e90fa 610 $daoOrBaoName = $table['bao'];
9d72cede 611 $expFields = $daoOrBaoName::exportableFields();
6a488035 612 }
9d72cede 613 elseif (array_key_exists('dao', $table)) {
c75e90fa 614 $daoOrBaoName = $table['dao'];
9d72cede 615 $expFields = $daoOrBaoName::export();
6a488035 616 }
9d72cede 617 else {
8edb9849 618 $expFields = array();
619 }
6a488035
TO
620
621 $doNotCopy = array('required');
622
623 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
624 foreach ($fieldGroups as $fieldGrp) {
a7488080 625 if (!empty($table[$fieldGrp]) && is_array($table[$fieldGrp])) {
6a488035
TO
626 foreach ($table[$fieldGrp] as $fieldName => $field) {
627 // $name is the field name used to reference the BAO/DAO export fields array
628 $name = isset($field['name']) ? $field['name'] : $fieldName;
629
630 // Sometimes the field name key in the BAO/DAO export fields array is
631 // different from the actual database field name.
632 // Unset $field['name'] so that actual database field name can be obtained
633 // from the BAO/DAO export fields array.
634 unset($field['name']);
635
636 if (array_key_exists($name, $expFields)) {
637 foreach ($doNotCopy as $dnc) {
638 // unset the values we don't want to be copied.
639 unset($expFields[$name][$dnc]);
640 }
641 if (empty($field)) {
642 $this->_columns[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
643 }
644 else {
645 foreach ($expFields[$name] as $property => $val) {
646 if (!array_key_exists($property, $field)) {
647 $this->_columns[$tableName][$fieldGrp][$fieldName][$property] = $val;
648 }
649 }
650 }
651 }
652
653 // fill other vars
a7488080 654 if (!empty($field['no_repeat'])) {
6a488035
TO
655 $this->_noRepeats[] = "{$tableName}_{$fieldName}";
656 }
a7488080 657 if (!empty($field['no_display'])) {
6a488035
TO
658 $this->_noDisplay[] = "{$tableName}_{$fieldName}";
659 }
660
661 // set alias = table-name, unless already set
971d41b1
CW
662 $alias = isset($field['alias']) ? $field['alias'] : (
663 isset($this->_columns[$tableName]['alias']) ? $this->_columns[$tableName]['alias'] : $tableName
6a488035
TO
664 );
665 $this->_columns[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
666
667 // set name = fieldName, unless already set
668 if (!isset($this->_columns[$tableName][$fieldGrp][$fieldName]['name'])) {
669 $this->_columns[$tableName][$fieldGrp][$fieldName]['name'] = $name;
670 }
671
672 // set dbAlias = alias.name, unless already set
673 if (!isset($this->_columns[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
971d41b1
CW
674 $this->_columns[$tableName][$fieldGrp][$fieldName]['dbAlias']
675 = $alias . '.' .
9d72cede 676 $this->_columns[$tableName][$fieldGrp][$fieldName]['name'];
6a488035
TO
677 }
678
c75e90fa 679 // a few auto fills for filters
c93f6d83 680 if ($fieldGrp == 'filters') {
c75e90fa
DS
681 // fill operator types
682 if (!array_key_exists('operatorType', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
683 switch (CRM_Utils_Array::value('type', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
684 case CRM_Utils_Type::T_MONEY:
685 case CRM_Utils_Type::T_FLOAT:
686 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
687 break;
ea100cb5 688
c75e90fa
DS
689 case CRM_Utils_Type::T_INT:
690 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_INT;
691 break;
ea100cb5 692
c75e90fa 693 case CRM_Utils_Type::T_DATE:
c93f6d83 694 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE;
c75e90fa 695 break;
ea100cb5 696
c75e90fa
DS
697 case CRM_Utils_Type::T_BOOLEAN:
698 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT;
699 if (!array_key_exists('options', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
971d41b1
CW
700 $this->_columns[$tableName][$fieldGrp][$fieldName]['options']
701 = array(
9d72cede
EM
702 '' => ts('Any'),
703 '0' => ts('No'),
21dfd5f5 704 '1' => ts('Yes'),
9d72cede 705 );
c75e90fa
DS
706 }
707 break;
ea100cb5 708
c75e90fa 709 default:
c93f6d83 710 if ($daoOrBaoName &&
9d72cede
EM
711 array_key_exists('pseudoconstant', $this->_columns[$tableName][$fieldGrp][$fieldName])
712 ) {
c75e90fa
DS
713 // with multiple options operator-type is generally multi-select
714 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
715 if (!array_key_exists('options', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
716 // fill options
717 $this->_columns[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant::get($daoOrBaoName, $fieldName);
718 }
719 }
720 break;
721 }
6a488035
TO
722 }
723 }
724 }
725 }
726 }
727
728 // copy filters to a separate handy variable
729 if (array_key_exists('filters', $table)) {
730 $this->_filters[$tableName] = $this->_columns[$tableName]['filters'];
731 }
732
733 if (array_key_exists('group_bys', $table)) {
734 $groupBys[$tableName] = $this->_columns[$tableName]['group_bys'];
735 }
736
737 if (array_key_exists('fields', $table)) {
738 $reportFields[$tableName] = $this->_columns[$tableName]['fields'];
739 }
740 }
741
742 if ($this->_force) {
743 $this->setDefaultValues(FALSE);
744 }
745
8f1445ea
DL
746 CRM_Report_Utils_Get::processFilter($this->_filters, $this->_defaults);
747 CRM_Report_Utils_Get::processGroupBy($groupBys, $this->_defaults);
748 CRM_Report_Utils_Get::processFields($reportFields, $this->_defaults);
6a488035
TO
749 CRM_Report_Utils_Get::processChart($this->_defaults);
750
751 if ($this->_force) {
752 $this->_formValues = $this->_defaults;
753 $this->postProcess();
754 }
755 }
756
74cf4551 757 /**
7d7c50f9
EM
758 * Set default values.
759 *
74cf4551
EM
760 * @param bool $freeze
761 *
762 * @return array
763 */
00be9182 764 public function setDefaultValues($freeze = TRUE) {
6a488035
TO
765 $freezeGroup = array();
766
767 // FIXME: generalizing form field naming conventions would reduce
7d7c50f9 768 // Lots of lines below.
6a488035
TO
769 foreach ($this->_columns as $tableName => $table) {
770 if (array_key_exists('fields', $table)) {
771 foreach ($table['fields'] as $fieldName => $field) {
a7488080 772 if (empty($field['no_display'])) {
6a488035
TO
773 if (isset($field['required'])) {
774 // set default
775 $this->_defaults['fields'][$fieldName] = 1;
776
777 if ($freeze) {
778 // find element object, so that we could use quickform's freeze method
779 // for required elements
8f1445ea 780 $obj = $this->getElementFromGroup("fields", $fieldName);
6a488035
TO
781 if ($obj) {
782 $freezeGroup[] = $obj;
783 }
784 }
785 }
786 elseif (isset($field['default'])) {
787 $this->_defaults['fields'][$fieldName] = $field['default'];
788 }
789 }
790 }
791 }
792
793 if (array_key_exists('group_bys', $table)) {
794 foreach ($table['group_bys'] as $fieldName => $field) {
795 if (isset($field['default'])) {
a7488080 796 if (!empty($field['frequency'])) {
6a488035
TO
797 $this->_defaults['group_bys_freq'][$fieldName] = 'MONTH';
798 }
799 $this->_defaults['group_bys'][$fieldName] = $field['default'];
800 }
801 }
802 }
803 if (array_key_exists('filters', $table)) {
804 foreach ($table['filters'] as $fieldName => $field) {
805 if (isset($field['default'])) {
9d72cede
EM
806 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE
807 ) {
808 if (is_array($field['default'])) {
b0e34e7c 809 $this->_defaults["{$fieldName}_from"] = CRM_Utils_Array::value('from', $field['default']);
810 $this->_defaults["{$fieldName}_to"] = CRM_Utils_Array::value('to', $field['default']);
811 $this->_defaults["{$fieldName}_relative"] = 0;
812 }
9d72cede 813 else {
b0e34e7c 814 $this->_defaults["{$fieldName}_relative"] = $field['default'];
815 }
6a488035
TO
816 }
817 else {
818 $this->_defaults["{$fieldName}_value"] = $field['default'];
819 }
820 }
821 //assign default value as "in" for multiselect
822 //operator, To freeze the select element
9d72cede
EM
823 if (CRM_Utils_Array::value('operatorType', $field) ==
824 CRM_Report_Form::OP_MULTISELECT
825 ) {
6a488035
TO
826 $this->_defaults["{$fieldName}_op"] = 'in';
827 }
9d72cede
EM
828 if (CRM_Utils_Array::value('operatorType', $field) ==
829 CRM_Report_Form::OP_ENTITYREF
830 ) {
2107cde9
CW
831 $this->_defaults["{$fieldName}_op"] = 'in';
832 }
9d72cede
EM
833 elseif (CRM_Utils_Array::value('operatorType', $field) ==
834 CRM_Report_Form::OP_MULTISELECT_SEPARATOR
835 ) {
6a488035
TO
836 $this->_defaults["{$fieldName}_op"] = 'mhas';
837 }
838 elseif ($op = CRM_Utils_Array::value('default_op', $field)) {
839 $this->_defaults["{$fieldName}_op"] = $op;
840 }
841 }
842 }
843
8f1445ea 844 if (
e76ce93e 845 empty($this->_formValues['order_bys']) &&
846 (array_key_exists('order_bys', $table) &&
847 is_array($table['order_bys']))
6a488035 848 ) {
6a488035 849 if (!array_key_exists('order_bys', $this->_defaults)) {
6a488035
TO
850 $this->_defaults['order_bys'] = array();
851 }
852 foreach ($table['order_bys'] as $fieldName => $field) {
8cc574cf 853 if (!empty($field['default']) || !empty($field['default_order']) ||
9d72cede
EM
854 CRM_Utils_Array::value('default_is_section', $field) ||
855 !empty($field['default_weight'])
856 ) {
6a488035
TO
857 $order_by = array(
858 'column' => $fieldName,
859 'order' => CRM_Utils_Array::value('default_order', $field, 'ASC'),
860 'section' => CRM_Utils_Array::value('default_is_section', $field, 0),
861 );
862
a7488080 863 if (!empty($field['default_weight'])) {
6a488035
TO
864 $this->_defaults['order_bys'][(int) $field['default_weight']] = $order_by;
865 }
866 else {
867 array_unshift($this->_defaults['order_bys'], $order_by);
868 }
869 }
870 }
871 }
872
873 foreach ($this->_options as $fieldName => $field) {
874 if (isset($field['default'])) {
875 $this->_defaults['options'][$fieldName] = $field['default'];
876 }
877 }
878 }
879
880 if (!empty($this->_submitValues)) {
881 $this->preProcessOrderBy($this->_submitValues);
882 }
883 else {
884 $this->preProcessOrderBy($this->_defaults);
885 }
886
887 // lets finish freezing task here itself
888 if (!empty($freezeGroup)) {
889 foreach ($freezeGroup as $elem) {
890 $elem->freeze();
891 }
892 }
893
894 if ($this->_formValues) {
895 $this->_defaults = array_merge($this->_defaults, $this->_formValues);
896 }
897
898 if ($this->_instanceValues) {
899 $this->_defaults = array_merge($this->_defaults, $this->_instanceValues);
900 }
901
902 CRM_Report_Form_Instance::setDefaultValues($this, $this->_defaults);
903
904 return $this->_defaults;
905 }
906
74cf4551 907 /**
7d7c50f9
EM
908 * Get element from group.
909 *
8a925f33 910 * @param string $group
100fef9d 911 * @param string $grpFieldName
74cf4551
EM
912 *
913 * @return bool
914 */
00be9182 915 public function getElementFromGroup($group, $grpFieldName) {
6a488035
TO
916 $eleObj = $this->getElement($group);
917 foreach ($eleObj->_elements as $index => $obj) {
918 if ($grpFieldName == $obj->_attributes['name']) {
919 return $obj;
920 }
921 }
922 return FALSE;
923 }
924
c58f66e0 925 /**
7d7c50f9 926 * Setter for $_params.
9d72cede 927 *
c58f66e0
E
928 * @param array $params
929 */
00be9182 930 public function setParams($params) {
c58f66e0
E
931 $this->_params = $params;
932 }
933
934 /**
0b62c1ab 935 * Setter for $_id.
2a6da8d7 936 *
537c70b8 937 * @param int $instanceID
c58f66e0 938 */
537c70b8
EM
939 public function setID($instanceID) {
940 $this->_id = $instanceID;
c58f66e0
E
941 }
942
943 /**
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 /**
1847 * @todo - could not find any instances where this is called
1848 *
537c70b8 1849 * @param bool $relative
7e06c9f5 1850 * @param string $from
7d7c50f9 1851 * @param string $to
9d72cede
EM
1852 *
1853 * @return string|NULL
1854 */
00be9182 1855 public function dateDisplay($relative, $from, $to) {
29fc2b79 1856 list($from, $to) = $this->getFromTo($relative, $from, $to);
6a488035
TO
1857
1858 if ($from) {
1859 $clauses[] = CRM_Utils_Date::customFormat($from, NULL, array('m', 'M'));
1860 }
1861 else {
1862 $clauses[] = 'Past';
1863 }
1864
1865 if ($to) {
1866 $clauses[] = CRM_Utils_Date::customFormat($to, NULL, array('m', 'M'));
1867 }
1868 else {
1869 $clauses[] = 'Today';
1870 }
1871
1872 if (!empty($clauses)) {
1873 return implode(' - ', $clauses);
1874 }
1875
1876 return NULL;
1877 }
1878
74cf4551 1879 /**
f587aa17
EM
1880 * @param bool $relative
1881 * @param string $from
1882 * @param string $to
9907633b
EM
1883 * @param string $fromTime
1884 * @param string $toTime
74cf4551
EM
1885 *
1886 * @return array
1887 */
9907633b
EM
1888 public function getFromTo($relative, $from, $to, $fromTime = NULL, $toTime = NULL) {
1889 if (empty($toTime)) {
1890 $toTime = '235959';
6a488035
TO
1891 }
1892 //FIX ME not working for relative
1893 if ($relative) {
1894 list($term, $unit) = CRM_Utils_System::explode('.', $relative, 2);
1895 $dateRange = CRM_Utils_Date::relativeToAbsolute($term, $unit);
1896 $from = substr($dateRange['from'], 0, 8);
1897 //Take only Date Part, Sometime Time part is also present in 'to'
1898 $to = substr($dateRange['to'], 0, 8);
1899 }
9907633b
EM
1900 $from = CRM_Utils_Date::processDate($from, $fromTime);
1901 $to = CRM_Utils_Date::processDate($to, $toTime);
6a488035
TO
1902 return array($from, $to);
1903 }
1904
74cf4551 1905 /**
4b62bc4f
EM
1906 * Alter display of rows.
1907 *
1908 * Iterate through the rows retrieved via SQL and make changes for display purposes,
1909 * such as rendering contacts as links.
1910 *
1911 * @param array $rows
1912 * Rows generated by SQL, with an array for each row.
74cf4551 1913 */
00be9182 1914 public function alterDisplay(&$rows) {
6a488035
TO
1915 }
1916
74cf4551
EM
1917 /**
1918 * @param $rows
1919 */
00be9182 1920 public function alterCustomDataDisplay(&$rows) {
6a488035
TO
1921 // custom code to alter rows having custom values
1922 if (empty($this->_customGroupExtends)) {
1923 return;
1924 }
1925
1926 $customFieldIds = array();
1927 foreach ($this->_params['fields'] as $fieldAlias => $value) {
1928 if ($fieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
1929 $customFieldIds[$fieldAlias] = $fieldId;
1930 }
1931 }
1932 if (empty($customFieldIds)) {
1933 return;
1934 }
1935
1936 $customFields = $fieldValueMap = array();
9d72cede
EM
1937 $customFieldCols = array(
1938 'column_name',
1939 'data_type',
1940 'html_type',
1941 'option_group_id',
21dfd5f5 1942 'id',
9d72cede 1943 );
6a488035
TO
1944
1945 // skip for type date and ContactReference since date format is already handled
1946 $query = "
1947SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1948FROM civicrm_custom_field cf
1949INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1950LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1951WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
1952 cg.is_active = 1 AND
1953 cf.is_active = 1 AND
1954 cf.is_searchable = 1 AND
1955 cf.data_type NOT IN ('ContactReference', 'Date') AND
1956 cf.id IN (" . implode(",", $customFieldIds) . ")";
1957
1958 $dao = CRM_Core_DAO::executeQuery($query);
1959 while ($dao->fetch()) {
1960 foreach ($customFieldCols as $key) {
9d72cede
EM
1961 $customFields[$dao->table_name . '_custom_' .
1962 $dao->id][$key] = $dao->$key;
6a488035
TO
1963 }
1964 if ($dao->option_group_id) {
1965 $fieldValueMap[$dao->option_group_id][$dao->value] = $dao->label;
1966 }
1967 }
1968 $dao->free();
1969
1970 $entryFound = FALSE;
1971 foreach ($rows as $rowNum => $row) {
1972 foreach ($row as $tableCol => $val) {
1973 if (array_key_exists($tableCol, $customFields)) {
1974 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1975 $entryFound = TRUE;
1976 }
1977 }
1978
1979 // skip looking further in rows, if first row itself doesn't
1980 // have the column we need
1981 if (!$entryFound) {
1982 break;
1983 }
1984 }
1985 }
1986
74cf4551
EM
1987 /**
1988 * @param $value
1989 * @param $customField
1990 * @param $fieldValueMap
1991 *
971d41b1 1992 * @return float|string|void
74cf4551 1993 */
00be9182 1994 public function formatCustomValues($value, $customField, $fieldValueMap) {
6a488035 1995 if (CRM_Utils_System::isNull($value)) {
bed98343 1996 return NULL;
6a488035
TO
1997 }
1998
1999 $htmlType = $customField['html_type'];
2000
2001 switch ($customField['data_type']) {
2002 case 'Boolean':
2003 if ($value == '1') {
2004 $retValue = ts('Yes');
2005 }
2006 else {
2007 $retValue = ts('No');
2008 }
2009 break;
2010
2011 case 'Link':
2012 $retValue = CRM_Utils_System::formatWikiURL($value);
2013 break;
2014
2015 case 'File':
2016 $retValue = $value;
2017 break;
2018
2019 case 'Memo':
2020 $retValue = $value;
2021 break;
2022
2023 case 'Float':
2024 if ($htmlType == 'Text') {
9d72cede 2025 $retValue = (float) $value;
6a488035
TO
2026 break;
2027 }
2028 case 'Money':
2029 if ($htmlType == 'Text') {
6a488035
TO
2030 $retValue = CRM_Utils_Money::format($value, NULL, '%a');
2031 break;
2032 }
2033 case 'String':
2034 case 'Int':
2035 if (in_array($htmlType, array(
9d72cede 2036 'Text',
21dfd5f5 2037 'TextArea',
9d72cede 2038 ))) {
6a488035
TO
2039 $retValue = $value;
2040 break;
2041 }
2042 case 'StateProvince':
2043 case 'Country':
2044
2045 switch ($htmlType) {
2046 case 'Multi-Select Country':
2047 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2048 $customData = array();
2049 foreach ($value as $val) {
2050 if ($val) {
2051 $customData[] = CRM_Core_PseudoConstant::country($val, FALSE);
2052 }
2053 }
2054 $retValue = implode(', ', $customData);
2055 break;
2056
2057 case 'Select Country':
2058 $retValue = CRM_Core_PseudoConstant::country($value, FALSE);
2059 break;
2060
2061 case 'Select State/Province':
2062 $retValue = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
2063 break;
2064
2065 case 'Multi-Select State/Province':
2066 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2067 $customData = array();
2068 foreach ($value as $val) {
2069 if ($val) {
2070 $customData[] = CRM_Core_PseudoConstant::stateProvince($val, FALSE);
2071 }
2072 }
2073 $retValue = implode(', ', $customData);
2074 break;
2075
2076 case 'Select':
2077 case 'Radio':
2078 case 'Autocomplete-Select':
2079 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
2080 break;
2081
2082 case 'CheckBox':
2083 case 'AdvMulti-Select':
2084 case 'Multi-Select':
2085 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
2086 $customData = array();
2087 foreach ($value as $val) {
2088 if ($val) {
2089 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
2090 }
2091 }
2092 $retValue = implode(', ', $customData);
2093 break;
2094
2095 default:
2096 $retValue = $value;
2097 }
2098 break;
2099
2100 default:
2101 $retValue = $value;
2102 }
2103
2104 return $retValue;
2105 }
2106
74cf4551
EM
2107 /**
2108 * @param $rows
2109 */
00be9182 2110 public function removeDuplicates(&$rows) {
6a488035
TO
2111 if (empty($this->_noRepeats)) {
2112 return;
2113 }
2114 $checkList = array();
2115
2116 foreach ($rows as $key => $list) {
2117 foreach ($list as $colName => $colVal) {
8f1445ea 2118 if (array_key_exists($colName, $checkList) &&
9d72cede
EM
2119 $checkList[$colName] == $colVal
2120 ) {
6a488035
TO
2121 $rows[$key][$colName] = "";
2122 }
2123 if (in_array($colName, $this->_noRepeats)) {
2124 $checkList[$colName] = $colVal;
2125 }
2126 }
2127 }
2128 }
2129
74cf4551
EM
2130 /**
2131 * @param $row
2132 * @param $fields
2133 * @param bool $subtotal
2134 */
00be9182 2135 public function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
6a488035
TO
2136 foreach ($row as $colName => $colVal) {
2137 if (in_array($colName, $fields)) {
6a488035
TO
2138 }
2139 elseif (isset($this->_columnHeaders[$colName])) {
2140 if ($subtotal) {
2141 $row[$colName] = "Subtotal";
2142 $subtotal = FALSE;
2143 }
2144 else {
2145 unset($row[$colName]);
2146 }
2147 }
2148 }
2149 }
2150
74cf4551
EM
2151 /**
2152 * @param $rows
2153 *
2154 * @return bool
2155 */
00be9182 2156 public function grandTotal(&$rows) {
6a488035
TO
2157 if (!$this->_rollup || ($this->_rollup == '') ||
2158 ($this->_limit && count($rows) >= self::ROW_COUNT_LIMIT)
2159 ) {
2160 return FALSE;
2161 }
2162 $lastRow = array_pop($rows);
2163
6a488035
TO
2164 foreach ($this->_columnHeaders as $fld => $val) {
2165 if (!in_array($fld, $this->_statFields)) {
2166 if (!$this->_grandFlag) {
2167 $lastRow[$fld] = "Grand Total";
2168 $this->_grandFlag = TRUE;
2169 }
2170 else {
2171 $lastRow[$fld] = "";
2172 }
2173 }
2174 }
2175
2176 $this->assign('grandStat', $lastRow);
2177 return TRUE;
2178 }
2179
74cf4551
EM
2180 /**
2181 * @param $rows
2182 * @param bool $pager
2183 */
00be9182 2184 public function formatDisplay(&$rows, $pager = TRUE) {
6a488035
TO
2185 // set pager based on if any limit was applied in the query.
2186 if ($pager) {
2187 $this->setPager();
2188 }
2189
2190 // allow building charts if any
2191 if (!empty($this->_params['charts']) && !empty($rows)) {
2192 $this->buildChart($rows);
2193 $this->assign('chartEnabled', TRUE);
9d72cede
EM
2194 $this->_chartId = "{$this->_params['charts']}_" .
2195 ($this->_id ? $this->_id : substr(get_class($this), 16)) . '_' .
2196 session_id();
6a488035
TO
2197 $this->assign('chartId', $this->_chartId);
2198 }
2199
2200 // unset columns not to be displayed.
2201 foreach ($this->_columnHeaders as $key => $value) {
a7488080 2202 if (!empty($value['no_display'])) {
6a488035
TO
2203 unset($this->_columnHeaders[$key]);
2204 }
2205 }
2206
2207 // unset columns not to be displayed.
2208 if (!empty($rows)) {
2209 foreach ($this->_noDisplay as $noDisplayField) {
2210 foreach ($rows as $rowNum => $row) {
2211 unset($this->_columnHeaders[$noDisplayField]);
2212 }
2213 }
2214 }
2215
2216 // build array of section totals
2217 $this->sectionTotals();
2218
2219 // process grand-total row
2220 $this->grandTotal($rows);
2221
2222 // use this method for formatting rows for display purpose.
2223 $this->alterDisplay($rows);
2224 CRM_Utils_Hook::alterReportVar('rows', $rows, $this);
2225
2226 // use this method for formatting custom rows for display purpose.
2227 $this->alterCustomDataDisplay($rows);
2228 }
2229
74cf4551
EM
2230 /**
2231 * @param $rows
2232 */
00be9182 2233 public function buildChart(&$rows) {
6a488035
TO
2234 // override this method for building charts.
2235 }
2236
2237 // select() method below has been added recently (v3.3), and many of the report templates might
2238 // still be having their own select() method. We should fix them as and when encountered and move
2239 // towards generalizing the select() method below.
971d41b1
CW
2240
2241 /**
2242 * Generate the SELECT clause and set class variable $_select
2243 */
00be9182 2244 public function select() {
1f220d30 2245 $select = $this->_selectAliases = array();
6a488035
TO
2246
2247 foreach ($this->_columns as $tableName => $table) {
2248 if (array_key_exists('fields', $table)) {
2249 foreach ($table['fields'] as $fieldName => $field) {
2250 if ($tableName == 'civicrm_address') {
2251 $this->_addressField = TRUE;
2252 }
2253 if ($tableName == 'civicrm_email') {
2254 $this->_emailField = TRUE;
2255 }
2256 if ($tableName == 'civicrm_phone') {
2257 $this->_phoneField = TRUE;
2258 }
2259
9d72cede
EM
2260 if (!empty($field['required']) ||
2261 !empty($this->_params['fields'][$fieldName])
2262 ) {
6a488035
TO
2263
2264 // 1. In many cases we want select clause to be built in slightly different way
2265 // for a particular field of a particular type.
2266 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2267 // as needed.
2268 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
2269 if ($selectClause) {
2270 $select[] = $selectClause;
2271 continue;
2272 }
2273
2274 // include statistics columns only if set
a7488080 2275 if (!empty($field['statistics'])) {
6a488035
TO
2276 foreach ($field['statistics'] as $stat => $label) {
2277 $alias = "{$tableName}_{$fieldName}_{$stat}";
2278 switch (strtolower($stat)) {
2279 case 'max':
2280 case 'sum':
2281 $select[] = "$stat({$field['dbAlias']}) as $alias";
2282 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2283 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
9e6d7767 2284 $this->_statFields[$label] = $alias;
6a488035
TO
2285 $this->_selectAliases[] = $alias;
2286 break;
2287
2288 case 'count':
2289 $select[] = "COUNT({$field['dbAlias']}) as $alias";
2290 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2291 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
9e6d7767 2292 $this->_statFields[$label] = $alias;
6a488035
TO
2293 $this->_selectAliases[] = $alias;
2294 break;
2295
1bfaf6a6
DS
2296 case 'count_distinct':
2297 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
2298 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2299 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
2300 $this->_statFields[$label] = $alias;
2301 $this->_selectAliases[] = $alias;
2302 break;
2303
6a488035
TO
2304 case 'avg':
2305 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
2306 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
2307 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
9e6d7767 2308 $this->_statFields[$label] = $alias;
6a488035
TO
2309 $this->_selectAliases[] = $alias;
2310 break;
2311 }
2312 }
2313 }
2314 else {
2315 $alias = "{$tableName}_{$fieldName}";
2316 $select[] = "{$field['dbAlias']} as $alias";
2317 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
2318 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
2319 $this->_selectAliases[] = $alias;
2320 }
2321 }
2322 }
2323 }
2324
2325 // select for group bys
2326 if (array_key_exists('group_bys', $table)) {
2327 foreach ($table['group_bys'] as $fieldName => $field) {
2328
2329 if ($tableName == 'civicrm_address') {
2330 $this->_addressField = TRUE;
2331 }
2332 if ($tableName == 'civicrm_email') {
2333 $this->_emailField = TRUE;
2334 }
2335 if ($tableName == 'civicrm_phone') {
2336 $this->_phoneField = TRUE;
2337 }
2338 // 1. In many cases we want select clause to be built in slightly different way
2339 // for a particular field of a particular type.
2340 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2341 // as needed.
2342 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2343 if ($selectClause) {
2344 $select[] = $selectClause;
2345 continue;
2346 }
2347
9d72cede
EM
2348 if (!empty($this->_params['group_bys']) &&
2349 !empty($this->_params['group_bys'][$fieldName]) &&
2350 !empty($this->_params['group_bys_freq'])
2351 ) {
6a488035
TO
2352 switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
2353 case 'YEARWEEK':
9d72cede
EM
2354 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2355 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2356 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
6a488035
TO
2357 $field['title'] = 'Week';
2358 break;
2359
2360 case 'YEAR':
9d72cede
EM
2361 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2362 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2363 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
6a488035
TO
2364 $field['title'] = 'Year';
2365 break;
2366
2367 case 'MONTH':
9d72cede
EM
2368 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2369 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2370 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
6a488035
TO
2371 $field['title'] = 'Month';
2372 break;
2373
2374 case 'QUARTER':
9d72cede
EM
2375 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2376 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2377 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
6a488035
TO
2378 $field['title'] = 'Quarter';
2379 break;
2380 }
2381 // for graphs and charts -
a7488080 2382 if (!empty($this->_params['group_bys_freq'][$fieldName])) {
6a488035 2383 $this->_interval = $field['title'];
971d41b1
CW
2384 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title']
2385 = $field['title'] . ' Beginning';
6a488035
TO
2386 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2387 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
2388
7d7c50f9 2389 // just to make sure these values are transferred to rows.
6a488035
TO
2390 // since we 'll need them for calculation purpose,
2391 // e.g making subtotals look nicer or graphs
2392 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2393 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2394 }
2395 }
2396 }
2397 }
2398 }
2399
1f220d30 2400 $this->_selectClauses = $select;
6a488035
TO
2401 $this->_select = "SELECT " . implode(', ', $select) . " ";
2402 }
2403
74cf4551 2404 /**
100fef9d 2405 * @param string $tableName
74cf4551 2406 * @param $tableKey
100fef9d 2407 * @param string $fieldName
74cf4551
EM
2408 * @param $field
2409 *
2410 * @return bool
2411 */
00be9182 2412 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
6a488035
TO
2413 return FALSE;
2414 }
2415
00be9182 2416 public function where() {
adfe2750 2417 $this->storeWhereHavingClauseArray();
2418
2419 if (empty($this->_whereClauses)) {
2420 $this->_where = "WHERE ( 1 ) ";
2421 $this->_having = "";
2422 }
2423 else {
2424 $this->_where = "WHERE " . implode(' AND ', $this->_whereClauses);
2425 }
2426
2427 if ($this->_aclWhere) {
2428 $this->_where .= " AND {$this->_aclWhere} ";
2429 }
2430
2431 if (!empty($this->_havingClauses)) {
2432 // use this clause to construct group by clause.
2433 $this->_having = "HAVING " . implode(' AND ', $this->_havingClauses);
2434 }
2435 }
2436
2437 /**
2438 * Store Where clauses into an array - breaking out this step makes
2439 * over-riding more flexible as the clauses can be used in constructing a
2440 * temp table that may not be part of the final where clause or added
2441 * in other functions
2442 */
00be9182 2443 public function storeWhereHavingClauseArray() {
6a488035
TO
2444 foreach ($this->_columns as $tableName => $table) {
2445 if (array_key_exists('filters', $table)) {
2446 foreach ($table['filters'] as $fieldName => $field) {
d12de91c 2447 // respect pseudofield to filter spec so fields can be marked as
2448 // not to be handled here
9d72cede 2449 if (!empty($field['pseudofield'])) {
d12de91c 2450 continue;
2451 }
6a488035
TO
2452 $clause = NULL;
2453 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
9d72cede
EM
2454 if (CRM_Utils_Array::value('operatorType', $field) ==
2455 CRM_Report_Form::OP_MONTH
2456 ) {
6a488035
TO
2457 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2458 $value = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
2459 if (is_array($value) && !empty($value)) {
971d41b1
CW
2460 $clause
2461 = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) .
9d72cede 2462 '))';
6a488035
TO
2463 }
2464 }
2465 else {
2466 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
9d72cede
EM
2467 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
2468 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
6a488035 2469 $fromTime = CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params);
9d72cede
EM
2470 $toTime = CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params);
2471 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
6a488035
TO
2472 }
2473 }
2474 else {
2475 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2476 if ($op) {
2477 $clause = $this->whereClause($field,
adfe2750 2478 $op,
2479 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
2480 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
2481 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
6a488035
TO
2482 );
2483 }
2484 }
2485
2486 if (!empty($clause)) {
a7488080 2487 if (!empty($field['having'])) {
adfe2750 2488 $this->_havingClauses[] = $clause;
6a488035
TO
2489 }
2490 else {
adfe2750 2491 $this->_whereClauses[] = $clause;
6a488035
TO
2492 }
2493 }
2494 }
2495 }
2496 }
2497
6a488035 2498 }
9d72cede 2499
00be9182 2500 public function processReportMode() {
6a488035
TO
2501 $buttonName = $this->controller->getButtonName();
2502
884605ca
DL
2503 $output = CRM_Utils_Request::retrieve(
2504 'output',
2505 'String',
2506 CRM_Core_DAO::$_nullObject
6a488035
TO
2507 );
2508
971d41b1
CW
2509 $this->_sendmail
2510 = CRM_Utils_Request::retrieve(
884605ca
DL
2511 'sendmail',
2512 'Boolean',
2513 CRM_Core_DAO::$_nullObject
2514 );
6a488035
TO
2515
2516 $this->_absoluteUrl = FALSE;
2517 $printOnly = FALSE;
2518 $this->assign('printOnly', FALSE);
2519
9d72cede
EM
2520 if ($this->_printButtonName == $buttonName || $output == 'print' ||
2521 ($this->_sendmail && !$output)
2522 ) {
6a488035
TO
2523 $this->assign('printOnly', TRUE);
2524 $printOnly = TRUE;
2525 $this->assign('outputMode', 'print');
2526 $this->_outputMode = 'print';
2527 if ($this->_sendmail) {
2528 $this->_absoluteUrl = TRUE;
9d72cede 2529 }
6a488035
TO
2530 }
2531 elseif ($this->_pdfButtonName == $buttonName || $output == 'pdf') {
2532 $this->assign('printOnly', TRUE);
2533 $printOnly = TRUE;
2534 $this->assign('outputMode', 'pdf');
2535 $this->_outputMode = 'pdf';
2536 $this->_absoluteUrl = TRUE;
2537 }
2538 elseif ($this->_csvButtonName == $buttonName || $output == 'csv') {
2539 $this->assign('printOnly', TRUE);
2540 $printOnly = TRUE;
2541 $this->assign('outputMode', 'csv');
2542 $this->_outputMode = 'csv';
2543 $this->_absoluteUrl = TRUE;
2544 }
2545 elseif ($this->_groupButtonName == $buttonName || $output == 'group') {
2546 $this->assign('outputMode', 'group');
2547 $this->_outputMode = 'group';
2548 }
2549 elseif ($output == 'create_report' && $this->_criteriaForm) {
2550 $this->assign('outputMode', 'create_report');
2551 $this->_outputMode = 'create_report';
2552 }
2553 else {
2554 $this->assign('outputMode', 'html');
2555 $this->_outputMode = 'html';
2556 }
2557
2558 // Get today's date to include in printed reports
2559 if ($printOnly) {
2560 $reportDate = CRM_Utils_Date::customFormat(date('Y-m-d H:i'));
2561 $this->assign('reportDate', $reportDate);
2562 }
2563 }
2564
9657ccf2
EM
2565 /**
2566 * Post Processing function for Form (postProcessCommon should be used to set other variables from input as the api accesses that function)
2567 */
00be9182 2568 public function beginPostProcess() {
c58f66e0 2569 $this->setParams($this->controller->exportValues($this->_name));
6a488035
TO
2570
2571 if (empty($this->_params) &&
2572 $this->_force
2573 ) {
c58f66e0 2574 $this->setParams($this->_formValues);
6a488035
TO
2575 }
2576
2577 // hack to fix params when submitted from dashboard, CRM-8532
2578 // fields array is missing because form building etc is skipped
2579 // in dashboard mode for report
c58f66e0 2580 //@todo - this could be done in the dashboard no we have a setter
a7488080 2581 if (empty($this->_params['fields']) && !$this->_noFields) {
c58f66e0 2582 $this->setParams($this->_formValues);
6a488035
TO
2583 }
2584
2585 $this->_formValues = $this->_params;
2586 if (CRM_Core_Permission::check('administer Reports') &&
2587 isset($this->_id) &&
9d72cede
EM
2588 ($this->_instanceButtonName ==
2589 $this->controller->getButtonName() . '_save' ||
6a488035
TO
2590 $this->_chartButtonName == $this->controller->getButtonName()
2591 )
2592 ) {
2593 $this->assign('updateReportButton', TRUE);
2594 }
2595 $this->processReportMode();
c58f66e0
E
2596 $this->beginPostProcessCommon();
2597 }
2598
2599 /**
100fef9d 2600 * BeginPostProcess function run in both report mode and non-report mode (api)
c58f66e0 2601 */
00be9182 2602 public function beginPostProcessCommon() {
c58f66e0 2603
6a488035
TO
2604 }
2605
74cf4551
EM
2606 /**
2607 * @param bool $applyLimit
2608 *
2609 * @return string
2610 */
00be9182 2611 public function buildQuery($applyLimit = TRUE) {
6a488035
TO
2612 $this->select();
2613 $this->from();
2614 $this->customDataFrom();
2615 $this->where();
2616 $this->groupBy();
2617 $this->orderBy();
2618
2619 // order_by columns not selected for display need to be included in SELECT
2620 $unselectedSectionColumns = $this->unselectedSectionColumns();
2621 foreach ($unselectedSectionColumns as $alias => $section) {
2622 $this->_select .= ", {$section['dbAlias']} as {$alias}";
2623 }
2624
8cc574cf 2625 if ($applyLimit && empty($this->_params['charts'])) {
6a488035
TO
2626 $this->limit();
2627 }
2628 CRM_Utils_Hook::alterReportVar('sql', $this, $this);
2629
2630 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2631 return $sql;
2632 }
2633
00be9182 2634 public function groupBy() {
6a488035 2635 $groupBys = array();
a7488080 2636 if (!empty($this->_params['group_bys']) &&
6a488035
TO
2637 is_array($this->_params['group_bys']) &&
2638 !empty($this->_params['group_bys'])
2639 ) {
2640 foreach ($this->_columns as $tableName => $table) {
2641 if (array_key_exists('group_bys', $table)) {
2642 foreach ($table['group_bys'] as $fieldName => $field) {
a7488080 2643 if (!empty($this->_params['group_bys'][$fieldName])) {
6a488035
TO
2644 $groupBys[] = $field['dbAlias'];
2645 }
2646 }
2647 }
2648 }
2649 }
2650
2651 if (!empty($groupBys)) {
2652 $this->_groupBy = "GROUP BY " . implode(', ', $groupBys);
2653 }
2654 }
2655
00be9182 2656 public function orderBy() {
9d72cede 2657 $this->_orderBy = "";
6a488035
TO
2658 $this->_sections = array();
2659 $this->storeOrderByArray();
9d72cede 2660 if (!empty($this->_orderByArray) && !$this->_rollup == 'WITH ROLLUP') {
6a488035
TO
2661 $this->_orderBy = "ORDER BY " . implode(', ', $this->_orderByArray);
2662 }
2663 $this->assign('sections', $this->_sections);
2664 }
f2947aea 2665
688d37c6 2666 /**
6a488035
TO
2667 * In some cases other functions want to know which fields are selected for ordering by
2668 * Separating this into a separate function allows it to be called separately from constructing
2669 * the order by clause
2670 */
00be9182 2671 public function storeOrderByArray() {
9d72cede 2672 $orderBys = array();
6a488035 2673
a7488080 2674 if (!empty($this->_params['order_bys']) &&
6a488035
TO
2675 is_array($this->_params['order_bys']) &&
2676 !empty($this->_params['order_bys'])
2677 ) {
2678
9907633b 2679 // Process order_bys in user-specified order
6a488035
TO
2680 foreach ($this->_params['order_bys'] as $orderBy) {
2681 $orderByField = array();
2682 foreach ($this->_columns as $tableName => $table) {
2683 if (array_key_exists('order_bys', $table)) {
2684 // For DAO columns defined in $this->_columns
2685 $fields = $table['order_bys'];
2686 }
2687 elseif (array_key_exists('extends', $table)) {
2688 // For custom fields referenced in $this->_customGroupExtends
1efec7ff 2689 $fields = CRM_Utils_Array::value('fields', $table, array());
6a488035 2690 }
6f993086
AH
2691 else {
2692 continue;
2693 }
6a488035
TO
2694 if (!empty($fields) && is_array($fields)) {
2695 foreach ($fields as $fieldName => $field) {
2696 if ($fieldName == $orderBy['column']) {
f2947aea 2697 $orderByField = array_merge($field, $orderBy);
6a488035
TO
2698 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2699 break 2;
2700 }
2701 }
2702 }
2703 }
2704
2705 if (!empty($orderByField)) {
f2947aea 2706 $this->_orderByFields[] = $orderByField;
6a488035
TO
2707 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2708
2709 // Record any section headers for assignment to the template
a7488080 2710 if (!empty($orderBy['section'])) {
b5801e1d 2711 $orderByField['pageBreak'] = CRM_Utils_Array::value('pageBreak', $orderBy);
6a488035
TO
2712 $this->_sections[$orderByField['tplField']] = $orderByField;
2713 }
2714 }
2715 }
2716 }
2717
2718 $this->_orderByArray = $orderBys;
2719
2720 $this->assign('sections', $this->_sections);
2721 }
2722
74cf4551
EM
2723 /**
2724 * @return array
2725 */
00be9182 2726 public function unselectedSectionColumns() {
6a488035
TO
2727 $selectColumns = array();
2728 foreach ($this->_columns as $tableName => $table) {
2729 if (array_key_exists('fields', $table)) {
2730 foreach ($table['fields'] as $fieldName => $field) {
9d72cede
EM
2731 if (!empty($field['required']) ||
2732 !empty($this->_params['fields'][$fieldName])
2733 ) {
6a488035
TO
2734
2735 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2736 }
2737 }
2738 }
2739 }
f2947aea 2740
6a488035
TO
2741 if (is_array($this->_sections)) {
2742 return array_diff_key($this->_sections, $selectColumns);
2743 }
2744 else {
2745 return array();
2746 }
2747 }
2748
74cf4551
EM
2749 /**
2750 * @param $sql
2751 * @param $rows
2752 */
00be9182 2753 public function buildRows($sql, &$rows) {
6a488035
TO
2754 $dao = CRM_Core_DAO::executeQuery($sql);
2755 if (!is_array($rows)) {
2756 $rows = array();
2757 }
2758
2759 // use this method to modify $this->_columnHeaders
2760 $this->modifyColumnHeaders();
2761
2762 $unselectedSectionColumns = $this->unselectedSectionColumns();
2763
2764 while ($dao->fetch()) {
2765 $row = array();
2766 foreach ($this->_columnHeaders as $key => $value) {
2767 if (property_exists($dao, $key)) {
2768 $row[$key] = $dao->$key;
2769 }
2770 }
2771
2772 // section headers not selected for display need to be added to row
2773 foreach ($unselectedSectionColumns as $key => $values) {
2774 if (property_exists($dao, $key)) {
2775 $row[$key] = $dao->$key;
2776 }
2777 }
2778
2779 $rows[] = $row;
2780 }
2781 }
2782
2783 /**
2784 * When "order by" fields are marked as sections, this assigns to the template
2785 * an array of total counts for each section. This data is used by the Smarty
2786 * plugin {sectionTotal}
2787 */
00be9182 2788 public function sectionTotals() {
6a488035
TO
2789
2790 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2791 if (empty($this->_selectAliases)) {
2792 return;
2793 }
2794
2795 if (!empty($this->_sections)) {
2796 // build the query with no LIMIT clause
2797 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select);
2798 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2799
2800 // pull section aliases out of $this->_sections
2801 $sectionAliases = array_keys($this->_sections);
2802
2803 $ifnulls = array();
2804 foreach (array_merge($sectionAliases, $this->_selectAliases) as $alias) {
2805 $ifnulls[] = "ifnull($alias, '') as $alias";
2806 }
2807
971d41b1
CW
2808 // Group (un-limited) report by all aliases and get counts. This might
2809 // be done more efficiently when the contents of $sql are known, ie. by
2810 // overriding this method in the report class.
6a488035 2811
9d72cede
EM
2812 $query = "select " . implode(", ", $ifnulls) .
2813 ", count(*) as ct from ($sql) as subquery group by " .
2814 implode(", ", $sectionAliases);
6a488035
TO
2815
2816 // initialize array of total counts
2817 $totals = array();
2818 $dao = CRM_Core_DAO::executeQuery($query);
2819 while ($dao->fetch()) {
2820
2821 // let $this->_alterDisplay translate any integer ids to human-readable values.
2822 $rows[0] = $dao->toArray();
2823 $this->alterDisplay($rows);
2824 $row = $rows[0];
2825
2826 // add totals for all permutations of section values
9d72cede
EM
2827 $values = array();
2828 $i = 1;
6a488035
TO
2829 $aliasCount = count($sectionAliases);
2830 foreach ($sectionAliases as $alias) {
2831 $values[] = $row[$alias];
2832 $key = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values);
2833 if ($i == $aliasCount) {
2834 // the last alias is the lowest-level section header; use count as-is
2835 $totals[$key] = $dao->ct;
2836 }
2837 else {
2838 // other aliases are higher level; roll count into their total
2839 $totals[$key] += $dao->ct;
2840 }
2841 }
2842 }
2843 $this->assign('sectionTotals', $totals);
2844 }
2845 }
2846
00be9182 2847 public function modifyColumnHeaders() {
6a488035
TO
2848 // use this method to modify $this->_columnHeaders
2849 }
2850
74cf4551
EM
2851 /**
2852 * @param $rows
2853 */
00be9182 2854 public function doTemplateAssignment(&$rows) {
6a488035
TO
2855 $this->assign_by_ref('columnHeaders', $this->_columnHeaders);
2856 $this->assign_by_ref('rows', $rows);
2857 $this->assign('statistics', $this->statistics($rows));
2858 }
2859
74cf4551 2860 /**
4f1f1f2a 2861 * override this method to build your own statistics
74cf4551
EM
2862 * @param $rows
2863 *
2864 * @return array
2865 */
00be9182 2866 public function statistics(&$rows) {
6a488035
TO
2867 $statistics = array();
2868
2869 $count = count($rows);
2870
2871 if ($this->_rollup && ($this->_rollup != '') && $this->_grandFlag) {
2872 $count++;
2873 }
2874
2875 $this->countStat($statistics, $count);
2876
2877 $this->groupByStat($statistics);
2878
2879 $this->filterStat($statistics);
2880
2881 return $statistics;
2882 }
2883
74cf4551
EM
2884 /**
2885 * @param $statistics
2886 * @param $count
2887 */
00be9182 2888 public function countStat(&$statistics, $count) {
9d72cede
EM
2889 $statistics['counts']['rowCount'] = array(
2890 'title' => ts('Row(s) Listed'),
2891 'value' => $count,
6a488035
TO
2892 );
2893
2894 if ($this->_rowsFound && ($this->_rowsFound > $count)) {
9d72cede
EM
2895 $statistics['counts']['rowsFound'] = array(
2896 'title' => ts('Total Row(s)'),
2897 'value' => $this->_rowsFound,
6a488035
TO
2898 );
2899 }
2900 }
2901
74cf4551
EM
2902 /**
2903 * @param $statistics
2904 */
00be9182 2905 public function groupByStat(&$statistics) {
a7488080 2906 if (!empty($this->_params['group_bys']) &&
6a488035
TO
2907 is_array($this->_params['group_bys']) &&
2908 !empty($this->_params['group_bys'])
2909 ) {
2910 foreach ($this->_columns as $tableName => $table) {
2911 if (array_key_exists('group_bys', $table)) {
2912 foreach ($table['group_bys'] as $fieldName => $field) {
a7488080 2913 if (!empty($this->_params['group_bys'][$fieldName])) {
6a488035
TO
2914 $combinations[] = $field['title'];
2915 }
2916 }
2917 }
2918 }
9d72cede
EM
2919 $statistics['groups'][] = array(
2920 'title' => ts('Grouping(s)'),
2921 'value' => implode(' & ', $combinations),
6a488035
TO
2922 );
2923 }
2924 }
2925
74cf4551
EM
2926 /**
2927 * @param $statistics
2928 */
00be9182 2929 public function filterStat(&$statistics) {
6a488035
TO
2930 foreach ($this->_columns as $tableName => $table) {
2931 if (array_key_exists('filters', $table)) {
2932 foreach ($table['filters'] as $fieldName => $field) {
9d72cede
EM
2933 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE &&
2934 CRM_Utils_Array::value('operatorType', $field) !=
2935 CRM_Report_Form::OP_MONTH
2936 ) {
971d41b1
CW
2937 list($from, $to)
2938 = $this->getFromTo(
8f1445ea
DL
2939 CRM_Utils_Array::value("{$fieldName}_relative", $this->_params),
2940 CRM_Utils_Array::value("{$fieldName}_from", $this->_params),
2941 CRM_Utils_Array::value("{$fieldName}_to", $this->_params),
2942 CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params),
2943 CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params)
2944 );
0d8afee2 2945 $from_time_format = !empty($this->_params["{$fieldName}_from_time"]) ? 'h' : 'd';
9d72cede 2946 $from = CRM_Utils_Date::customFormat($from, NULL, array($from_time_format));
6a488035 2947
0d8afee2 2948 $to_time_format = !empty($this->_params["{$fieldName}_to_time"]) ? 'h' : 'd';
9d72cede 2949 $to = CRM_Utils_Date::customFormat($to, NULL, array($to_time_format));
6a488035
TO
2950
2951 if ($from || $to) {
2952 $statistics['filters'][] = array(
2953 'title' => $field['title'],
10a5be27 2954 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
6a488035
TO
2955 );
2956 }
2957 elseif (in_array($rel = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params),
9d72cede
EM
2958 array_keys($this->getOperationPair(CRM_Report_Form::OP_DATE))
2959 )) {
160d32e1 2960 $pair = $this->getOperationPair(CRM_Report_Form::OP_DATE);
6a488035
TO
2961 $statistics['filters'][] = array(
2962 'title' => $field['title'],
2963 'value' => $pair[$rel],
2964 );
2965 }
2966 }
2967 else {
2968 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2969 $value = NULL;
2970 if ($op) {
1b36206c 2971 $pair = $this->getOperationPair(
8f1445ea
DL
2972 CRM_Utils_Array::value('operatorType', $field),
2973 $fieldName
6a488035
TO
2974 );
2975 $min = CRM_Utils_Array::value("{$fieldName}_min", $this->_params);
2976 $max = CRM_Utils_Array::value("{$fieldName}_max", $this->_params);
2977 $val = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
2107cde9
CW
2978 if (in_array($op, array('bw', 'nbw')) && ($min || $max)) {
2979 $value = "{$pair[$op]} $min " . ts('and') . " $max";
2980 }
d3e86119 2981 elseif ($val && CRM_Utils_Array::value('operatorType', $field) & self::OP_ENTITYREF) {
2107cde9 2982 $this->setEntityRefDefaults($field, $tableName);
9d72cede
EM
2983 $result = civicrm_api3($field['attributes']['entity'], 'getlist',
2984 array('id' => $val) +
2985 CRM_Utils_Array::value('api', $field['attributes'], array()));
2107cde9
CW
2986 $values = array();
2987 foreach ($result['values'] as $v) {
2988 $values[] = $v['label'];
2989 }
2990 $value = "{$pair[$op]} " . implode(', ', $values);
6a488035
TO
2991 }
2992 elseif ($op == 'nll' || $op == 'nnll') {
2993 $value = $pair[$op];
2994 }
2995 elseif (is_array($val) && (!empty($val))) {
f974e915 2996 $options = CRM_Utils_Array::value('options', $field, array());
6a488035
TO
2997 foreach ($val as $key => $valIds) {
2998 if (isset($options[$valIds])) {
2999 $val[$key] = $options[$valIds];
3000 }
3001 }
9d72cede
EM
3002 $pair[$op] = (count($val) == 1) ? (($op == 'notin' || $op ==
3003 'mnot') ? ts('Is Not') : ts('Is')) : CRM_Utils_Array::value($op, $pair);
3004 $val = implode(', ', $val);
3005 $value = "{$pair[$op]} " . $val;
6a488035 3006 }
9d72cede
EM
3007 elseif (!is_array($val) && (!empty($val) || $val == '0') &&
3008 isset($field['options']) &&
6a488035
TO
3009 is_array($field['options']) && !empty($field['options'])
3010 ) {
9d72cede
EM
3011 $value = CRM_Utils_Array::value($op, $pair) . " " .
3012 CRM_Utils_Array::value($val, $field['options'], $val);
6a488035
TO
3013 }
3014 elseif ($val) {
3015 $value = CRM_Utils_Array::value($op, $pair) . " " . $val;
3016 }
3017 }
3018 if ($value) {
9d72cede
EM
3019 $statistics['filters'][] = array(
3020 'title' => CRM_Utils_Array::value('title', $field),
3021 'value' => $value,
6a488035
TO
3022 );
3023 }
3024 }
3025 }
3026 }
3027 }
3028 }
3029
74cf4551 3030 /**
7d7c50f9
EM
3031 * End post processing.
3032 *
3033 * @param array|null $rows
74cf4551 3034 */
00be9182 3035 public function endPostProcess(&$rows = NULL) {
9d72cede 3036 if ($this->_storeResultSet) {
ae555e90
DS
3037 $this->_resultSet = $rows;
3038 }
3039
6a488035
TO
3040 if ($this->_outputMode == 'print' ||
3041 $this->_outputMode == 'pdf' ||
3042 $this->_sendmail
3043 ) {
3044
3045 $content = $this->compileContent();
3046 $url = CRM_Utils_System::url("civicrm/report/instance/{$this->_id}",
9d72cede 3047 "reset=1", TRUE
6a488035
TO
3048 );
3049
3050 if ($this->_sendmail) {
3051 $config = CRM_Core_Config::singleton();
3052 $attachments = array();
3053
3054 if ($this->_outputMode == 'csv') {
971d41b1
CW
3055 $content
3056 = $this->_formValues['report_header'] . '<p>' . ts('Report URL') .
9d72cede
EM
3057 ": {$url}</p>" . '<p>' .
3058 ts('The report is attached as a CSV file.') . '</p>' .
3059 $this->_formValues['report_footer'];
3060
3061 $csvFullFilename = $config->templateCompileDir .
3062 CRM_Utils_File::makeFileName('CiviReport.csv');
6a488035
TO
3063 $csvContent = CRM_Report_Utils_Report::makeCsv($this, $rows);
3064 file_put_contents($csvFullFilename, $csvContent);
3065 $attachments[] = array(
3066 'fullPath' => $csvFullFilename,
3067 'mime_type' => 'text/csv',
3068 'cleanName' => 'CiviReport.csv',
3069 );
3070 }
3071 if ($this->_outputMode == 'pdf') {
3072 // generate PDF content
9d72cede
EM
3073 $pdfFullFilename = $config->templateCompileDir .
3074 CRM_Utils_File::makeFileName('CiviReport.pdf');
6a488035
TO
3075 file_put_contents($pdfFullFilename,
3076 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf",
3077 TRUE, array('orientation' => 'landscape')
3078 )
3079 );
3080 // generate Email Content
971d41b1
CW
3081 $content
3082 = $this->_formValues['report_header'] . '<p>' . ts('Report URL') .
9d72cede
EM
3083 ": {$url}</p>" . '<p>' .
3084 ts('The report is attached as a PDF file.') . '</p>' .
3085 $this->_formValues['report_footer'];
6a488035
TO
3086
3087 $attachments[] = array(
3088 'fullPath' => $pdfFullFilename,
3089 'mime_type' => 'application/pdf',
3090 'cleanName' => 'CiviReport.pdf',
3091 );
3092 }
3093
3094 if (CRM_Report_Utils_Report::mailReport($content, $this->_id,
9d72cede
EM
3095 $this->_outputMode, $attachments
3096 )
3097 ) {
6a488035
TO
3098 CRM_Core_Session::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3099 }
3100 else {
3101 CRM_Core_Session::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3102 }
824aede6 3103 return TRUE;
6a488035
TO
3104 }
3105 elseif ($this->_outputMode == 'print') {
3106 echo $content;
3107 }
3108 else {
3109 if ($chartType = CRM_Utils_Array::value('charts', $this->_params)) {
3110 $config = CRM_Core_Config::singleton();
3111 //get chart image name
3112 $chartImg = $this->_chartId . '.png';
3113 //get image url path
971d41b1
CW
3114 $uploadUrl
3115 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL) .
9d72cede 3116 'openFlashChart/';
6a488035
TO
3117 $uploadUrl .= $chartImg;
3118 //get image doc path to overwrite
971d41b1
CW
3119 $uploadImg
3120 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir) .
9d72cede 3121 'openFlashChart/' . $chartImg;
6a488035
TO
3122 //Load the image
3123 $chart = imagecreatefrompng($uploadUrl);
2fe3c48d 3124 //convert it into formatted png
6a488035
TO
3125 header('Content-type: image/png');
3126 //overwrite with same image
3127 imagepng($chart, $uploadImg);
3128 //delete the object
3129 imagedestroy($chart);
3130 }
3131 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3132 }
3133 CRM_Utils_System::civiExit();
3134 }
3135 elseif ($this->_outputMode == 'csv') {
3136 CRM_Report_Utils_Report::export2csv($this, $rows);
3137 }
3138 elseif ($this->_outputMode == 'group') {
3139 $group = $this->_params['groups'];
3140 $this->add2group($group);
3141 }
3142 elseif ($this->_instanceButtonName == $this->controller->getButtonName()) {
3143 CRM_Report_Form_Instance::postProcess($this);
3144 }
3145 elseif ($this->_createNewButtonName == $this->controller->getButtonName() ||
9d72cede
EM
3146 $this->_outputMode == 'create_report'
3147 ) {
6a488035
TO
3148 $this->_createNew = TRUE;
3149 CRM_Report_Form_Instance::postProcess($this);
3150 }
3151 }
8f1445ea 3152
8a925f33 3153 /**
7d7c50f9
EM
3154 * Set store result set indicator to TRUE.
3155 *
8a925f33
EM
3156 * @todo explain what this does
3157 */
00be9182 3158 public function storeResultSet() {
ae555e90
DS
3159 $this->_storeResultSet = TRUE;
3160 }
3161
74cf4551 3162 /**
7d7c50f9
EM
3163 * Get result set.
3164 *
74cf4551
EM
3165 * @return bool
3166 */
00be9182 3167 public function getResultSet() {
ae555e90
DS
3168 return $this->_resultSet;
3169 }
3170
74cf4551 3171 /**
fe482240 3172 * Use the form name to create the tpl file name.
74cf4551
EM
3173 *
3174 * @return string
74cf4551 3175 */
00be9182 3176 public function getTemplateFileName() {
6a488035 3177 $defaultTpl = parent::getTemplateFileName();
9d72cede 3178 $template = CRM_Core_Smarty::singleton();
6a488035
TO
3179 if (!$template->template_exists($defaultTpl)) {
3180 $defaultTpl = 'CRM/Report/Form.tpl';
3181 }
3182 return $defaultTpl;
3183 }
3184
688d37c6 3185 /**
fe482240 3186 * Compile the report content.
688d37c6 3187 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
6a488035 3188 *
74cf4551
EM
3189 * @return string
3190 */
00be9182 3191 public function compileContent() {
8aac22c8 3192 $templateFile = $this->getHookedTemplateFileName();
9d72cede
EM
3193 return $this->_formValues['report_header'] .
3194 CRM_Core_Form::$_template->fetch($templateFile) .
3195 $this->_formValues['report_footer'];
6a488035
TO
3196 }
3197
3198
00be9182 3199 public function postProcess() {
6a488035
TO
3200 // get ready with post process params
3201 $this->beginPostProcess();
3202
3203 // build query
3204 $sql = $this->buildQuery();
3205
3206 // build array of result based on column headers. This method also allows
3207 // modifying column headers before using it to build result set i.e $rows.
3208 $rows = array();
3209 $this->buildRows($sql, $rows);
3210
3211 // format result set.
3212 $this->formatDisplay($rows);
3213
3214 // assign variables to templates
3215 $this->doTemplateAssignment($rows);
3216
3217 // do print / pdf / instance stuff if needed
3218 $this->endPostProcess($rows);
3219 }
3220
74cf4551
EM
3221 /**
3222 * @param int $rowCount
688d37c6 3223 * @return array
74cf4551 3224 */
00be9182 3225 public function limit($rowCount = self::ROW_COUNT_LIMIT) {
6a488035
TO
3226 // lets do the pager if in html mode
3227 $this->_limit = NULL;
77b97be7 3228
dbb4a0f9
PN
3229 // CRM-14115, over-ride row count if rowCount is specified in URL
3230 if ($this->_dashBoardRowCount) {
3231 $rowCount = $this->_dashBoardRowCount;
3232 }
6a488035
TO
3233 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
3234 $this->_select = str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select);
3235
3236 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
3237
8a925f33
EM
3238 // @todo all http vars should be extracted in the preProcess
3239 // - not randomly in the class
6a488035
TO
3240 if (!$pageId && !empty($_POST)) {
3241 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
8a925f33 3242 $pageId = max((int) $_POST['crmPID_B'], 1);
6a488035
TO
3243 }
3244 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
8a925f33 3245 $pageId = max((int) $_POST['crmPID'], 1);
6a488035
TO
3246 }
3247 unset($_POST['crmPID_B'], $_POST['crmPID']);
3248 }
3249
3250 $pageId = $pageId ? $pageId : 1;
3251 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
3252 $offset = ($pageId - 1) * $rowCount;
3253
bf00d1b6
DL
3254 $offset = CRM_Utils_Type::escape($offset, 'Int');
3255 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
3256
dd3a4117 3257 $this->_limit = " LIMIT $offset, $rowCount";
6a488035
TO
3258 return array($offset, $rowCount);
3259 }
9d72cede
EM
3260 if ($this->_limitValue) {
3261 if ($this->_offsetValue) {
6f900755
E
3262 $this->_limit = " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3263 }
3264 else {
3265 $this->_limit = " LIMIT " . $this->_limitValue;
3266 }
3267 }
6a488035
TO
3268 }
3269
74cf4551
EM
3270 /**
3271 * @param int $rowCount
3272 */
00be9182 3273 public function setPager($rowCount = self::ROW_COUNT_LIMIT) {
dbb4a0f9
PN
3274
3275 // CRM-14115, over-ride row count if rowCount is specified in URL
3276 if ($this->_dashBoardRowCount) {
3277 $rowCount = $this->_dashBoardRowCount;
3278 }
3279
6a488035 3280 if ($this->_limit && ($this->_limit != '')) {
9d72cede 3281 $sql = "SELECT FOUND_ROWS();";
6a488035 3282 $this->_rowsFound = CRM_Core_DAO::singleValueQuery($sql);
9d72cede 3283 $params = array(
6a488035
TO
3284 'total' => $this->_rowsFound,
3285 'rowCount' => $rowCount,
3286 'status' => ts('Records') . ' %%StatusMessage%%',
3287 'buttonBottom' => 'PagerBottomButton',
3288 'buttonTop' => 'PagerTopButton',
3289 'pageID' => $this->get(CRM_Utils_Pager::PAGE_ID),
3290 );
3291
3292 $pager = new CRM_Utils_Pager($params);
3293 $this->assign_by_ref('pager', $pager);
ecc20f0e 3294 $this->ajaxResponse['totalRows'] = $this->_rowsFound;
6a488035
TO
3295 }
3296 }
3297
74cf4551
EM
3298 /**
3299 * @param $field
3300 * @param $value
3301 * @param $op
3302 *
3303 * @return string
3304 */
00be9182 3305 public function whereGroupClause($field, $value, $op) {
6a488035
TO
3306
3307 $smartGroupQuery = "";
3308
3309 $group = new CRM_Contact_DAO_Group();
3310 $group->is_active = 1;
3311 $group->find();
3312 $smartGroups = array();
3313 while ($group->fetch()) {
9d72cede
EM
3314 if (in_array($group->id, $this->_params['gid_value']) &&
3315 $group->saved_search_id
3316 ) {
6a488035
TO
3317 $smartGroups[] = $group->id;
3318 }
3319 }
3320
3321 CRM_Contact_BAO_GroupContactCache::check($smartGroups);
3322
3323 $smartGroupQuery = '';
3324 if (!empty($smartGroups)) {
3325 $smartGroups = implode(',', $smartGroups);
3326 $smartGroupQuery = " UNION DISTINCT
3327 SELECT DISTINCT smartgroup_contact.contact_id
3328 FROM civicrm_group_contact_cache smartgroup_contact
3329 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3330 }
3331
29fc2b79 3332 $sqlOp = $this->getSQLOperator($op);
6a488035
TO
3333 if (!is_array($value)) {
3334 $value = array($value);
3335 }
3336 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3337
3338 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3339 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3340 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3341 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3342 {$smartGroupQuery} ) ";
3343 }
3344
74cf4551
EM
3345 /**
3346 * @param $field
3347 * @param $value
3348 * @param $op
3349 *
3350 * @return string
3351 */
00be9182 3352 public function whereTagClause($field, $value, $op) {
6a488035
TO
3353 // not using left join in query because if any contact
3354 // belongs to more than one tag, results duplicate
3355 // entries.
29fc2b79 3356 $sqlOp = $this->getSQLOperator($op);
6a488035
TO
3357 if (!is_array($value)) {
3358 $value = array($value);
3359 }
3360 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
ed795723
JM
3361 $entity_table = $this->_tagFilterTable;
3362 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
6a488035
TO
3363 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3364 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
ed795723 3365 WHERE entity_table = '$entity_table' AND {$clause} ) ";
6a488035
TO
3366 }
3367
f587aa17
EM
3368 /**
3369 * Generate membership organization clause.
3370 *
3371 * @param mixed $value
3372 * @param string $op SQL Operator
3373 *
3374 * @return string
3375 */
3376 public function whereMembershipOrgClause($value, $op) {
114a2c85
DG
3377 $sqlOp = $this->getSQLOperator($op);
3378 if (!is_array($value)) {
3379 $value = array($value);
3380 }
258e2add 3381
114a2c85
DG
3382 $tmp_membership_org_sql_list = implode(', ', $value);
3383 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
97709b72 3384 SELECT DISTINCT mem.contact_id
258e2add 3385 FROM civicrm_membership mem
97709b72 3386 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
258e2add 3387 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
9d72cede
EM
3388 WHERE mt.member_of_contact_id IN (" .
3389 $tmp_membership_org_sql_list . ")
97709b72
DG
3390 AND mt.is_active = '1'
3391 AND mem_status.is_current_member = '1'
3392 AND mem_status.is_active = '1' ) ";
9d72cede 3393 }
114a2c85 3394
f587aa17 3395 /**
fe482240 3396 * Generate Membership Type SQL Clause.
f587aa17
EM
3397 * @param mixed $value
3398 * @param string $op
3399 *
3400 * @return string
3401 * SQL query string
3402 */
3403 public function whereMembershipTypeClause($value, $op) {
114a2c85
DG
3404 $sqlOp = $this->getSQLOperator($op);
3405 if (!is_array($value)) {
3406 $value = array($value);
3407 }
258e2add 3408
9d72cede 3409 $tmp_membership_sql_list = implode(', ', $value);
114a2c85 3410 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
97709b72 3411 SELECT DISTINCT mem.contact_id
258e2add 3412 FROM civicrm_membership mem
3413 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3414 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
9d72cede
EM
3415 WHERE mem.membership_type_id IN (" .
3416 $tmp_membership_sql_list . ")
97709b72
DG
3417 AND mt.is_active = '1'
3418 AND mem_status.is_current_member = '1'
3419 AND mem_status.is_active = '1' ) ";
114a2c85 3420 }
258e2add 3421
74cf4551
EM
3422 /**
3423 * @param string $tableAlias
3424 */
00be9182 3425 public function buildACLClause($tableAlias = 'contact_a') {
6a488035
TO
3426 list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
3427 }
3428
74cf4551
EM
3429 /**
3430 * @param bool $addFields
3431 * @param array $permCustomGroupIds
3432 */
00be9182 3433 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
6a488035
TO
3434 if (empty($this->_customGroupExtends)) {
3435 return;
3436 }
3437 if (!is_array($this->_customGroupExtends)) {
3438 $this->_customGroupExtends = array($this->_customGroupExtends);
3439 }
3440 $customGroupWhere = '';
3441 if (!empty($permCustomGroupIds)) {
9d72cede
EM
3442 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3443 ") AND";
6a488035
TO
3444 }
3445 $sql = "
3446SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3447 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3448FROM civicrm_custom_group cg
3449INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3450WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
3451 {$customGroupWhere}
3452 cg.is_active = 1 AND
3453 cf.is_active = 1 AND
3454 cf.is_searchable = 1
3455ORDER BY cg.weight, cf.weight";
3456 $customDAO = CRM_Core_DAO::executeQuery($sql);
3457
3458 $curTable = NULL;
3459 while ($customDAO->fetch()) {
3460 if ($customDAO->table_name != $curTable) {
3461 $curTable = $customDAO->table_name;
3462 $curFields = $curFilters = array();
3463
3464 // dummy dao object
3465 $this->_columns[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3466 $this->_columns[$curTable]['extends'] = $customDAO->extends;
3467 $this->_columns[$curTable]['grouping'] = $customDAO->table_name;
3468 $this->_columns[$curTable]['group_title'] = $customDAO->title;
3469
3470 foreach (array(
9d72cede
EM
3471 'fields',
3472 'filters',
21dfd5f5 3473 'group_bys',
9d72cede 3474 ) as $colKey) {
6a488035
TO
3475 if (!array_key_exists($colKey, $this->_columns[$curTable])) {
3476 $this->_columns[$curTable][$colKey] = array();
3477 }
3478 }
3479 }
3480 $fieldName = 'custom_' . $customDAO->cf_id;
3481
3482 if ($addFields) {
3483 // this makes aliasing work in favor
3484 $curFields[$fieldName] = array(
3485 'name' => $customDAO->column_name,
3486 'title' => $customDAO->label,
3487 'dataType' => $customDAO->data_type,
3488 'htmlType' => $customDAO->html_type,
3489 );
3490 }
3491 if ($this->_customGroupFilters) {
3492 // this makes aliasing work in favor
3493 $curFilters[$fieldName] = array(
3494 'name' => $customDAO->column_name,
3495 'title' => $customDAO->label,
3496 'dataType' => $customDAO->data_type,
3497 'htmlType' => $customDAO->html_type,
3498 );
3499 }
3500
3501 switch ($customDAO->data_type) {
3502 case 'Date':
3503 // filters
3504 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE;
3505 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_DATE;
3506 // CRM-6946, show time part for datetime date fields
3507 if ($customDAO->time_format) {
3508 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_TIMESTAMP;
3509 }
3510 break;
3511
3512 case 'Boolean':
3513 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT;
9d72cede
EM
3514 $curFilters[$fieldName]['options'] = array(
3515 '' => ts('- select -'),
3516 1 => ts('Yes'),
3517 0 => ts('No'),
6a488035
TO
3518 );
3519 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
3520 break;
3521
3522 case 'Int':
3523 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_INT;
3524 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
3525 break;
3526
3527 case 'Money':
3528 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
3529 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_MONEY;
3530 break;
3531
3532 case 'Float':
3533 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
3534 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_FLOAT;
3535 break;
3536
3537 case 'String':
3538 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3539
3540 if (!empty($customDAO->option_group_id)) {
3541 if (in_array($customDAO->html_type, array(
9d72cede
EM
3542 'Multi-Select',
3543 'AdvMulti-Select',
21dfd5f5 3544 'CheckBox',
9d72cede 3545 ))) {
6a488035
TO
3546 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
3547 }
3548 else {
3549 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
3550 }
3551 if ($this->_customGroupFilters) {
3552 $curFilters[$fieldName]['options'] = array();
9d72cede 3553 $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
3554 1 => array(
3555 $customDAO->option_group_id,
21dfd5f5
TO
3556 'Integer',
3557 ),
86bd39be 3558 ));
6a488035
TO
3559 while ($ogDAO->fetch()) {
3560 $curFilters[$fieldName]['options'][$ogDAO->value] = $ogDAO->label;
3561 }
6e57f5ca 3562 CRM_Utils_Hook::customFieldOptions($customDAO->cf_id, $curFilters[$fieldName]['options'], FALSE);
6a488035
TO
3563 }
3564 }
3565 break;
3566
3567 case 'StateProvince':
3568 if (in_array($customDAO->html_type, array(
21dfd5f5 3569 'Multi-Select State/Province',
9d72cede 3570 ))) {
6a488035
TO
3571 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
3572 }
3573 else {
3574 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
3575 }
3576 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::stateProvince();
3577 break;
3578
3579 case 'Country':
3580 if (in_array($customDAO->html_type, array(
21dfd5f5 3581 'Multi-Select Country',
9d72cede 3582 ))) {
6a488035
TO
3583 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
3584 }
3585 else {
3586 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
3587 }
3588 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::country();
3589 break;
3590
3591 case 'ContactReference':
3592 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3593 $curFilters[$fieldName]['name'] = 'display_name';
3594 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3595
3596 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3597 $curFields[$fieldName]['name'] = 'display_name';
3598 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3599 break;
3600
3601 default:
3602 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3603 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3604 }
3605
3606 if (!array_key_exists('type', $curFields[$fieldName])) {
fc161185 3607 $curFields[$fieldName]['type'] = CRM_Utils_Array::value('type', $curFilters[$fieldName], array());
6a488035
TO
3608 }
3609
3610 if ($addFields) {
3611 $this->_columns[$curTable]['fields'] = array_merge($this->_columns[$curTable]['fields'], $curFields);
3612 }
3613 if ($this->_customGroupFilters) {
3614 $this->_columns[$curTable]['filters'] = array_merge($this->_columns[$curTable]['filters'], $curFilters);
3615 }
3616 if ($this->_customGroupGroupBy) {
3617 $this->_columns[$curTable]['group_bys'] = array_merge($this->_columns[$curTable]['group_bys'], $curFields);
3618 }
3619 }
3620 }
3621
00be9182 3622 public function customDataFrom() {
6a488035
TO
3623 if (empty($this->_customGroupExtends)) {
3624 return;
3625 }
3626 $mapper = CRM_Core_BAO_CustomQuery::$extendsMap;
3627
3628 foreach ($this->_columns as $table => $prop) {
9d72cede
EM
3629 if (substr($table, 0, 13) == 'civicrm_value' ||
3630 substr($table, 0, 12) == 'custom_value'
3631 ) {
6a488035
TO
3632 $extendsTable = $mapper[$prop['extends']];
3633
3634 // check field is in params
3635 if (!$this->isFieldSelected($prop)) {
3636 continue;
3637 }
4c9d78ea 3638 $baseJoin = CRM_Utils_Array::value($prop['extends'], $this->_customGroupExtendsJoin, "{$this->_aliases[$extendsTable]}.id");
6a488035 3639
9d72cede 3640 $customJoin = is_array($this->_customGroupJoin) ? $this->_customGroupJoin[$table] : $this->_customGroupJoin;
6a488035 3641 $this->_from .= "
aa1aa08e 3642{$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
6a488035
TO
3643 // handle for ContactReference
3644 if (array_key_exists('fields', $prop)) {
3645 foreach ($prop['fields'] as $fieldName => $field) {
9d72cede
EM
3646 if (CRM_Utils_Array::value('dataType', $field) ==
3647 'ContactReference'
3648 ) {
6a488035
TO
3649 $columnName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField::getKeyID($fieldName), 'column_name');
3650 $this->_from .= "
3651LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3652 }
3653 }
3654 }
3655 }
3656 }
3657 }
3658
74cf4551
EM
3659 /**
3660 * @param $prop
3661 *
3662 * @return bool
3663 */
00be9182 3664 public function isFieldSelected($prop) {
6a488035
TO
3665 if (empty($prop)) {
3666 return FALSE;
3667 }
3668
3669 if (!empty($this->_params['fields'])) {
3670 foreach (array_keys($prop['fields']) as $fieldAlias) {
3671 $customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias);
3672 if ($customFieldId) {
3673 if (array_key_exists($fieldAlias, $this->_params['fields'])) {
3674 return TRUE;
3675 }
3676
3677 //might be survey response field.
9d72cede
EM
3678 if (!empty($this->_params['fields']['survey_response']) &&
3679 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3680 ) {
6a488035
TO
3681 return TRUE;
3682 }
3683 }
3684 }
3685 }
3686
3687 if (!empty($this->_params['group_bys']) && $this->_customGroupGroupBy) {
3688 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
9d72cede
EM
3689 if (array_key_exists($fieldAlias, $this->_params['group_bys']) &&
3690 CRM_Core_BAO_CustomField::getKeyID($fieldAlias)
3691 ) {
6a488035
TO
3692 return TRUE;
3693 }
3694 }
3695 }
3696
3697 if (!empty($this->_params['order_bys'])) {
3698 foreach (array_keys($prop['fields']) as $fieldAlias) {
3699 foreach ($this->_params['order_bys'] as $orderBy) {
9d72cede
EM
3700 if ($fieldAlias == $orderBy['column'] &&
3701 CRM_Core_BAO_CustomField::getKeyID($fieldAlias)
3702 ) {
6a488035
TO
3703 return TRUE;
3704 }
3705 }
3706 }
3707 }
3708
3709 if (!empty($prop['filters']) && $this->_customGroupFilters) {
3710 foreach ($prop['filters'] as $fieldAlias => $val) {
3711 foreach (array(
9d72cede
EM
3712 'value',
3713 'min',
3714 'max',
3715 'relative',
3716 'from',
21dfd5f5 3717 'to',
9d72cede 3718 ) as $attach) {
6a488035 3719 if (isset($this->_params[$fieldAlias . '_' . $attach]) &&
dfe4b2f5 3720 (!empty($this->_params[$fieldAlias . '_' . $attach])
9d72cede
EM
3721 || ($attach != 'relative' &&
3722 $this->_params[$fieldAlias . '_' . $attach] == '0')
dfe4b2f5 3723 )
9d72cede 3724 ) {
6a488035
TO
3725 return TRUE;
3726 }
3727 }
a7488080 3728 if (!empty($this->_params[$fieldAlias . '_op']) &&
6a488035
TO
3729 in_array($this->_params[$fieldAlias . '_op'], array('nll', 'nnll'))
3730 ) {
3731 return TRUE;
3732 }
3733 }
3734 }
3735
3736 return FALSE;
3737 }
3738
3739 /**
3740 * Check for empty order_by configurations and remove them; also set
3741 * template to hide them.
537c70b8
EM
3742 *
3743 * @param array $formValues
6a488035 3744 */
00be9182 3745 public function preProcessOrderBy(&$formValues) {
6a488035 3746 // Object to show/hide form elements
ae555e90 3747 $_showHide = new CRM_Core_ShowHideBlocks('', '');
6a488035
TO
3748
3749 $_showHide->addShow('optionField_1');
3750
3751 // Cycle through order_by options; skip any empty ones, and hide them as well
3752 $n = 1;
3753
3754 if (!empty($formValues['order_bys'])) {
3755 foreach ($formValues['order_bys'] as $order_by) {
3756 if ($order_by['column'] && $order_by['column'] != '-') {
3757 $_showHide->addShow('optionField_' . $n);
3758 $orderBys[$n] = $order_by;
3759 $n++;
3760 }
3761 }
3762 }
3763 for ($i = $n; $i <= 5; $i++) {
3764 if ($i > 1) {
3765 $_showHide->addHide('optionField_' . $i);
3766 }
3767 }
3768
3769 // overwrite order_by options with modified values
3770 if (!empty($orderBys)) {
3771 $formValues['order_bys'] = $orderBys;
3772 }
3773 else {
3774 $formValues['order_bys'] = array(1 => array('column' => '-'));
3775 }
3776
3777 // assign show/hide data to template
3778 $_showHide->addToTemplate();
3779 }
3780
3781 /**
3782 * Does table name have columns in SELECT clause?
3783 *
7e06c9f5
TO
3784 * @param string $tableName
3785 * Name of table (index of $this->_columns array).
6a488035
TO
3786 *
3787 * @return bool
3788 */
00be9182 3789 public function isTableSelected($tableName) {
6a488035
TO
3790 return in_array($tableName, $this->selectedTables());
3791 }
3792
3793 /**
fe482240 3794 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
6a488035
TO
3795 * (building the array if it's unset)
3796 *
971d41b1
CW
3797 * @return array
3798 * selectedTables
6a488035 3799 */
00be9182 3800 public function selectedTables() {
6a488035
TO
3801 if (!$this->_selectedTables) {
3802 $orderByColumns = array();
9d72cede
EM
3803 if (array_key_exists('order_bys', $this->_params) &&
3804 is_array($this->_params['order_bys'])
3805 ) {
6a488035
TO
3806 foreach ($this->_params['order_bys'] as $orderBy) {
3807 $orderByColumns[] = $orderBy['column'];
3808 }
3809 }
3810
3811 foreach ($this->_columns as $tableName => $table) {
3812 if (array_key_exists('fields', $table)) {
3813 foreach ($table['fields'] as $fieldName => $field) {
9d72cede
EM
3814 if (!empty($field['required']) ||
3815 !empty($this->_params['fields'][$fieldName])
3816 ) {
6a488035
TO
3817 $this->_selectedTables[] = $tableName;
3818 break;
3819 }
3820 }
3821 }
3822 if (array_key_exists('order_bys', $table)) {
3823 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3824 if (in_array($orderByName, $orderByColumns)) {
3825 $this->_selectedTables[] = $tableName;
3826 break;
3827 }
3828 }
3829 }
3830 if (array_key_exists('filters', $table)) {
3831 foreach ($table['filters'] as $filterName => $filter) {
a7488080 3832 if (!empty($this->_params["{$filterName}_value"]) ||
9d72cede
EM
3833 CRM_Utils_Array::value("{$filterName}_op", $this->_params) ==
3834 'nll' ||
3835 CRM_Utils_Array::value("{$filterName}_op", $this->_params) ==
3836 'nnll'
6a488035
TO
3837 ) {
3838 $this->_selectedTables[] = $tableName;
3839 break;
3840 }
3841 }
3842 }
3843 }
3844 }
3845 return $this->_selectedTables;
3846 }
3847
850e4640
E
3848 /**
3849 * @deprecated - use getAddressColumns which is a more accurate description
3850 * and also accepts an array of options rather than a long list
3851 *
c490a46a 3852 * adding address fields to construct function in reports
77b97be7 3853 *
7e06c9f5
TO
3854 * @param bool $groupBy
3855 * Add GroupBy? Not appropriate for detail report.
3856 * @param bool $orderBy
3857 * Add GroupBy? Not appropriate for detail report.
77b97be7
EM
3858 * @param bool $filters
3859 * @param array $defaults
3860 *
a6c01b45
CW
3861 * @return array
3862 * address fields for construct clause
6a488035 3863 */
00be9182 3864 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
6a488035 3865 $addressFields = array(
9d72cede 3866 'civicrm_address' => array(
6a488035 3867 'dao' => 'CRM_Core_DAO_Address',
9d72cede
EM
3868 'fields' => array(
3869 'name' => array(
3870 'title' => ts('Address Name'),
6a488035
TO
3871 'default' => CRM_Utils_Array::value('name', $defaults, FALSE),
3872 ),
9d72cede
EM
3873 'street_address' => array(
3874 'title' => ts('Street Address'),
6a488035
TO
3875 'default' => CRM_Utils_Array::value('street_address', $defaults, FALSE),
3876 ),
9d72cede
EM
3877 'supplemental_address_1' => array(
3878 'title' => ts('Supplementary Address Field 1'),
6a488035
TO
3879 'default' => CRM_Utils_Array::value('supplemental_address_1', $defaults, FALSE),
3880 ),
9d72cede
EM
3881 'supplemental_address_2' => array(
3882 'title' => ts('Supplementary Address Field 2'),
6a488035
TO
3883 'default' => CRM_Utils_Array::value('supplemental_address_2', $defaults, FALSE),
3884 ),
9d72cede 3885 'street_number' => array(
6a488035
TO
3886 'name' => 'street_number',
3887 'title' => ts('Street Number'),
3888 'type' => 1,
3889 'default' => CRM_Utils_Array::value('street_number', $defaults, FALSE),
3890 ),
9d72cede 3891 'street_name' => array(
6a488035
TO
3892 'name' => 'street_name',
3893 'title' => ts('Street Name'),
3894 'type' => 1,
3895 'default' => CRM_Utils_Array::value('street_name', $defaults, FALSE),
3896 ),
9d72cede 3897 'street_unit' => array(
6a488035
TO
3898 'name' => 'street_unit',
3899 'title' => ts('Street Unit'),
3900 'type' => 1,
3901 'default' => CRM_Utils_Array::value('street_unit', $defaults, FALSE),
3902 ),
9d72cede
EM
3903 'city' => array(
3904 'title' => ts('City'),
6a488035
TO
3905 'default' => CRM_Utils_Array::value('city', $defaults, FALSE),
3906 ),
9d72cede
EM
3907 'postal_code' => array(
3908 'title' => ts('Postal Code'),
6a488035 3909 'default' => CRM_Utils_Array::value('postal_code', $defaults, FALSE),
4cbdd2b1 3910 ),
9d72cede
EM
3911 'postal_code_suffix' => array(
3912 'title' => ts('Postal Code Suffix'),
4cbdd2b1 3913 'default' => CRM_Utils_Array::value('postal_code_suffix', $defaults, FALSE),
6a488035 3914 ),
9d72cede
EM
3915 'country_id' => array(
3916 'title' => ts('Country'),
3917 'default' => CRM_Utils_Array::value('country_id', $defaults, FALSE),
3918 ),
3919 'state_province_id' => array(
3920 'title' => ts('State/Province'),
6a488035
TO
3921 'default' => CRM_Utils_Array::value('state_province_id', $defaults, FALSE),
3922 ),
9d72cede
EM
3923 'county_id' => array(
3924 'title' => ts('County'),
3925 'default' => CRM_Utils_Array::value('county_id', $defaults, FALSE),
3926 ),
6a488035
TO
3927 ),
3928 'grouping' => 'location-fields',
3929 ),
3930 );
3931
3932 if ($filters) {
3933 $addressFields['civicrm_address']['filters'] = array(
9d72cede
EM
3934 'street_number' => array(
3935 'title' => ts('Street Number'),
3936 'type' => 1,
3937 'name' => 'street_number',
6a488035 3938 ),
9d72cede
EM
3939 'street_name' => array(
3940 'title' => ts('Street Name'),
3941 'name' => 'street_name',
3942 'operator' => 'like',
6a488035 3943 ),
9d72cede
EM
3944 'postal_code' => array(
3945 'title' => ts('Postal Code'),
3946 'type' => 1,
3947 'name' => 'postal_code',
6a488035 3948 ),
9d72cede
EM
3949 'city' => array(
3950 'title' => ts('City'),
3951 'operator' => 'like',
3952 'name' => 'city',
6a488035 3953 ),
863581d1
CW
3954 'country_id' => array(
3955 'name' => 'country_id',
3956 'title' => ts('Country'),
6a488035 3957 'type' => CRM_Utils_Type::T_INT,
9d72cede 3958 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
c927c151 3959 'options' => CRM_Core_PseudoConstant::country(),
6a488035
TO
3960 ),
3961 'state_province_id' => array(
3962 'name' => 'state_province_id',
3963 'title' => ts('State/Province'),
3964 'type' => CRM_Utils_Type::T_INT,
c927c151
CW
3965 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
3966 'options' => array(),
6a488035 3967 ),
863581d1
CW
3968 'county_id' => array(
3969 'name' => 'county_id',
3970 'title' => ts('County'),
6a488035 3971 'type' => CRM_Utils_Type::T_INT,
c927c151
CW
3972 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
3973 'options' => array(),
6a488035
TO
3974 ),
3975 );
3976 }
3977
3978 if ($orderBy) {
9d72cede
EM
3979 $addressFields['civicrm_address']['order_bys'] = array(
3980 'street_name' => array('title' => ts('Street Name')),
3981 'street_number' => array('title' => 'Odd / Even Street Number'),
3982 'street_address' => NULL,
3983 'city' => NULL,
3984 'postal_code' => NULL,
6a488035
TO
3985 );
3986 }
3987
3988 if ($groupBy) {
3989 $addressFields['civicrm_address']['group_bys'] = array(
3990 'street_address' => NULL,
3991 'city' => NULL,
3992 'postal_code' => NULL,
9d72cede
EM
3993 'state_province_id' => array(
3994 'title' => ts('State/Province'),
6a488035 3995 ),
9d72cede
EM
3996 'country_id' => array(
3997 'title' => ts('Country'),
6a488035 3998 ),
9d72cede
EM
3999 'county_id' => array(
4000 'title' => ts('County'),
6a488035
TO
4001 ),
4002 );
4003 }
4004 return $addressFields;
4005 }
4006
74cf4551 4007 /**
fe482240 4008 * Do AlterDisplay processing on Address Fields.
688d37c6 4009 *
74cf4551
EM
4010 * @param $row
4011 * @param $rows
4012 * @param $rowNum
4013 * @param $baseUrl
4014 * @param $urltxt
4015 *
4016 * @return bool
4017 */
00be9182 4018 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
6a488035
TO
4019 $criteriaQueryParams = CRM_Report_Utils_Report::getPreviewCriteriaQueryParams($this->_defaults, $this->_params);
4020 $entryFound = FALSE;
4021 // handle country
4022 if (array_key_exists('civicrm_address_country_id', $row)) {
4023 if ($value = $row['civicrm_address_country_id']) {
4024 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
4025 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
9d72cede
EM
4026 "reset=1&force=1&{$criteriaQueryParams}&" .
4027 "country_id_op=in&country_id_value={$value}",
4028 $this->_absoluteUrl, $this->_id
6a488035
TO
4029 );
4030 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4031 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
9d72cede 4032 array(1 => $urltxt)
6a488035
TO
4033 );
4034 }
4035
4036 $entryFound = TRUE;
4037 }
4038 if (array_key_exists('civicrm_address_county_id', $row)) {
4039 if ($value = $row['civicrm_address_county_id']) {
4040 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant::county($value, FALSE);
4041 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
9d72cede
EM
4042 "reset=1&force=1&{$criteriaQueryParams}&" .
4043 "county_id_op=in&county_id_value={$value}",
4044 $this->_absoluteUrl, $this->_id
6a488035
TO
4045 );
4046 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4047 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
9d72cede 4048 array(1 => $urltxt)
6a488035
TO
4049 );
4050 }
4051 $entryFound = TRUE;
4052 }
4053 // handle state province
4054 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4055 if ($value = $row['civicrm_address_state_province_id']) {
4056 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
4057
4058 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
9d72cede
EM
4059 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4060 $this->_absoluteUrl, $this->_id
6a488035
TO
4061 );
4062 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4063 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
9d72cede 4064 array(1 => $urltxt)
6a488035
TO
4065 );
4066 }
4067 $entryFound = TRUE;
4068 }
4069
4070 return $entryFound;
4071 }
4072
74cf4551 4073 /**
688d37c6
CW
4074 * Adjusts dates passed in to YEAR() for fiscal year.
4075 *
100fef9d 4076 * @param string $fieldName
74cf4551
EM
4077 *
4078 * @return string
4079 */
00be9182 4080 public function fiscalYearOffset($fieldName) {
6a488035
TO
4081 $config = CRM_Core_Config::singleton();
4082 $fy = $config->fiscalYearStart;
9d72cede
EM
4083 if (CRM_Utils_Array::value('yid_op', $this->_params) == 'calendar' ||
4084 ($fy['d'] == 1 && $fy['M'] == 1)
4085 ) {
6a488035
TO
4086 return "YEAR( $fieldName )";
4087 }
9d72cede
EM
4088 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4089 ($fy['d'] > 1 ? (" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
6a488035
TO
4090 }
4091
688d37c6 4092 /**
fe482240 4093 * Add Address into From Table if required.
6a488035 4094 */
00be9182 4095 public function addAddressFromClause() {
6a488035
TO
4096 // include address field if address column is to be included
4097 if ((isset($this->_addressField) &&
4098 $this->_addressField
4099 ) ||
4100 $this->isTableSelected('civicrm_address')
4101 ) {
4102 $this->_from .= "
4103 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4104 ON ({$this->_aliases['civicrm_contact']}.id =
4105 {$this->_aliases['civicrm_address']}.contact_id) AND
4106 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4107 }
4108 }
4109
850e4640 4110 /**
fe482240 4111 * Add Phone into From Table if required.
850e4640 4112 */
00be9182 4113 public function addPhoneFromClause() {
850e4640
E
4114 // include address field if address column is to be included
4115 if ($this->isTableSelected('civicrm_phone')
4116 ) {
4117 $this->_from .= "
4118 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4119 ON ({$this->_aliases['civicrm_contact']}.id =
4120 {$this->_aliases['civicrm_phone']}.contact_id) AND
4121 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4122 }
4123 }
4124
4125 /**
fe482240 4126 * Get phone columns to add to array.
9d72cede 4127 *
850e4640 4128 * @param array $options
16b10e64
CW
4129 * - prefix Prefix to add to table (in case of more than one instance of the table)
4130 * - prefix_label Label to give columns from this phone table instance
9d72cede 4131 *
a6c01b45
CW
4132 * @return array
4133 * phone columns definition
850e4640 4134 */
00be9182 4135 public function getPhoneColumns($options = array()) {
850e4640
E
4136 $defaultOptions = array(
4137 'prefix' => '',
4138 'prefix_label' => '',
4139 );
4140
9d72cede 4141 $options = array_merge($defaultOptions, $options);
850e4640
E
4142
4143 $fields = array(
4144 $options['prefix'] . 'civicrm_phone' => array(
9d72cede 4145 'dao' => 'CRM_Core_DAO_Phone',
850e4640
E
4146 'fields' => array(
4147 $options['prefix'] . 'phone' => array(
4148 'title' => ts($options['prefix_label'] . 'Phone'),
21dfd5f5 4149 'name' => 'phone',
850e4640
E
4150 ),
4151 ),
4152 ),
4153 );
4154 return $fields;
4155 }
4156
4157 /**
fe482240 4158 * Get address columns to add to array.
9d72cede 4159 *
850e4640 4160 * @param array $options
16b10e64
CW
4161 * - prefix Prefix to add to table (in case of more than one instance of the table)
4162 * - prefix_label Label to give columns from this address table instance
9d72cede 4163 *
a6c01b45
CW
4164 * @return array
4165 * address columns definition
850e4640 4166 */
00be9182 4167 public function getAddressColumns($options = array()) {
c927c151 4168 $options += array(
850e4640
E
4169 'prefix' => '',
4170 'prefix_label' => '',
4171 'group_by' => TRUE,
4172 'order_by' => TRUE,
4173 'filters' => TRUE,
c927c151 4174 'defaults' => array(),
850e4640 4175 );
850e4640
E
4176 return $this->addAddressFields(
4177 $options['group_by'],
4178 $options['order_by'],
4179 $options['filters'],
4180 $options['defaults']
4181 );
850e4640
E
4182 }
4183
74cf4551 4184 /**
100fef9d 4185 * @param int $groupID
74cf4551 4186 */
00be9182 4187 public function add2group($groupID) {
6a488035
TO
4188 if (is_numeric($groupID) && isset($this->_aliases['civicrm_contact'])) {
4189 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4190 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select);
4191
4192 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4193 $dao = CRM_Core_DAO::executeQuery($sql);
4194
4195 $contact_ids = array();
4196 // Add resulting contacts to group
4197 while ($dao->fetch()) {
4198 if ($dao->addtogroup_contact_id) {
4199 $contact_ids[$dao->addtogroup_contact_id] = $dao->addtogroup_contact_id;
4200 }
4201 }
4202
9d72cede 4203 if (!empty($contact_ids)) {
6a488035
TO
4204 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
4205 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4206 }
4207 else {
4208 CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
4209 }
4210 }
4211 }
46065582 4212
688d37c6 4213 /**
fe482240 4214 * function used for showing charts on print screen.
688d37c6 4215 */
00be9182 4216 public static function uploadChartImage() {
46065582 4217 // upload strictly for '.png' images
d04d4eef
PJ
4218 $name = trim(basename(CRM_Utils_Request::retrieve('name', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET')));
4219 if (preg_match('/\.png$/', $name)) {
46065582
PJ
4220 //
4221 // POST data is usually string data, but we are passing a RAW .png
4222 // so PHP is a bit confused and $_POST is empty. But it has saved
4223 // the raw bits into $HTTP_RAW_POST_DATA
4224 //
4225 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
4226
4227 // prepare the directory
4228 $config = CRM_Core_Config::singleton();
971d41b1
CW
4229 $defaultPath
4230 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir) .
9d72cede 4231 '/openFlashChart/';
46065582
PJ
4232 if (!file_exists($defaultPath)) {
4233 mkdir($defaultPath, 0777, TRUE);
4234 }
4235
4236 // full path to the saved image including filename
d04d4eef 4237 $destination = $defaultPath . $name;
46065582
PJ
4238
4239 //write and save
4240 $jfh = fopen($destination, 'w') or die("can't open file");
4241 fwrite($jfh, $httpRawPostData);
4242 fclose($jfh);
4243 CRM_Utils_System::civiExit();
4244 }
4245 }
2107cde9
CW
4246
4247 /**
fe482240 4248 * Apply common settings to entityRef fields.
9d72cede 4249 *
2107cde9
CW
4250 * @param array $field
4251 * @param string $table
4252 */
4253 private function setEntityRefDefaults(&$field, $table) {
4254 $field['attributes'] = $field['attributes'] ? $field['attributes'] : array();
4255 $field['attributes'] += array(
4256 'entity' => CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($table)),
4257 'multiple' => TRUE,
4258 'placeholder' => ts('- select -'),
4259 );
4260 }
96025800 4261
232624b1 4262}