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