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