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