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