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