CRM-14589 - Next Payment Due broken on pledged but not paid report
[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.
1c4d8c3e 400 if (CRM_Utils_Array::value('reset', $_REQUEST)) {
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) {
501 if (CRM_Utils_Array::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
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
530 if (CRM_Utils_Array::value('no_repeat', $field)) {
531 $this->_noRepeats[] = "{$tableName}_{$fieldName}";
532 }
533 if (CRM_Utils_Array::value('no_display', $field)) {
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
DL
576 if ($daoOrBaoName &&
577 (array_key_exists('pseudoconstant', $this->_columns[$tableName][$fieldGrp][$fieldName])
c75e90fa
DS
578 || array_key_exists('enumValues', $this->_columns[$tableName][$fieldGrp][$fieldName]))
579 ) {
580 // with multiple options operator-type is generally multi-select
581 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
582 if (!array_key_exists('options', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
583 // fill options
584 $this->_columns[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant::get($daoOrBaoName, $fieldName);
585 }
586 }
587 break;
588 }
6a488035
TO
589 }
590 }
591 }
592 }
593 }
594
595 // copy filters to a separate handy variable
596 if (array_key_exists('filters', $table)) {
597 $this->_filters[$tableName] = $this->_columns[$tableName]['filters'];
598 }
599
600 if (array_key_exists('group_bys', $table)) {
601 $groupBys[$tableName] = $this->_columns[$tableName]['group_bys'];
602 }
603
604 if (array_key_exists('fields', $table)) {
605 $reportFields[$tableName] = $this->_columns[$tableName]['fields'];
606 }
607 }
608
609 if ($this->_force) {
610 $this->setDefaultValues(FALSE);
611 }
612
8f1445ea
DL
613 CRM_Report_Utils_Get::processFilter($this->_filters, $this->_defaults);
614 CRM_Report_Utils_Get::processGroupBy($groupBys, $this->_defaults);
615 CRM_Report_Utils_Get::processFields($reportFields, $this->_defaults);
6a488035
TO
616 CRM_Report_Utils_Get::processChart($this->_defaults);
617
618 if ($this->_force) {
619 $this->_formValues = $this->_defaults;
620 $this->postProcess();
621 }
622 }
623
624 function setDefaultValues($freeze = TRUE) {
625 $freezeGroup = array();
626
627 // FIXME: generalizing form field naming conventions would reduce
628 // lots of lines below.
629 foreach ($this->_columns as $tableName => $table) {
630 if (array_key_exists('fields', $table)) {
631 foreach ($table['fields'] as $fieldName => $field) {
d4997a19 632 if (!CRM_Utils_Array::value('no_display', $field)) {
6a488035
TO
633 if (isset($field['required'])) {
634 // set default
635 $this->_defaults['fields'][$fieldName] = 1;
636
637 if ($freeze) {
638 // find element object, so that we could use quickform's freeze method
639 // for required elements
8f1445ea 640 $obj = $this->getElementFromGroup("fields", $fieldName);
6a488035
TO
641 if ($obj) {
642 $freezeGroup[] = $obj;
643 }
644 }
645 }
646 elseif (isset($field['default'])) {
647 $this->_defaults['fields'][$fieldName] = $field['default'];
648 }
649 }
650 }
651 }
652
653 if (array_key_exists('group_bys', $table)) {
654 foreach ($table['group_bys'] as $fieldName => $field) {
655 if (isset($field['default'])) {
656 if (CRM_Utils_Array::value('frequency', $field)) {
657 $this->_defaults['group_bys_freq'][$fieldName] = 'MONTH';
658 }
659 $this->_defaults['group_bys'][$fieldName] = $field['default'];
660 }
661 }
662 }
663 if (array_key_exists('filters', $table)) {
664 foreach ($table['filters'] as $fieldName => $field) {
665 if (isset($field['default'])) {
666 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
b0e34e7c 667 if(is_array($field['default'])){
668 $this->_defaults["{$fieldName}_from"] = CRM_Utils_Array::value('from', $field['default']);
669 $this->_defaults["{$fieldName}_to"] = CRM_Utils_Array::value('to', $field['default']);
670 $this->_defaults["{$fieldName}_relative"] = 0;
671 }
672 else{
673 $this->_defaults["{$fieldName}_relative"] = $field['default'];
674 }
6a488035
TO
675 }
676 else {
677 $this->_defaults["{$fieldName}_value"] = $field['default'];
678 }
679 }
680 //assign default value as "in" for multiselect
681 //operator, To freeze the select element
160d32e1 682 if (CRM_Utils_Array::value('operatorType', $field) == CRM_Report_Form::OP_MULTISELECT) {
6a488035
TO
683 $this->_defaults["{$fieldName}_op"] = 'in';
684 }
160d32e1 685 elseif (CRM_Utils_Array::value('operatorType', $field) == CRM_Report_Form::OP_MULTISELECT_SEPARATOR) {
6a488035
TO
686 $this->_defaults["{$fieldName}_op"] = 'mhas';
687 }
688 elseif ($op = CRM_Utils_Array::value('default_op', $field)) {
689 $this->_defaults["{$fieldName}_op"] = $op;
690 }
691 }
692 }
693
8f1445ea
DL
694 if (
695 array_key_exists('order_bys', $table) &&
6a488035
TO
696 is_array($table['order_bys'])
697 ) {
6a488035 698 if (!array_key_exists('order_bys', $this->_defaults)) {
6a488035
TO
699 $this->_defaults['order_bys'] = array();
700 }
701 foreach ($table['order_bys'] as $fieldName => $field) {
8f1445ea
DL
702 if (
703 CRM_Utils_Array::value('default', $field) ||
6a488035
TO
704 CRM_Utils_Array::value('default_order', $field) ||
705 CRM_Utils_Array::value('default_is_section', $field) ||
706 CRM_Utils_Array::value('default_weight', $field)
707 ) {
708 $order_by = array(
709 'column' => $fieldName,
710 'order' => CRM_Utils_Array::value('default_order', $field, 'ASC'),
711 'section' => CRM_Utils_Array::value('default_is_section', $field, 0),
712 );
713
714 if (CRM_Utils_Array::value('default_weight', $field)) {
715 $this->_defaults['order_bys'][(int) $field['default_weight']] = $order_by;
716 }
717 else {
718 array_unshift($this->_defaults['order_bys'], $order_by);
719 }
720 }
721 }
722 }
723
724 foreach ($this->_options as $fieldName => $field) {
725 if (isset($field['default'])) {
726 $this->_defaults['options'][$fieldName] = $field['default'];
727 }
728 }
729 }
730
731 if (!empty($this->_submitValues)) {
732 $this->preProcessOrderBy($this->_submitValues);
733 }
734 else {
735 $this->preProcessOrderBy($this->_defaults);
736 }
737
738 // lets finish freezing task here itself
739 if (!empty($freezeGroup)) {
740 foreach ($freezeGroup as $elem) {
741 $elem->freeze();
742 }
743 }
744
745 if ($this->_formValues) {
746 $this->_defaults = array_merge($this->_defaults, $this->_formValues);
747 }
748
749 if ($this->_instanceValues) {
750 $this->_defaults = array_merge($this->_defaults, $this->_instanceValues);
751 }
752
753 CRM_Report_Form_Instance::setDefaultValues($this, $this->_defaults);
754
755 return $this->_defaults;
756 }
757
758 function getElementFromGroup($group, $grpFieldName) {
759 $eleObj = $this->getElement($group);
760 foreach ($eleObj->_elements as $index => $obj) {
761 if ($grpFieldName == $obj->_attributes['name']) {
762 return $obj;
763 }
764 }
765 return FALSE;
766 }
767
c58f66e0
E
768 /**
769 * Setter for $_params
770 * @param array $params
771 */
772 function setParams($params) {
773 $this->_params = $params;
774 }
775
776 /**
777 * Setter for $_id
778 * @param integer $id
779 */
780 function setID($instanceid) {
781 $this->_id = $instanceid;
782 }
783
784 /**
785 * Setter for $_force
786 * @param boolean $force
787 */
788 function setForce($isForce) {
789 $this->_force = $isForce;
790 }
6f900755
E
791
792 /**
793 * Setter for $_limitValue
794 * @param number $_limitValue
795 */
796 function setLimitValue($_limitValue) {
797 $this->_limitValue = $_limitValue;
798 }
799
800 /**
801 * Setter for $_offsetValue
802 * @param number $_offsetValue
803 */
804 function setOffsetValue($_offsetValue) {
805 $this->_offsetValue = $_offsetValue;
806 }
807
c58f66e0
E
808 /**
809 * Getter for $_defaultValues
810 * @return array $_defaultValues
811 */
812 function getDefaultValues() {
813 return $this->_defaults;
814 }
815
6a488035
TO
816 function addColumns() {
817 $options = array();
818 $colGroups = NULL;
819 foreach ($this->_columns as $tableName => $table) {
820 if (array_key_exists('fields', $table)) {
821 foreach ($table['fields'] as $fieldName => $field) {
8bdc861c 822 $groupTitle = '';
d4997a19 823 if (!CRM_Utils_Array::value('no_display', $field)) {
8bdc861c
DS
824 foreach ( array('table', 'field') as $var) {
825 if (!empty(${$var}['grouping'])) {
826 if (!is_array(${$var}['grouping'])) {
827 $tableName = ${$var}['grouping'];
828 } else {
b80138e0
DS
829 $tableName = array_keys(${$var}['grouping']);
830 $tableName = $tableName[0];
831 $groupTitle = array_values(${$var}['grouping']);
832 $groupTitle = $groupTitle[0];
8bdc861c
DS
833 }
834 }
6a488035 835 }
8bdc861c
DS
836
837 if (!$groupTitle && isset($table['group_title'])) {
838 $groupTitle = $table['group_title'];
6a488035 839 }
6a488035 840
8bdc861c
DS
841 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array::value('title', $field);
842 if ($groupTitle && !CRM_Utils_Array::value('group_title', $colGroups[$tableName])) {
843 $colGroups[$tableName]['group_title'] = $groupTitle;
6a488035
TO
844 }
845
846 $options[$fieldName] = CRM_Utils_Array::value('title', $field);
847 }
848 }
849 }
850 }
851
852 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
853 NULL, NULL, NULL, $this->_fourColumnAttribute, TRUE
854 );
855 $this->assign('colGroups', $colGroups);
856 }
857
858 function addFilters() {
859 $options = $filters = array();
860 $count = 1;
861 foreach ($this->_filters as $table => $attributes) {
862 foreach ($attributes as $fieldName => $field) {
863 // get ready with option value pair
1b36206c 864 // @ 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
865 // would be useful
866 $operations = $this->getOperationPair(
8f1445ea 867 CRM_Utils_Array::value('operatorType', $field),
1b36206c 868 $fieldName);
6a488035
TO
869
870 $filters[$table][$fieldName] = $field;
871
872 switch (CRM_Utils_Array::value('operatorType', $field)) {
873 case CRM_Report_Form::OP_MONTH:
874 if (!array_key_exists('options', $field) || !is_array($field['options']) || empty($field['options'])) {
875 // If there's no option list for this filter, define one.
876 $field['options'] = array(
877 1 => ts('January'),
878 2 => ts('February'),
879 3 => ts('March'),
880 4 => ts('April'),
881 5 => ts('May'),
882 6 => ts('June'),
883 7 => ts('July'),
884 8 => ts('August'),
885 9 => ts('September'),
886 10 => ts('October'),
887 11 => ts('November'),
888 12 => ts('December'),
889 );
890 // Add this option list to this column _columns. This is
891 // required so that filter statistics show properly.
892 $this->_columns[$table]['filters'][$fieldName]['options'] = $field['options'];
893 }
160d32e1
E
894 case CRM_Report_Form::OP_MULTISELECT:
895 case CRM_Report_Form::OP_MULTISELECT_SEPARATOR:
6a488035
TO
896 // assume a multi-select field
897 if (!empty($field['options'])) {
898 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
899 if (count($operations) <= 1) {
900 $element->freeze();
901 }
902 $select = $this->addElement('select', "{$fieldName}_value", NULL,
903 $field['options'], array(
904 'size' => 4,
905 'style' => 'min-width:250px',
906 )
907 );
908 $select->setMultiple(TRUE);
909 }
910 break;
911
160d32e1 912 case CRM_Report_Form::OP_SELECT:
6a488035
TO
913 // assume a select field
914 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
5a9a44d9
DS
915 if (!empty($field['options']))
916 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
6a488035
TO
917 break;
918
160d32e1 919 case CRM_Report_Form::OP_DATE:
6a488035 920 // build datetime fields
bc3f7f04 921 CRM_Core_Form_Date::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
6a488035
TO
922 $count++;
923 break;
924
160d32e1 925 case CRM_Report_Form::OP_DATETIME:
6a488035 926 // build datetime fields
bc3f7f04 927 CRM_Core_Form_Date::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
6a488035
TO
928 $count++;
929 break;
930
160d32e1
E
931 case CRM_Report_Form::OP_INT:
932 case CRM_Report_Form::OP_FLOAT:
6a488035
TO
933 // and a min value input box
934 $this->add('text', "{$fieldName}_min", ts('Min'));
935 // and a max value input box
936 $this->add('text', "{$fieldName}_max", ts('Max'));
937 default:
938 // default type is string
939 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
940 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
941 );
942 // we need text box for value input
943 $this->add('text', "{$fieldName}_value", NULL);
944 break;
945 }
946 }
947 }
948 $this->assign('filters', $filters);
949 }
950
951 function addOptions() {
952 if (!empty($this->_options)) {
953 // FIXME: For now lets build all elements as checkboxes.
954 // Once we clear with the format we can build elements based on type
955
956 $options = array();
957 foreach ($this->_options as $fieldName => $field) {
958 if ($field['type'] == 'select') {
959 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
960 }
52634dad 961 else if ($field['type'] == 'checkbox') {
6a488035 962 $options[$field['title']] = $fieldName;
52634dad
DS
963 $this->addCheckBox($fieldName, NULL,
964 $options, NULL,
965 NULL, NULL, NULL, $this->_fourColumnAttribute
966 );
6a488035
TO
967 }
968 }
6a488035 969 }
52634dad 970 $this->assign('otherOptions', $this->_options);
6a488035
TO
971 }
972
973 function addChartOptions() {
974 if (!empty($this->_charts)) {
975 $this->addElement('select', "charts", ts('Chart'), $this->_charts, array('onchange' => 'disablePrintPDFButtons(this.value);'));
976 $this->assign('charts', $this->_charts);
977 $this->addElement('submit', $this->_chartButtonName, ts('View'));
978 }
979 }
980
981 function addGroupBys() {
982 $options = $freqElements = array();
983
984 foreach ($this->_columns as $tableName => $table) {
985 if (array_key_exists('group_bys', $table)) {
986 foreach ($table['group_bys'] as $fieldName => $field) {
987 if (!empty($field)) {
988 $options[$field['title']] = $fieldName;
989 if (CRM_Utils_Array::value('frequency', $field)) {
990 $freqElements[$field['title']] = $fieldName;
991 }
992 }
993 }
994 }
995 }
996 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
997 NULL, NULL, NULL, $this->_fourColumnAttribute
998 );
999 $this->assign('groupByElements', $options);
1000
1001 foreach ($freqElements as $name) {
1002 $this->addElement('select', "group_bys_freq[$name]",
1003 ts('Frequency'), $this->_groupByDateFreq
1004 );
1005 }
1006 }
1007
1008 function addOrderBys() {
1009 $options = array();
1010 foreach ($this->_columns as $tableName => $table) {
1011
1012 // Report developer may define any column to order by; include these as order-by options
1013 if (array_key_exists('order_bys', $table)) {
1014 foreach ($table['order_bys'] as $fieldName => $field) {
1015 if (!empty($field)) {
1016 $options[$fieldName] = $field['title'];
1017 }
1018 }
1019 }
1020
1021 /* Add searchable custom fields as order-by options, if so requested
1022 * (These are already indexed, so allowing to order on them is cheap.)
1023 */
1024
1025
1026 if ($this->_autoIncludeIndexedFieldsAsOrderBys && array_key_exists('extends', $table) && !empty($table['extends'])) {
1027 foreach ($table['fields'] as $fieldName => $field) {
d4997a19 1028 if (!CRM_Utils_Array::value('no_display', $field)) {
6a488035
TO
1029 $options[$fieldName] = $field['title'];
1030 }
1031 }
1032 }
1033 }
1034
1035 asort($options);
1036
1037 $this->assign('orderByOptions', $options);
1038
1039 if (!empty($options)) {
1040 $options = array(
1041 '-' => ' - none - ') + $options;
1042 for ($i = 1; $i <= 5; $i++) {
1043 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
1044 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
1045 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$i"));
1046 }
1047 }
1048 }
1049
1050 function buildInstanceAndButtons() {
1051 CRM_Report_Form_Instance::buildForm($this);
1052
1053 $label = $this->_id ? ts('Update Report') : ts('Create Report');
1054
1055 $this->addElement('submit', $this->_instanceButtonName, $label);
1056 $this->addElement('submit', $this->_printButtonName, ts('Print Report'));
1057 $this->addElement('submit', $this->_pdfButtonName, ts('PDF'));
1058
1059 if ($this->_id) {
1060 $this->addElement('submit', $this->_createNewButtonName, ts('Save a Copy') . '...');
1061 }
1062 if ($this->_instanceForm) {
1063 $this->assign('instanceForm', TRUE);
1064 }
1065
1066 $label = $this->_id ? ts('Print Report') : ts('Print Preview');
1067 $this->addElement('submit', $this->_printButtonName, $label);
1068
1069 $label = $this->_id ? ts('PDF') : ts('Preview PDF');
1070 $this->addElement('submit', $this->_pdfButtonName, $label);
1071
1072 $label = $this->_id ? ts('Export to CSV') : ts('Preview CSV');
1073
1074 if ($this->_csvSupported) {
1075 $this->addElement('submit', $this->_csvButtonName, $label);
1076 }
1077
1078 if (CRM_Core_Permission::check('administer Reports') && $this->_add2groupSupported) {
1079 $this->addElement('select', 'groups', ts('Group'),
1080 array('' => ts('- select group -')) + CRM_Core_PseudoConstant::staticGroup()
1081 );
1082 $this->assign('group', TRUE);
1083 }
1084
1085 $label = ts('Add these Contacts to Group');
1086 $this->addElement('submit', $this->_groupButtonName, $label, array('onclick' => 'return checkGroup();'));
1087
1088 $this->addChartOptions();
1089 $this->addButtons(array(
1090 array(
1091 'type' => 'submit',
1092 'name' => ts('Preview Report'),
1093 'isDefault' => TRUE,
1094 ),
1095 )
1096 );
1097 }
1098
1099 function buildQuickForm() {
1100 $this->addColumns();
1101
1102 $this->addFilters();
1103
1104 $this->addOptions();
1105
1106 $this->addGroupBys();
1107
1108 $this->addOrderBys();
1109
1110 $this->buildInstanceAndButtons();
1111
1112 //add form rule for report
1113 if (is_callable(array(
1114 $this, 'formRule'))) {
1115 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1116 }
1117 }
1118
1119 // a formrule function to ensure that fields selected in group_by
1120 // (if any) should only be the ones present in display/select fields criteria;
1121 // note: works if and only if any custom field selected in group_by.
1122 function customDataFormRule($fields, $ignoreFields = array( )) {
1123 $errors = array();
1124 if (!empty($this->_customGroupExtends) && $this->_customGroupGroupBy && !empty($fields['group_bys'])) {
1125 foreach ($this->_columns as $tableName => $table) {
1126 if ((substr($tableName, 0, 13) == 'civicrm_value' || substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns[$tableName]['fields'])) {
1127 foreach ($this->_columns[$tableName]['fields'] as $fieldName => $field) {
1128 if (array_key_exists($fieldName, $fields['group_bys']) &&
1129 !array_key_exists($fieldName, $fields['fields'])
1130 ) {
1131 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1132 }
1133 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1134 foreach ($fields['fields'] as $fld => $val) {
1135 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1136 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1137 }
1138 }
1139 }
1140 }
1141 }
1142 }
1143 }
1144 return $errors;
1145 }
1146
1147 // Note: $fieldName param allows inheriting class to build operationPairs
1148 // specific to a field.
1b36206c 1149 function getOperationPair($type = "string", $fieldName = NULL) {
6a488035
TO
1150 // FIXME: At some point we should move these key-val pairs
1151 // to option_group and option_value table.
6a488035 1152 switch ($type) {
160d32e1
E
1153 case CRM_Report_Form::OP_INT:
1154 case CRM_Report_Form::OP_FLOAT:
bc3f7f04 1155 return array(
1156 'lte' => ts('Is less than or equal to'),
6a488035
TO
1157 'gte' => ts('Is greater than or equal to'),
1158 'bw' => ts('Is between'),
1159 'eq' => ts('Is equal to'),
1160 'lt' => ts('Is less than'),
1161 'gt' => ts('Is greater than'),
1162 'neq' => ts('Is not equal to'),
1163 'nbw' => ts('Is not between'),
1164 'nll' => ts('Is empty (Null)'),
1165 'nnll' => ts('Is not empty (Null)'),
1166 );
1167 break;
1168
160d32e1 1169 case CRM_Report_Form::OP_SELECT:
bc3f7f04 1170 return array(
1171 'eq' => ts('Is equal to'),
1172 );
6a488035 1173
160d32e1
E
1174 case CRM_Report_Form::OP_MONTH:
1175 case CRM_Report_Form::OP_MULTISELECT:
bc3f7f04 1176 return array(
1177 'in' => ts('Is one of'),
6a488035
TO
1178 'notin' => ts('Is not one of'),
1179 );
1180 break;
1181
160d32e1 1182 case CRM_Report_Form::OP_DATE:
bc3f7f04 1183 return array(
1184 'nll' => ts('Is empty (Null)'),
6a488035
TO
1185 'nnll' => ts('Is not empty (Null)'),
1186 );
1187 break;
1188
160d32e1 1189 case CRM_Report_Form::OP_MULTISELECT_SEPARATOR:
6a488035
TO
1190 // use this operator for the values, concatenated with separator. For e.g if
1191 // multiple options for a column is stored as ^A{val1}^A{val2}^A
bc3f7f04 1192 return array(
1193 'mhas' => ts('Is one of'),
1194 );
6a488035
TO
1195
1196 default:
1197 // type is string
bc3f7f04 1198 return array(
1199 'has' => ts('Contains'),
6a488035
TO
1200 'sw' => ts('Starts with'),
1201 'ew' => ts('Ends with'),
1202 'nhas' => ts('Does not contain'),
1203 'eq' => ts('Is equal to'),
1204 'neq' => ts('Is not equal to'),
1205 'nll' => ts('Is empty (Null)'),
1206 'nnll' => ts('Is not empty (Null)'),
1207 );
1208 }
1209 }
1210
1211 function buildTagFilter() {
1212 $contactTags = CRM_Core_BAO_Tag::getTags();
1213 if (!empty($contactTags)) {
1214 $this->_columns['civicrm_tag'] = array(
1215 'dao' => 'CRM_Core_DAO_Tag',
1216 'filters' =>
1217 array(
1218 'tagid' =>
1219 array(
1220 'name' => 'tag_id',
1221 'title' => ts('Tag'),
1222 'tag' => TRUE,
1223 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
1224 'options' => $contactTags,
1225 ),
1226 ),
1227 );
1228 }
1229 }
1230
1231 /*
1232 * Adds group filters to _columns (called from _Constuct
1233 */
1234 function buildGroupFilter() {
1235 $this->_columns['civicrm_group']['filters'] = array(
1236 'gid' =>
1237 array(
1238 'name' => 'group_id',
1239 'title' => ts('Group'),
1240 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
1241 'group' => TRUE,
1242 'options' => CRM_Core_PseudoConstant::group(),
1243 ),
1244 );
1245 if (empty($this->_columns['civicrm_group']['dao'])) {
1246 $this->_columns['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1247 }
1248 if (empty($this->_columns['civicrm_group']['alias'])) {
1249 $this->_columns['civicrm_group']['alias'] = 'cgroup';
1250 }
1251 }
1252
29fc2b79 1253 function getSQLOperator($operator = "like") {
6a488035
TO
1254 switch ($operator) {
1255 case 'eq':
1256 return '=';
1257
1258 case 'lt':
1259 return '<';
1260
1261 case 'lte':
1262 return '<=';
1263
1264 case 'gt':
1265 return '>';
1266
1267 case 'gte':
1268 return '>=';
1269
1270 case 'ne':
1271 case 'neq':
1272 return '!=';
1273
1274 case 'nhas':
1275 return 'NOT LIKE';
1276
1277 case 'in':
1278 return 'IN';
1279
1280 case 'notin':
1281 return 'NOT IN';
1282
1283 case 'nll':
1284 return 'IS NULL';
1285
1286 case 'nnll':
1287 return 'IS NOT NULL';
1288
1289 default:
1290 // type is string
1291 return 'LIKE';
1292 }
1293 }
1294
1295 function whereClause(&$field, $op,
1296 $value, $min, $max
1297 ) {
1298
1299 $type = CRM_Utils_Type::typeToString(CRM_Utils_Array::value('type', $field));
1300 $clause = NULL;
1301
1302 switch ($op) {
1303 case 'bw':
1304 case 'nbw':
1305 if (($min !== NULL && strlen($min) > 0) ||
1306 ($max !== NULL && strlen($max) > 0)
1307 ) {
1308 $min = CRM_Utils_Type::escape($min, $type);
1309 $max = CRM_Utils_Type::escape($max, $type);
1310 $clauses = array();
1311 if ($min) {
1312 if ($op == 'bw') {
1313 $clauses[] = "( {$field['dbAlias']} >= $min )";
1314 }
1315 else {
1316 $clauses[] = "( {$field['dbAlias']} < $min )";
1317 }
1318 }
1319 if ($max) {
1320 if ($op == 'bw') {
1321 $clauses[] = "( {$field['dbAlias']} <= $max )";
1322 }
1323 else {
1324 $clauses[] = "( {$field['dbAlias']} > $max )";
1325 }
1326 }
1327
1328 if (!empty($clauses)) {
1329 if ($op == 'bw') {
1330 $clause = implode(' AND ', $clauses);
1331 }
1332 else {
1333 $clause = implode(' OR ', $clauses);
1334 }
1335 }
1336 }
1337 break;
1338
1339 case 'has':
1340 case 'nhas':
1341 if ($value !== NULL && strlen($value) > 0) {
1342 $value = CRM_Utils_Type::escape($value, $type);
1343 if (strpos($value, '%') === FALSE) {
1344 $value = "'%{$value}%'";
1345 }
1346 else {
1347 $value = "'{$value}'";
1348 }
29fc2b79 1349 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1350 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1351 }
1352 break;
1353
1354 case 'in':
1355 case 'notin':
1356 if ($value !== NULL && is_array($value) && count($value) > 0) {
29fc2b79 1357 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1358 if (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_STRING) {
1359 //cycle through selections and esacape values
1360 foreach ($value as $key => $selection) {
1361 $value[$key] = CRM_Utils_Type::escape($selection, $type);
1362 }
1363 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1364 }
1365 else {
1366 // for numerical values
1367 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1368 }
1369 if ($op == 'notin') {
1370 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1371 }
1372 else {
1373 $clause = "( " . $clause . " )";
1374 }
1375 }
1376 break;
1377
1378 case 'mhas':
1379 // mhas == multiple has
1380 if ($value !== NULL && count($value) > 0) {
29fc2b79 1381 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1382 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1383 }
1384 break;
1385
1386 case 'sw':
1387 case 'ew':
1388 if ($value !== NULL && strlen($value) > 0) {
1389 $value = CRM_Utils_Type::escape($value, $type);
1390 if (strpos($value, '%') === FALSE) {
1391 if ($op == 'sw') {
1392 $value = "'{$value}%'";
1393 }
1394 else {
1395 $value = "'%{$value}'";
1396 }
1397 }
1398 else {
1399 $value = "'{$value}'";
1400 }
29fc2b79 1401 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1402 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1403 }
1404 break;
1405
1406 case 'nll':
1407 case 'nnll':
29fc2b79 1408 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1409 $clause = "( {$field['dbAlias']} $sqlOP )";
1410 break;
1411
1412 default:
1413 if ($value !== NULL && strlen($value) > 0) {
1414 if (isset($field['clause'])) {
1415 // FIXME: we not doing escape here. Better solution is to use two
1416 // different types - data-type and filter-type
0e6e8724 1417 $clause = $field['clause'];
6a488035
TO
1418 }
1419 else {
1420 $value = CRM_Utils_Type::escape($value, $type);
29fc2b79 1421 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1422 if ($field['type'] == CRM_Utils_Type::T_STRING) {
1423 $value = "'{$value}'";
1424 }
1425 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1426 }
1427 }
1428 break;
1429 }
1430
1431 if (CRM_Utils_Array::value('group', $field) && $clause) {
1432 $clause = $this->whereGroupClause($field, $value, $op);
1433 }
1434 elseif (CRM_Utils_Array::value('tag', $field) && $clause) {
1435 // not using left join in query because if any contact
1436 // belongs to more than one tag, results duplicate
1437 // entries.
1438 $clause = $this->whereTagClause($field, $value, $op);
1439 }
1440
1441 return $clause;
1442 }
1443
1444 function dateClause($fieldName,
1445 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1446 ) {
1447 $clauses = array();
160d32e1 1448 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form::OP_DATE)))) {
29fc2b79 1449 $sqlOP = $this->getSQLOperator($relative);
6a488035
TO
1450 return "( {$fieldName} {$sqlOP} )";
1451 }
1452
29fc2b79 1453 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
6a488035
TO
1454
1455 if ($from) {
1456 $from = ($type == CRM_Utils_Type::T_DATE) ? substr($from, 0, 8) : $from;
1457 $clauses[] = "( {$fieldName} >= $from )";
1458 }
1459
1460 if ($to) {
1461 $to = ($type == CRM_Utils_Type::T_DATE) ? substr($to, 0, 8) : $to;
1462 $clauses[] = "( {$fieldName} <= {$to} )";
1463 }
1464
1465 if (!empty($clauses)) {
1466 return implode(' AND ', $clauses);
1467 }
1468
1469 return NULL;
1470 }
29fc2b79 1471 /**
1472 * @todo - could not find any instances where this is called
1473 * @param unknown_type $relative
1474 * @param String $from
1475 * @param String_type $to
1476 * @return string|NULL
1477 */
1478 function dateDisplay($relative, $from, $to) {
1479 list($from, $to) = $this->getFromTo($relative, $from, $to);
6a488035
TO
1480
1481 if ($from) {
1482 $clauses[] = CRM_Utils_Date::customFormat($from, NULL, array('m', 'M'));
1483 }
1484 else {
1485 $clauses[] = 'Past';
1486 }
1487
1488 if ($to) {
1489 $clauses[] = CRM_Utils_Date::customFormat($to, NULL, array('m', 'M'));
1490 }
1491 else {
1492 $clauses[] = 'Today';
1493 }
1494
1495 if (!empty($clauses)) {
1496 return implode(' - ', $clauses);
1497 }
1498
1499 return NULL;
1500 }
1501
29fc2b79 1502 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
6a488035
TO
1503 if (empty($totime)) {
1504 $totime = '235959';
1505 }
1506 //FIX ME not working for relative
1507 if ($relative) {
1508 list($term, $unit) = CRM_Utils_System::explode('.', $relative, 2);
1509 $dateRange = CRM_Utils_Date::relativeToAbsolute($term, $unit);
1510 $from = substr($dateRange['from'], 0, 8);
1511 //Take only Date Part, Sometime Time part is also present in 'to'
1512 $to = substr($dateRange['to'], 0, 8);
1513 }
1514 $from = CRM_Utils_Date::processDate($from, $fromtime);
1515 $to = CRM_Utils_Date::processDate($to, $totime);
1516 return array($from, $to);
1517 }
1518
1519 function alterDisplay(&$rows) {
1520 // custom code to alter rows
1521 }
1522
1523 function alterCustomDataDisplay(&$rows) {
1524 // custom code to alter rows having custom values
1525 if (empty($this->_customGroupExtends)) {
1526 return;
1527 }
1528
1529 $customFieldIds = array();
1530 foreach ($this->_params['fields'] as $fieldAlias => $value) {
1531 if ($fieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
1532 $customFieldIds[$fieldAlias] = $fieldId;
1533 }
1534 }
1535 if (empty($customFieldIds)) {
1536 return;
1537 }
1538
1539 $customFields = $fieldValueMap = array();
1540 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1541
1542 // skip for type date and ContactReference since date format is already handled
1543 $query = "
1544SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1545FROM civicrm_custom_field cf
1546INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1547LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1548WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
1549 cg.is_active = 1 AND
1550 cf.is_active = 1 AND
1551 cf.is_searchable = 1 AND
1552 cf.data_type NOT IN ('ContactReference', 'Date') AND
1553 cf.id IN (" . implode(",", $customFieldIds) . ")";
1554
1555 $dao = CRM_Core_DAO::executeQuery($query);
1556 while ($dao->fetch()) {
1557 foreach ($customFieldCols as $key) {
1558 $customFields[$dao->table_name . '_custom_' . $dao->id][$key] = $dao->$key;
1559 }
1560 if ($dao->option_group_id) {
1561 $fieldValueMap[$dao->option_group_id][$dao->value] = $dao->label;
1562 }
1563 }
1564 $dao->free();
1565
1566 $entryFound = FALSE;
1567 foreach ($rows as $rowNum => $row) {
1568 foreach ($row as $tableCol => $val) {
1569 if (array_key_exists($tableCol, $customFields)) {
1570 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1571 $entryFound = TRUE;
1572 }
1573 }
1574
1575 // skip looking further in rows, if first row itself doesn't
1576 // have the column we need
1577 if (!$entryFound) {
1578 break;
1579 }
1580 }
1581 }
1582
1583 function formatCustomValues($value, $customField, $fieldValueMap) {
1584 if (CRM_Utils_System::isNull($value)) {
1585 return;
1586 }
1587
1588 $htmlType = $customField['html_type'];
1589
1590 switch ($customField['data_type']) {
1591 case 'Boolean':
1592 if ($value == '1') {
1593 $retValue = ts('Yes');
1594 }
1595 else {
1596 $retValue = ts('No');
1597 }
1598 break;
1599
1600 case 'Link':
1601 $retValue = CRM_Utils_System::formatWikiURL($value);
1602 break;
1603
1604 case 'File':
1605 $retValue = $value;
1606 break;
1607
1608 case 'Memo':
1609 $retValue = $value;
1610 break;
1611
1612 case 'Float':
1613 if ($htmlType == 'Text') {
1614 $retValue = (float)$value;
1615 break;
1616 }
1617 case 'Money':
1618 if ($htmlType == 'Text') {
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628 $retValue = CRM_Utils_Money::format($value, NULL, '%a');
1629 break;
1630 }
1631 case 'String':
1632 case 'Int':
1633 if (in_array($htmlType, array(
1634 'Text', 'TextArea'))) {
1635 $retValue = $value;
1636 break;
1637 }
1638 case 'StateProvince':
1639 case 'Country':
1640
1641 switch ($htmlType) {
1642 case 'Multi-Select Country':
1643 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1644 $customData = array();
1645 foreach ($value as $val) {
1646 if ($val) {
1647 $customData[] = CRM_Core_PseudoConstant::country($val, FALSE);
1648 }
1649 }
1650 $retValue = implode(', ', $customData);
1651 break;
1652
1653 case 'Select Country':
1654 $retValue = CRM_Core_PseudoConstant::country($value, FALSE);
1655 break;
1656
1657 case 'Select State/Province':
1658 $retValue = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
1659 break;
1660
1661 case 'Multi-Select State/Province':
1662 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1663 $customData = array();
1664 foreach ($value as $val) {
1665 if ($val) {
1666 $customData[] = CRM_Core_PseudoConstant::stateProvince($val, FALSE);
1667 }
1668 }
1669 $retValue = implode(', ', $customData);
1670 break;
1671
1672 case 'Select':
1673 case 'Radio':
1674 case 'Autocomplete-Select':
1675 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1676 break;
1677
1678 case 'CheckBox':
1679 case 'AdvMulti-Select':
1680 case 'Multi-Select':
1681 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1682 $customData = array();
1683 foreach ($value as $val) {
1684 if ($val) {
1685 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1686 }
1687 }
1688 $retValue = implode(', ', $customData);
1689 break;
1690
1691 default:
1692 $retValue = $value;
1693 }
1694 break;
1695
1696 default:
1697 $retValue = $value;
1698 }
1699
1700 return $retValue;
1701 }
1702
1703 function removeDuplicates(&$rows) {
1704 if (empty($this->_noRepeats)) {
1705 return;
1706 }
1707 $checkList = array();
1708
1709 foreach ($rows as $key => $list) {
1710 foreach ($list as $colName => $colVal) {
8f1445ea 1711 if (array_key_exists($colName, $checkList) &&
6a488035
TO
1712 $checkList[$colName] == $colVal) {
1713 $rows[$key][$colName] = "";
1714 }
1715 if (in_array($colName, $this->_noRepeats)) {
1716 $checkList[$colName] = $colVal;
1717 }
1718 }
1719 }
1720 }
1721
1722 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1723 foreach ($row as $colName => $colVal) {
1724 if (in_array($colName, $fields)) {
1725 $row[$colName] = $row[$colName];
1726 }
1727 elseif (isset($this->_columnHeaders[$colName])) {
1728 if ($subtotal) {
1729 $row[$colName] = "Subtotal";
1730 $subtotal = FALSE;
1731 }
1732 else {
1733 unset($row[$colName]);
1734 }
1735 }
1736 }
1737 }
1738
1739 function grandTotal(&$rows) {
1740 if (!$this->_rollup || ($this->_rollup == '') ||
1741 ($this->_limit && count($rows) >= self::ROW_COUNT_LIMIT)
1742 ) {
1743 return FALSE;
1744 }
1745 $lastRow = array_pop($rows);
1746
6a488035
TO
1747 foreach ($this->_columnHeaders as $fld => $val) {
1748 if (!in_array($fld, $this->_statFields)) {
1749 if (!$this->_grandFlag) {
1750 $lastRow[$fld] = "Grand Total";
1751 $this->_grandFlag = TRUE;
1752 }
1753 else {
1754 $lastRow[$fld] = "";
1755 }
1756 }
1757 }
1758
1759 $this->assign('grandStat', $lastRow);
1760 return TRUE;
1761 }
1762
1763 function formatDisplay(&$rows, $pager = TRUE) {
1764 // set pager based on if any limit was applied in the query.
1765 if ($pager) {
1766 $this->setPager();
1767 }
1768
1769 // allow building charts if any
1770 if (!empty($this->_params['charts']) && !empty($rows)) {
1771 $this->buildChart($rows);
1772 $this->assign('chartEnabled', TRUE);
1773 $this->_chartId = "{$this->_params['charts']}_" . ($this->_id ? $this->_id : substr(get_class($this), 16)) . '_' . session_id();
1774 $this->assign('chartId', $this->_chartId);
1775 }
1776
1777 // unset columns not to be displayed.
1778 foreach ($this->_columnHeaders as $key => $value) {
d4997a19 1779 if (CRM_Utils_Array::value('no_display', $value)) {
6a488035
TO
1780 unset($this->_columnHeaders[$key]);
1781 }
1782 }
1783
1784 // unset columns not to be displayed.
1785 if (!empty($rows)) {
1786 foreach ($this->_noDisplay as $noDisplayField) {
1787 foreach ($rows as $rowNum => $row) {
1788 unset($this->_columnHeaders[$noDisplayField]);
1789 }
1790 }
1791 }
1792
1793 // build array of section totals
1794 $this->sectionTotals();
1795
1796 // process grand-total row
1797 $this->grandTotal($rows);
1798
1799 // use this method for formatting rows for display purpose.
1800 $this->alterDisplay($rows);
1801 CRM_Utils_Hook::alterReportVar('rows', $rows, $this);
1802
1803 // use this method for formatting custom rows for display purpose.
1804 $this->alterCustomDataDisplay($rows);
1805 }
1806
1807 function buildChart(&$rows) {
1808 // override this method for building charts.
1809 }
1810
1811 // select() method below has been added recently (v3.3), and many of the report templates might
1812 // still be having their own select() method. We should fix them as and when encountered and move
1813 // towards generalizing the select() method below.
1814 function select() {
1f220d30 1815 $select = $this->_selectAliases = array();
6a488035
TO
1816
1817 foreach ($this->_columns as $tableName => $table) {
1818 if (array_key_exists('fields', $table)) {
1819 foreach ($table['fields'] as $fieldName => $field) {
1820 if ($tableName == 'civicrm_address') {
1821 $this->_addressField = TRUE;
1822 }
1823 if ($tableName == 'civicrm_email') {
1824 $this->_emailField = TRUE;
1825 }
1826 if ($tableName == 'civicrm_phone') {
1827 $this->_phoneField = TRUE;
1828 }
1829
1830 if (CRM_Utils_Array::value('required', $field) ||
1831 CRM_Utils_Array::value($fieldName, $this->_params['fields'])
1832 ) {
1833
1834 // 1. In many cases we want select clause to be built in slightly different way
1835 // for a particular field of a particular type.
1836 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1837 // as needed.
1838 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1839 if ($selectClause) {
1840 $select[] = $selectClause;
1841 continue;
1842 }
1843
1844 // include statistics columns only if set
1845 if (CRM_Utils_Array::value('statistics', $field)) {
1846 foreach ($field['statistics'] as $stat => $label) {
1847 $alias = "{$tableName}_{$fieldName}_{$stat}";
1848 switch (strtolower($stat)) {
1849 case 'max':
1850 case 'sum':
1851 $select[] = "$stat({$field['dbAlias']}) as $alias";
1852 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1853 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
9e6d7767 1854 $this->_statFields[$label] = $alias;
6a488035
TO
1855 $this->_selectAliases[] = $alias;
1856 break;
1857
1858 case 'count':
1859 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1860 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1861 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
9e6d7767 1862 $this->_statFields[$label] = $alias;
6a488035
TO
1863 $this->_selectAliases[] = $alias;
1864 break;
1865
1bfaf6a6
DS
1866 case 'count_distinct':
1867 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1868 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1869 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
1870 $this->_statFields[$label] = $alias;
1871 $this->_selectAliases[] = $alias;
1872 break;
1873
6a488035
TO
1874 case 'avg':
1875 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1876 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1877 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
9e6d7767 1878 $this->_statFields[$label] = $alias;
6a488035
TO
1879 $this->_selectAliases[] = $alias;
1880 break;
1881 }
1882 }
1883 }
1884 else {
1885 $alias = "{$tableName}_{$fieldName}";
1886 $select[] = "{$field['dbAlias']} as $alias";
1887 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
1888 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
1889 $this->_selectAliases[] = $alias;
1890 }
1891 }
1892 }
1893 }
1894
1895 // select for group bys
1896 if (array_key_exists('group_bys', $table)) {
1897 foreach ($table['group_bys'] as $fieldName => $field) {
1898
1899 if ($tableName == 'civicrm_address') {
1900 $this->_addressField = TRUE;
1901 }
1902 if ($tableName == 'civicrm_email') {
1903 $this->_emailField = TRUE;
1904 }
1905 if ($tableName == 'civicrm_phone') {
1906 $this->_phoneField = TRUE;
1907 }
1908 // 1. In many cases we want select clause to be built in slightly different way
1909 // for a particular field of a particular type.
1910 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1911 // as needed.
1912 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1913 if ($selectClause) {
1914 $select[] = $selectClause;
1915 continue;
1916 }
1917
1918 if (!empty($this->_params['group_bys']) && CRM_Utils_Array::value($fieldName, $this->_params['group_bys'])
1919 && !empty($this->_params['group_bys_freq'])) {
1920 switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
1921 case 'YEARWEEK':
1922 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1923 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1924 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1925 $field['title'] = 'Week';
1926 break;
1927
1928 case 'YEAR':
1929 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1930 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1931 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1932 $field['title'] = 'Year';
1933 break;
1934
1935 case 'MONTH':
1936 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1937 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1938 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1939 $field['title'] = 'Month';
1940 break;
1941
1942 case 'QUARTER':
1943 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1944 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1945 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1946 $field['title'] = 'Quarter';
1947 break;
1948 }
1949 // for graphs and charts -
1950 if (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
1951 $this->_interval = $field['title'];
1952 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1953 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1954 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
1955
1956 // just to make sure these values are transfered to rows.
1957 // since we 'll need them for calculation purpose,
1958 // e.g making subtotals look nicer or graphs
1959 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1960 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1961 }
1962 }
1963 }
1964 }
1965 }
1966
1f220d30 1967 $this->_selectClauses = $select;
6a488035
TO
1968 $this->_select = "SELECT " . implode(', ', $select) . " ";
1969 }
1970
1971 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1972 return FALSE;
1973 }
1974
1975 function where() {
adfe2750 1976 $this->storeWhereHavingClauseArray();
1977
1978 if (empty($this->_whereClauses)) {
1979 $this->_where = "WHERE ( 1 ) ";
1980 $this->_having = "";
1981 }
1982 else {
1983 $this->_where = "WHERE " . implode(' AND ', $this->_whereClauses);
1984 }
1985
1986 if ($this->_aclWhere) {
1987 $this->_where .= " AND {$this->_aclWhere} ";
1988 }
1989
1990 if (!empty($this->_havingClauses)) {
1991 // use this clause to construct group by clause.
1992 $this->_having = "HAVING " . implode(' AND ', $this->_havingClauses);
1993 }
1994 }
1995
1996 /**
1997 * Store Where clauses into an array - breaking out this step makes
1998 * over-riding more flexible as the clauses can be used in constructing a
1999 * temp table that may not be part of the final where clause or added
2000 * in other functions
2001 */
2002 function storeWhereHavingClauseArray(){
6a488035
TO
2003 foreach ($this->_columns as $tableName => $table) {
2004 if (array_key_exists('filters', $table)) {
2005 foreach ($table['filters'] as $fieldName => $field) {
d12de91c 2006 // respect pseudofield to filter spec so fields can be marked as
2007 // not to be handled here
2008 if(!empty($field['pseudofield'])){
2009 continue;
2010 }
6a488035
TO
2011 $clause = NULL;
2012 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
2013 if (CRM_Utils_Array::value('operatorType', $field) == CRM_Report_Form::OP_MONTH) {
2014 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2015 $value = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
2016 if (is_array($value) && !empty($value)) {
2017 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2018 }
2019 }
2020 else {
2021 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
2022 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
2023 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
2024 $fromTime = CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params);
2025 $toTime = CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params);
2026 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2027 }
2028 }
2029 else {
2030 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2031 if ($op) {
2032 $clause = $this->whereClause($field,
adfe2750 2033 $op,
2034 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
2035 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
2036 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
6a488035
TO
2037 );
2038 }
2039 }
2040
2041 if (!empty($clause)) {
2042 if (CRM_Utils_Array::value('having', $field)) {
adfe2750 2043 $this->_havingClauses[] = $clause;
6a488035
TO
2044 }
2045 else {
adfe2750 2046 $this->_whereClauses[] = $clause;
6a488035
TO
2047 }
2048 }
2049 }
2050 }
2051 }
2052
6a488035 2053 }
6a488035
TO
2054 function processReportMode() {
2055 $buttonName = $this->controller->getButtonName();
2056
884605ca
DL
2057 $output = CRM_Utils_Request::retrieve(
2058 'output',
2059 'String',
2060 CRM_Core_DAO::$_nullObject
6a488035
TO
2061 );
2062
2063 $this->_sendmail =
884605ca
DL
2064 CRM_Utils_Request::retrieve(
2065 'sendmail',
2066 'Boolean',
2067 CRM_Core_DAO::$_nullObject
2068 );
6a488035
TO
2069
2070 $this->_absoluteUrl = FALSE;
2071 $printOnly = FALSE;
2072 $this->assign('printOnly', FALSE);
2073
2074 if ($this->_printButtonName == $buttonName || $output == 'print' || ($this->_sendmail && !$output)) {
2075 $this->assign('printOnly', TRUE);
2076 $printOnly = TRUE;
2077 $this->assign('outputMode', 'print');
2078 $this->_outputMode = 'print';
2079 if ($this->_sendmail) {
2080 $this->_absoluteUrl = TRUE;
2081 }
2082 }
2083 elseif ($this->_pdfButtonName == $buttonName || $output == 'pdf') {
2084 $this->assign('printOnly', TRUE);
2085 $printOnly = TRUE;
2086 $this->assign('outputMode', 'pdf');
2087 $this->_outputMode = 'pdf';
2088 $this->_absoluteUrl = TRUE;
2089 }
2090 elseif ($this->_csvButtonName == $buttonName || $output == 'csv') {
2091 $this->assign('printOnly', TRUE);
2092 $printOnly = TRUE;
2093 $this->assign('outputMode', 'csv');
2094 $this->_outputMode = 'csv';
2095 $this->_absoluteUrl = TRUE;
2096 }
2097 elseif ($this->_groupButtonName == $buttonName || $output == 'group') {
2098 $this->assign('outputMode', 'group');
2099 $this->_outputMode = 'group';
2100 }
2101 elseif ($output == 'create_report' && $this->_criteriaForm) {
2102 $this->assign('outputMode', 'create_report');
2103 $this->_outputMode = 'create_report';
2104 }
2105 else {
2106 $this->assign('outputMode', 'html');
2107 $this->_outputMode = 'html';
2108 }
2109
2110 // Get today's date to include in printed reports
2111 if ($printOnly) {
2112 $reportDate = CRM_Utils_Date::customFormat(date('Y-m-d H:i'));
2113 $this->assign('reportDate', $reportDate);
2114 }
2115 }
2116
2117 function beginPostProcess() {
c58f66e0 2118 $this->setParams($this->controller->exportValues($this->_name));
6a488035
TO
2119
2120 if (empty($this->_params) &&
2121 $this->_force
2122 ) {
c58f66e0 2123 $this->setParams($this->_formValues);
6a488035
TO
2124 }
2125
2126 // hack to fix params when submitted from dashboard, CRM-8532
2127 // fields array is missing because form building etc is skipped
2128 // in dashboard mode for report
c58f66e0 2129 //@todo - this could be done in the dashboard no we have a setter
6a488035 2130 if (!CRM_Utils_Array::value('fields', $this->_params) && !$this->_noFields) {
c58f66e0 2131 $this->setParams($this->_formValues);
6a488035
TO
2132 }
2133
2134 $this->_formValues = $this->_params;
2135 if (CRM_Core_Permission::check('administer Reports') &&
2136 isset($this->_id) &&
2137 ($this->_instanceButtonName == $this->controller->getButtonName() . '_save' ||
2138 $this->_chartButtonName == $this->controller->getButtonName()
2139 )
2140 ) {
2141 $this->assign('updateReportButton', TRUE);
2142 }
2143 $this->processReportMode();
c58f66e0
E
2144 $this->beginPostProcessCommon();
2145 }
2146
2147 /**
2148 * beginPostProcess function run in both report mode and non-report mode (api)
2149 */
2150 function beginPostProcessCommon() {
2151
6a488035
TO
2152 }
2153
2154 function buildQuery($applyLimit = TRUE) {
2155 $this->select();
2156 $this->from();
2157 $this->customDataFrom();
2158 $this->where();
2159 $this->groupBy();
2160 $this->orderBy();
2161
2162 // order_by columns not selected for display need to be included in SELECT
2163 $unselectedSectionColumns = $this->unselectedSectionColumns();
2164 foreach ($unselectedSectionColumns as $alias => $section) {
2165 $this->_select .= ", {$section['dbAlias']} as {$alias}";
2166 }
2167
2168 if ($applyLimit && !CRM_Utils_Array::value('charts', $this->_params)) {
2169 $this->limit();
2170 }
2171 CRM_Utils_Hook::alterReportVar('sql', $this, $this);
2172
2173 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2174 return $sql;
2175 }
2176
2177 function groupBy() {
2178 $groupBys = array();
2179 if (CRM_Utils_Array::value('group_bys', $this->_params) &&
2180 is_array($this->_params['group_bys']) &&
2181 !empty($this->_params['group_bys'])
2182 ) {
2183 foreach ($this->_columns as $tableName => $table) {
2184 if (array_key_exists('group_bys', $table)) {
2185 foreach ($table['group_bys'] as $fieldName => $field) {
2186 if (CRM_Utils_Array::value($fieldName, $this->_params['group_bys'])) {
2187 $groupBys[] = $field['dbAlias'];
2188 }
2189 }
2190 }
2191 }
2192 }
2193
2194 if (!empty($groupBys)) {
2195 $this->_groupBy = "GROUP BY " . implode(', ', $groupBys);
2196 }
2197 }
2198
2199 function orderBy() {
2200 $this->_orderBy = "";
2201 $this->_sections = array();
2202 $this->storeOrderByArray();
2203 if(!empty($this->_orderByArray) && !$this->_rollup == 'WITH ROLLUP'){
2204 $this->_orderBy = "ORDER BY " . implode(', ', $this->_orderByArray);
2205 }
2206 $this->assign('sections', $this->_sections);
2207 }
f2947aea 2208
6a488035
TO
2209 /*
2210 * In some cases other functions want to know which fields are selected for ordering by
2211 * Separating this into a separate function allows it to be called separately from constructing
2212 * the order by clause
2213 */
2214 function storeOrderByArray() {
2215 $orderBys = array();
2216
2217 if (CRM_Utils_Array::value('order_bys', $this->_params) &&
2218 is_array($this->_params['order_bys']) &&
2219 !empty($this->_params['order_bys'])
2220 ) {
2221
2222 // Proces order_bys in user-specified order
2223 foreach ($this->_params['order_bys'] as $orderBy) {
2224 $orderByField = array();
2225 foreach ($this->_columns as $tableName => $table) {
2226 if (array_key_exists('order_bys', $table)) {
2227 // For DAO columns defined in $this->_columns
2228 $fields = $table['order_bys'];
2229 }
2230 elseif (array_key_exists('extends', $table)) {
2231 // For custom fields referenced in $this->_customGroupExtends
1efec7ff 2232 $fields = CRM_Utils_Array::value('fields', $table, array());
6a488035
TO
2233 }
2234 if (!empty($fields) && is_array($fields)) {
2235 foreach ($fields as $fieldName => $field) {
2236 if ($fieldName == $orderBy['column']) {
f2947aea 2237 $orderByField = array_merge($field, $orderBy);
6a488035
TO
2238 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2239 break 2;
2240 }
2241 }
2242 }
2243 }
2244
2245 if (!empty($orderByField)) {
f2947aea 2246 $this->_orderByFields[] = $orderByField;
6a488035
TO
2247 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2248
2249 // Record any section headers for assignment to the template
2250 if (CRM_Utils_Array::value('section', $orderBy)) {
2251 $this->_sections[$orderByField['tplField']] = $orderByField;
2252 }
2253 }
2254 }
2255 }
2256
2257 $this->_orderByArray = $orderBys;
2258
2259 $this->assign('sections', $this->_sections);
2260 }
2261
2262 function unselectedSectionColumns() {
2263 $selectColumns = array();
2264 foreach ($this->_columns as $tableName => $table) {
2265 if (array_key_exists('fields', $table)) {
2266 foreach ($table['fields'] as $fieldName => $field) {
2267 if (CRM_Utils_Array::value('required', $field) ||
2268 CRM_Utils_Array::value($fieldName, $this->_params['fields'])
2269 ) {
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) {
2421 if (CRM_Utils_Array::value('group_bys', $this->_params) &&
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) {
2428 if (CRM_Utils_Array::value($fieldName, $this->_params['group_bys'])) {
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 );
6a488035
TO
2453 $from_time_format = CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params) ? 'h' : 'd';
2454 $from = CRM_Utils_Date::customFormat($from, null, array($from_time_format));
2455
2456 $to_time_format = CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params) ? 'h' : 'd';
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 }
f974e915 2500 $pair[$op] = (count($val) == 1) ? (($op == 'notin') ? 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);
2734 }
2735 }
2736
2737 function whereGroupClause($field, $value, $op) {
2738
2739 $smartGroupQuery = "";
2740
2741 $group = new CRM_Contact_DAO_Group();
2742 $group->is_active = 1;
2743 $group->find();
2744 $smartGroups = array();
2745 while ($group->fetch()) {
2746 if (in_array($group->id, $this->_params['gid_value']) && $group->saved_search_id) {
2747 $smartGroups[] = $group->id;
2748 }
2749 }
2750
2751 CRM_Contact_BAO_GroupContactCache::check($smartGroups);
2752
2753 $smartGroupQuery = '';
2754 if (!empty($smartGroups)) {
2755 $smartGroups = implode(',', $smartGroups);
2756 $smartGroupQuery = " UNION DISTINCT
2757 SELECT DISTINCT smartgroup_contact.contact_id
2758 FROM civicrm_group_contact_cache smartgroup_contact
2759 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2760 }
2761
29fc2b79 2762 $sqlOp = $this->getSQLOperator($op);
6a488035
TO
2763 if (!is_array($value)) {
2764 $value = array($value);
2765 }
2766 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2767
2768 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2769 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2770 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2771 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2772 {$smartGroupQuery} ) ";
2773 }
2774
2775 function whereTagClause($field, $value, $op) {
2776 // not using left join in query because if any contact
2777 // belongs to more than one tag, results duplicate
2778 // entries.
29fc2b79 2779 $sqlOp = $this->getSQLOperator($op);
6a488035
TO
2780 if (!is_array($value)) {
2781 $value = array($value);
2782 }
2783 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2784
2785 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2786 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2787 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2788 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2789 }
2790
2791 function buildACLClause($tableAlias = 'contact_a') {
2792 list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
2793 }
2794
2795 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2796 if (empty($this->_customGroupExtends)) {
2797 return;
2798 }
2799 if (!is_array($this->_customGroupExtends)) {
2800 $this->_customGroupExtends = array($this->_customGroupExtends);
2801 }
2802 $customGroupWhere = '';
2803 if (!empty($permCustomGroupIds)) {
2804 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2805 }
2806 $sql = "
2807SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2808 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2809FROM civicrm_custom_group cg
2810INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2811WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
2812 {$customGroupWhere}
2813 cg.is_active = 1 AND
2814 cf.is_active = 1 AND
2815 cf.is_searchable = 1
2816ORDER BY cg.weight, cf.weight";
2817 $customDAO = CRM_Core_DAO::executeQuery($sql);
2818
2819 $curTable = NULL;
2820 while ($customDAO->fetch()) {
2821 if ($customDAO->table_name != $curTable) {
2822 $curTable = $customDAO->table_name;
2823 $curFields = $curFilters = array();
2824
2825 // dummy dao object
2826 $this->_columns[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2827 $this->_columns[$curTable]['extends'] = $customDAO->extends;
2828 $this->_columns[$curTable]['grouping'] = $customDAO->table_name;
2829 $this->_columns[$curTable]['group_title'] = $customDAO->title;
2830
2831 foreach (array(
2832 'fields', 'filters', 'group_bys') as $colKey) {
2833 if (!array_key_exists($colKey, $this->_columns[$curTable])) {
2834 $this->_columns[$curTable][$colKey] = array();
2835 }
2836 }
2837 }
2838 $fieldName = 'custom_' . $customDAO->cf_id;
2839
2840 if ($addFields) {
2841 // this makes aliasing work in favor
2842 $curFields[$fieldName] = array(
2843 'name' => $customDAO->column_name,
2844 'title' => $customDAO->label,
2845 'dataType' => $customDAO->data_type,
2846 'htmlType' => $customDAO->html_type,
2847 );
2848 }
2849 if ($this->_customGroupFilters) {
2850 // this makes aliasing work in favor
2851 $curFilters[$fieldName] = array(
2852 'name' => $customDAO->column_name,
2853 'title' => $customDAO->label,
2854 'dataType' => $customDAO->data_type,
2855 'htmlType' => $customDAO->html_type,
2856 );
2857 }
2858
2859 switch ($customDAO->data_type) {
2860 case 'Date':
2861 // filters
2862 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE;
2863 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_DATE;
2864 // CRM-6946, show time part for datetime date fields
2865 if ($customDAO->time_format) {
2866 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_TIMESTAMP;
2867 }
2868 break;
2869
2870 case 'Boolean':
2871 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT;
2872 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2873 1 => ts('Yes'),
2874 0 => ts('No'),
2875 );
2876 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
2877 break;
2878
2879 case 'Int':
2880 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_INT;
2881 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
2882 break;
2883
2884 case 'Money':
2885 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
2886 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_MONEY;
2887 break;
2888
2889 case 'Float':
2890 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
2891 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_FLOAT;
2892 break;
2893
2894 case 'String':
2895 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2896
2897 if (!empty($customDAO->option_group_id)) {
2898 if (in_array($customDAO->html_type, array(
2899 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2900 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
2901 }
2902 else {
2903 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
2904 }
2905 if ($this->_customGroupFilters) {
2906 $curFilters[$fieldName]['options'] = array();
2907 $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')));
2908 while ($ogDAO->fetch()) {
2909 $curFilters[$fieldName]['options'][$ogDAO->value] = $ogDAO->label;
2910 }
2911 }
2912 }
2913 break;
2914
2915 case 'StateProvince':
2916 if (in_array($customDAO->html_type, array(
2917 'Multi-Select State/Province'))) {
2918 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
2919 }
2920 else {
2921 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
2922 }
2923 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::stateProvince();
2924 break;
2925
2926 case 'Country':
2927 if (in_array($customDAO->html_type, array(
2928 'Multi-Select Country'))) {
2929 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
2930 }
2931 else {
2932 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
2933 }
2934 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::country();
2935 break;
2936
2937 case 'ContactReference':
2938 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2939 $curFilters[$fieldName]['name'] = 'display_name';
2940 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2941
2942 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2943 $curFields[$fieldName]['name'] = 'display_name';
2944 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2945 break;
2946
2947 default:
2948 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2949 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2950 }
2951
2952 if (!array_key_exists('type', $curFields[$fieldName])) {
fc161185 2953 $curFields[$fieldName]['type'] = CRM_Utils_Array::value('type', $curFilters[$fieldName], array());
6a488035
TO
2954 }
2955
2956 if ($addFields) {
2957 $this->_columns[$curTable]['fields'] = array_merge($this->_columns[$curTable]['fields'], $curFields);
2958 }
2959 if ($this->_customGroupFilters) {
2960 $this->_columns[$curTable]['filters'] = array_merge($this->_columns[$curTable]['filters'], $curFilters);
2961 }
2962 if ($this->_customGroupGroupBy) {
2963 $this->_columns[$curTable]['group_bys'] = array_merge($this->_columns[$curTable]['group_bys'], $curFields);
2964 }
2965 }
2966 }
2967
2968 function customDataFrom() {
2969 if (empty($this->_customGroupExtends)) {
2970 return;
2971 }
2972 $mapper = CRM_Core_BAO_CustomQuery::$extendsMap;
2973
2974 foreach ($this->_columns as $table => $prop) {
2975 if (substr($table, 0, 13) == 'civicrm_value' || substr($table, 0, 12) == 'custom_value') {
2976 $extendsTable = $mapper[$prop['extends']];
2977
2978 // check field is in params
2979 if (!$this->isFieldSelected($prop)) {
2980 continue;
2981 }
4c9d78ea 2982 $baseJoin = CRM_Utils_Array::value($prop['extends'], $this->_customGroupExtendsJoin, "{$this->_aliases[$extendsTable]}.id");
6a488035 2983
7a8b61ab 2984 $customJoin = is_array($this->_customGroupJoin) ? $this->_customGroupJoin[$table] : $this->_customGroupJoin;
6a488035 2985 $this->_from .= "
aa1aa08e 2986{$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
6a488035
TO
2987 // handle for ContactReference
2988 if (array_key_exists('fields', $prop)) {
2989 foreach ($prop['fields'] as $fieldName => $field) {
2990 if (CRM_Utils_Array::value('dataType', $field) == 'ContactReference') {
2991 $columnName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField::getKeyID($fieldName), 'column_name');
2992 $this->_from .= "
2993LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2994 }
2995 }
2996 }
2997 }
2998 }
2999 }
3000
3001 function isFieldSelected($prop) {
3002 if (empty($prop)) {
3003 return FALSE;
3004 }
3005
3006 if (!empty($this->_params['fields'])) {
3007 foreach (array_keys($prop['fields']) as $fieldAlias) {
3008 $customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias);
3009 if ($customFieldId) {
3010 if (array_key_exists($fieldAlias, $this->_params['fields'])) {
3011 return TRUE;
3012 }
3013
3014 //might be survey response field.
3015 if (CRM_Utils_Array::value('survey_response', $this->_params['fields']) &&
3016 CRM_Utils_Array::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
3017 ) {
3018 return TRUE;
3019 }
3020 }
3021 }
3022 }
3023
3024 if (!empty($this->_params['group_bys']) && $this->_customGroupGroupBy) {
3025 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3026 if (array_key_exists($fieldAlias, $this->_params['group_bys']) && CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
3027 return TRUE;
3028 }
3029 }
3030 }
3031
3032 if (!empty($this->_params['order_bys'])) {
3033 foreach (array_keys($prop['fields']) as $fieldAlias) {
3034 foreach ($this->_params['order_bys'] as $orderBy) {
3035 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
3036 return TRUE;
3037 }
3038 }
3039 }
3040 }
3041
3042 if (!empty($prop['filters']) && $this->_customGroupFilters) {
3043 foreach ($prop['filters'] as $fieldAlias => $val) {
3044 foreach (array(
3045 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3046 if (isset($this->_params[$fieldAlias . '_' . $attach]) &&
dfe4b2f5 3047 (!empty($this->_params[$fieldAlias . '_' . $attach])
3048 || ($attach != 'relative' && $this->_params[$fieldAlias . '_' . $attach] == '0')
3049 )
3050 ){
6a488035
TO
3051 return TRUE;
3052 }
3053 }
3054 if (CRM_Utils_Array::value($fieldAlias . '_op', $this->_params) &&
3055 in_array($this->_params[$fieldAlias . '_op'], array('nll', 'nnll'))
3056 ) {
3057 return TRUE;
3058 }
3059 }
3060 }
3061
3062 return FALSE;
3063 }
3064
3065 /**
3066 * Check for empty order_by configurations and remove them; also set
3067 * template to hide them.
3068 */
3069 function preProcessOrderBy(&$formValues) {
3070 // Object to show/hide form elements
ae555e90 3071 $_showHide = new CRM_Core_ShowHideBlocks('', '');
6a488035
TO
3072
3073 $_showHide->addShow('optionField_1');
3074
3075 // Cycle through order_by options; skip any empty ones, and hide them as well
3076 $n = 1;
3077
3078 if (!empty($formValues['order_bys'])) {
3079 foreach ($formValues['order_bys'] as $order_by) {
3080 if ($order_by['column'] && $order_by['column'] != '-') {
3081 $_showHide->addShow('optionField_' . $n);
3082 $orderBys[$n] = $order_by;
3083 $n++;
3084 }
3085 }
3086 }
3087 for ($i = $n; $i <= 5; $i++) {
3088 if ($i > 1) {
3089 $_showHide->addHide('optionField_' . $i);
3090 }
3091 }
3092
3093 // overwrite order_by options with modified values
3094 if (!empty($orderBys)) {
3095 $formValues['order_bys'] = $orderBys;
3096 }
3097 else {
3098 $formValues['order_bys'] = array(1 => array('column' => '-'));
3099 }
3100
3101 // assign show/hide data to template
3102 $_showHide->addToTemplate();
3103 }
3104
3105 /**
3106 * Does table name have columns in SELECT clause?
3107 *
3108 * @param string $tableName Name of table (index of $this->_columns array)
3109 *
3110 * @return bool
3111 */
3112 function isTableSelected($tableName) {
3113 return in_array($tableName, $this->selectedTables());
3114 }
3115
3116 /**
3117 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3118 * (building the array if it's unset)
3119 *
3120 * @return Array $this->_selectedTables
3121 */
3122 function selectedTables() {
3123 if (!$this->_selectedTables) {
3124 $orderByColumns = array();
7a8b61ab 3125 if (array_key_exists('order_bys', $this->_params) && is_array($this->_params['order_bys'])) {
6a488035
TO
3126 foreach ($this->_params['order_bys'] as $orderBy) {
3127 $orderByColumns[] = $orderBy['column'];
3128 }
3129 }
3130
3131 foreach ($this->_columns as $tableName => $table) {
3132 if (array_key_exists('fields', $table)) {
3133 foreach ($table['fields'] as $fieldName => $field) {
3134 if (CRM_Utils_Array::value('required', $field) ||
3135 CRM_Utils_Array::value($fieldName, $this->_params['fields'])
3136 ) {
3137 $this->_selectedTables[] = $tableName;
3138 break;
3139 }
3140 }
3141 }
3142 if (array_key_exists('order_bys', $table)) {
3143 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3144 if (in_array($orderByName, $orderByColumns)) {
3145 $this->_selectedTables[] = $tableName;
3146 break;
3147 }
3148 }
3149 }
3150 if (array_key_exists('filters', $table)) {
3151 foreach ($table['filters'] as $filterName => $filter) {
3152 if (CRM_Utils_Array::value("{$filterName}_value", $this->_params) ||
3153 CRM_Utils_Array::value("{$filterName}_op", $this->_params) == 'nll' ||
3154 CRM_Utils_Array::value("{$filterName}_op", $this->_params) == 'nnll'
3155 ) {
3156 $this->_selectedTables[] = $tableName;
3157 break;
3158 }
3159 }
3160 }
3161 }
3162 }
3163 return $this->_selectedTables;
3164 }
3165
850e4640
E
3166 /**
3167 * @deprecated - use getAddressColumns which is a more accurate description
3168 * and also accepts an array of options rather than a long list
3169 *
6a488035
TO
3170 * function for adding address fields to construct function in reports
3171 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3172 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3173 * @return array address fields for construct clause
3174 */
3175 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3176 'country_id' => TRUE)) {
3177 $addressFields = array(
3178 'civicrm_address' =>
3179 array(
3180 'dao' => 'CRM_Core_DAO_Address',
3181 'fields' =>
3182 array(
3183 'name' =>
3184 array('title' => ts('Address Name'),
3185 'default' => CRM_Utils_Array::value('name', $defaults, FALSE),
3186 ),
3187 'street_address' =>
3188 array('title' => ts('Street Address'),
3189 'default' => CRM_Utils_Array::value('street_address', $defaults, FALSE),
3190 ),
3191 'supplemental_address_1' =>
3192 array('title' => ts('Supplementary Address Field 1'),
3193 'default' => CRM_Utils_Array::value('supplemental_address_1', $defaults, FALSE),
3194 ),
3195 'supplemental_address_2' =>
3196 array('title' => ts('Supplementary Address Field 2'),
3197 'default' => CRM_Utils_Array::value('supplemental_address_2', $defaults, FALSE),
3198 ),
3199 'street_number' =>
3200 array(
3201 'name' => 'street_number',
3202 'title' => ts('Street Number'),
3203 'type' => 1,
3204 'default' => CRM_Utils_Array::value('street_number', $defaults, FALSE),
3205 ),
3206 'street_name' =>
3207 array(
3208 'name' => 'street_name',
3209 'title' => ts('Street Name'),
3210 'type' => 1,
3211 'default' => CRM_Utils_Array::value('street_name', $defaults, FALSE),
3212 ),
3213 'street_unit' =>
3214 array(
3215 'name' => 'street_unit',
3216 'title' => ts('Street Unit'),
3217 'type' => 1,
3218 'default' => CRM_Utils_Array::value('street_unit', $defaults, FALSE),
3219 ),
3220 'city' =>
3221 array('title' => ts('City'),
3222 'default' => CRM_Utils_Array::value('city', $defaults, FALSE),
3223 ),
3224 'postal_code' =>
3225 array('title' => ts('Postal Code'),
3226 'default' => CRM_Utils_Array::value('postal_code', $defaults, FALSE),
4cbdd2b1
JL
3227 ),
3228 'postal_code_suffix' =>
3229 array('title' => ts('Postal Code Suffix'),
3230 'default' => CRM_Utils_Array::value('postal_code_suffix', $defaults, FALSE),
6a488035
TO
3231 ),
3232 'county_id' =>
3233 array('title' => ts('County'),
3234 'default' => CRM_Utils_Array::value('county_id', $defaults, FALSE),
3235 ),
3236 'state_province_id' =>
3237 array('title' => ts('State/Province'),
3238 'default' => CRM_Utils_Array::value('state_province_id', $defaults, FALSE),
3239 ),
3240 'country_id' =>
3241 array('title' => ts('Country'),
3242 'default' => CRM_Utils_Array::value('country_id', $defaults, FALSE),
3243 ),
3244 ),
3245 'grouping' => 'location-fields',
3246 ),
3247 );
3248
3249 if ($filters) {
3250 $addressFields['civicrm_address']['filters'] = array(
3251 'street_number' => array('title' => ts('Street Number'),
3252 'type' => 1,
3253 'name' => 'street_number',
3254 ),
3255 'street_name' => array('title' => ts('Street Name'),
3256 'name' => 'street_name',
3257 'operator' => 'like',
3258 ),
3259 'postal_code' => array('title' => ts('Postal Code'),
3260 'type' => 1,
3261 'name' => 'postal_code',
3262 ),
3263 'city' => array('title' => ts('City'),
3264 'operator' => 'like',
3265 'name' => 'city',
3266 ),
3267 'county_id' => array(
3268 'name' => 'county_id',
3269 'title' => ts('County'),
3270 'type' => CRM_Utils_Type::T_INT,
3271 'operatorType' =>
3272 CRM_Report_Form::OP_MULTISELECT,
3273 'options' =>
3274 CRM_Core_PseudoConstant::county(),
3275 ),
3276 'state_province_id' => array(
3277 'name' => 'state_province_id',
3278 'title' => ts('State/Province'),
3279 'type' => CRM_Utils_Type::T_INT,
3280 'operatorType' =>
3281 CRM_Report_Form::OP_MULTISELECT,
3282 'options' =>
3283 CRM_Core_PseudoConstant::stateProvince(),
3284 ),
3285 'country_id' => array(
3286 'name' => 'country_id',
3287 'title' => ts('Country'),
3288 'type' => CRM_Utils_Type::T_INT,
3289 'operatorType' =>
3290 CRM_Report_Form::OP_MULTISELECT,
3291 'options' =>
3292 CRM_Core_PseudoConstant::country(),
3293 ),
3294 );
3295 }
3296
3297 if ($orderBy) {
3298 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3299 'street_number' => array('title' => 'Odd / Even Street Number'),
3300 'street_address' => NULL,
3301 'city' => NULL,
3302 'postal_code' => NULL,
3303 );
3304 }
3305
3306 if ($groupBy) {
3307 $addressFields['civicrm_address']['group_bys'] = array(
3308 'street_address' => NULL,
3309 'city' => NULL,
3310 'postal_code' => NULL,
3311 'state_province_id' =>
3312 array('title' => ts('State/Province'),
3313 ),
3314 'country_id' =>
3315 array('title' => ts('Country'),
3316 ),
3317 'county_id' =>
3318 array('title' => ts('County'),
3319 ),
3320 );
3321 }
3322 return $addressFields;
3323 }
3324
3325 /*
3326 * Do AlterDisplay processing on Address Fields
3327 */
3328 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3329 $criteriaQueryParams = CRM_Report_Utils_Report::getPreviewCriteriaQueryParams($this->_defaults, $this->_params);
3330 $entryFound = FALSE;
3331 // handle country
3332 if (array_key_exists('civicrm_address_country_id', $row)) {
3333 if ($value = $row['civicrm_address_country_id']) {
3334 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
3335 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
3336 "reset=1&force=1&{$criteriaQueryParams}&" .
3337 "country_id_op=in&country_id_value={$value}",
3338 $this->_absoluteUrl, $this->_id
3339 );
3340 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3341 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3342 array(1 => $urltxt)
3343 );
3344 }
3345
3346 $entryFound = TRUE;
3347 }
3348 if (array_key_exists('civicrm_address_county_id', $row)) {
3349 if ($value = $row['civicrm_address_county_id']) {
3350 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant::county($value, FALSE);
3351 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
3352 "reset=1&force=1&{$criteriaQueryParams}&" .
3353 "county_id_op=in&county_id_value={$value}",
3354 $this->_absoluteUrl, $this->_id
3355 );
3356 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3357 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3358 array(1 => $urltxt)
3359 );
3360 }
3361 $entryFound = TRUE;
3362 }
3363 // handle state province
3364 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3365 if ($value = $row['civicrm_address_state_province_id']) {
3366 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
3367
3368 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
3369 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3370 $this->_absoluteUrl, $this->_id
3371 );
3372 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3373 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3374 array(1 => $urltxt)
3375 );
3376 }
3377 $entryFound = TRUE;
3378 }
3379
3380 return $entryFound;
3381 }
3382
3383 /*
3384 * Adjusts dates passed in to YEAR() for fiscal year.
3385 */
3386 function fiscalYearOffset($fieldName) {
3387 $config = CRM_Core_Config::singleton();
3388 $fy = $config->fiscalYearStart;
3389 if (CRM_Utils_Array::value('yid_op', $this->_params) == 'calendar' || ($fy['d'] == 1 && $fy['M'] == 1)) {
3390 return "YEAR( $fieldName )";
3391 }
3392 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ? (" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3393 }
3394
3395 /*
3396 * Add Address into From Table if required
3397 */
3398 function addAddressFromClause() {
3399 // include address field if address column is to be included
3400 if ((isset($this->_addressField) &&
3401 $this->_addressField
3402 ) ||
3403 $this->isTableSelected('civicrm_address')
3404 ) {
3405 $this->_from .= "
3406 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3407 ON ({$this->_aliases['civicrm_contact']}.id =
3408 {$this->_aliases['civicrm_address']}.contact_id) AND
3409 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3410 }
3411 }
3412
850e4640
E
3413 /**
3414 * Add Phone into From Table if required
3415 */
3416 function addPhoneFromClause() {
3417 // include address field if address column is to be included
3418 if ($this->isTableSelected('civicrm_phone')
3419 ) {
3420 $this->_from .= "
3421 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3422 ON ({$this->_aliases['civicrm_contact']}.id =
3423 {$this->_aliases['civicrm_phone']}.contact_id) AND
3424 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3425 }
3426 }
3427
3428 /**
3429 * Get phone columns to add to array
3430 * @param array $options
3431 * - prefix Prefix to add to table (in case of more than one instance of the table)
3432 * - prefix_label Label to give columns from this phone table instance
3433 * @return array phone columns definition
3434 */
3435 function getPhoneColumns($options = array()){
3436 $defaultOptions = array(
3437 'prefix' => '',
3438 'prefix_label' => '',
3439 );
3440
3441 $options = array_merge($defaultOptions,$options);
3442
3443 $fields = array(
3444 $options['prefix'] . 'civicrm_phone' => array(
3445 'dao' => 'CRM_Core_DAO_Phone',
3446 'fields' => array(
3447 $options['prefix'] . 'phone' => array(
3448 'title' => ts($options['prefix_label'] . 'Phone'),
3449 'name' => 'phone'
3450 ),
3451 ),
3452 ),
3453 );
3454 return $fields;
3455 }
3456
3457 /**
3458 * Get address columns to add to array
3459 * @param array $options
3460 * - prefix Prefix to add to table (in case of more than one instance of the table)
3461 * - prefix_label Label to give columns from this address table instance
3462 * @return array address columns definition
3463 */
3464 function getAddressColumns($options = array()){
3465 $defaultOptions = array(
3466 'prefix' => '',
3467 'prefix_label' => '',
3468 'group_by' => TRUE,
3469 'order_by' => TRUE,
3470 'filters' => TRUE,
3471 'defaults' => array(
3472 ),
3473 );
3474 $options = array_merge($defaultOptions,$options);
3475 return $this->addAddressFields(
3476 $options['group_by'],
3477 $options['order_by'],
3478 $options['filters'],
3479 $options['defaults']
3480 );
3481
3482 }
3483
6a488035
TO
3484 function add2group($groupID) {
3485 if (is_numeric($groupID) && isset($this->_aliases['civicrm_contact'])) {
3486 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3487 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select);
3488
3489 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3490 $dao = CRM_Core_DAO::executeQuery($sql);
3491
3492 $contact_ids = array();
3493 // Add resulting contacts to group
3494 while ($dao->fetch()) {
3495 if ($dao->addtogroup_contact_id) {
3496 $contact_ids[$dao->addtogroup_contact_id] = $dao->addtogroup_contact_id;
3497 }
3498 }
3499
3500 if ( !empty($contact_ids) ) {
3501 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
3502 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3503 }
3504 else {
3505 CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
3506 }
3507 }
3508 }
46065582
PJ
3509
3510 /* function used for showing charts on print screen */
3511 static function uploadChartImage() {
3512 // upload strictly for '.png' images
d04d4eef
PJ
3513 $name = trim(basename(CRM_Utils_Request::retrieve('name', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET')));
3514 if (preg_match('/\.png$/', $name)) {
46065582
PJ
3515 //
3516 // POST data is usually string data, but we are passing a RAW .png
3517 // so PHP is a bit confused and $_POST is empty. But it has saved
3518 // the raw bits into $HTTP_RAW_POST_DATA
3519 //
3520 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3521
3522 // prepare the directory
3523 $config = CRM_Core_Config::singleton();
3524 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir) . '/openFlashChart/';
3525 if (!file_exists($defaultPath)) {
3526 mkdir($defaultPath, 0777, TRUE);
3527 }
3528
3529 // full path to the saved image including filename
d04d4eef 3530 $destination = $defaultPath . $name;
46065582
PJ
3531
3532 //write and save
3533 $jfh = fopen($destination, 'w') or die("can't open file");
3534 fwrite($jfh, $httpRawPostData);
3535 fclose($jfh);
3536 CRM_Utils_System::civiExit();
3537 }
3538 }
232624b1 3539}