Merge pull request #2390 from dlobo/CRM-14085
[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 }
381
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"));
5895cba0 1046 $this->addElement('checkbox', "order_bys[{$i}][pageBreak]", ts('Page Break'), FALSE, array('id' => "order_by_pagebreak_$i"));
6a488035
TO
1047 }
1048 }
1049 }
1050
1051 function buildInstanceAndButtons() {
1052 CRM_Report_Form_Instance::buildForm($this);
1053
1054 $label = $this->_id ? ts('Update Report') : ts('Create Report');
1055
1056 $this->addElement('submit', $this->_instanceButtonName, $label);
1057 $this->addElement('submit', $this->_printButtonName, ts('Print Report'));
1058 $this->addElement('submit', $this->_pdfButtonName, ts('PDF'));
1059
1060 if ($this->_id) {
1061 $this->addElement('submit', $this->_createNewButtonName, ts('Save a Copy') . '...');
1062 }
1063 if ($this->_instanceForm) {
1064 $this->assign('instanceForm', TRUE);
1065 }
1066
1067 $label = $this->_id ? ts('Print Report') : ts('Print Preview');
1068 $this->addElement('submit', $this->_printButtonName, $label);
1069
1070 $label = $this->_id ? ts('PDF') : ts('Preview PDF');
1071 $this->addElement('submit', $this->_pdfButtonName, $label);
1072
1073 $label = $this->_id ? ts('Export to CSV') : ts('Preview CSV');
1074
1075 if ($this->_csvSupported) {
1076 $this->addElement('submit', $this->_csvButtonName, $label);
1077 }
1078
1079 if (CRM_Core_Permission::check('administer Reports') && $this->_add2groupSupported) {
1080 $this->addElement('select', 'groups', ts('Group'),
1081 array('' => ts('- select group -')) + CRM_Core_PseudoConstant::staticGroup()
1082 );
1083 $this->assign('group', TRUE);
1084 }
1085
58175fe6 1086 $label = ts('Add These Contacts to Group');
6a488035
TO
1087 $this->addElement('submit', $this->_groupButtonName, $label, array('onclick' => 'return checkGroup();'));
1088
1089 $this->addChartOptions();
1090 $this->addButtons(array(
1091 array(
1092 'type' => 'submit',
1093 'name' => ts('Preview Report'),
1094 'isDefault' => TRUE,
1095 ),
1096 )
1097 );
1098 }
1099
1100 function buildQuickForm() {
1101 $this->addColumns();
1102
1103 $this->addFilters();
1104
1105 $this->addOptions();
1106
1107 $this->addGroupBys();
1108
1109 $this->addOrderBys();
1110
1111 $this->buildInstanceAndButtons();
1112
1113 //add form rule for report
1114 if (is_callable(array(
1115 $this, 'formRule'))) {
1116 $this->addFormRule(array(get_class($this), 'formRule'), $this);
1117 }
1118 }
1119
1120 // a formrule function to ensure that fields selected in group_by
1121 // (if any) should only be the ones present in display/select fields criteria;
1122 // note: works if and only if any custom field selected in group_by.
1123 function customDataFormRule($fields, $ignoreFields = array( )) {
1124 $errors = array();
1125 if (!empty($this->_customGroupExtends) && $this->_customGroupGroupBy && !empty($fields['group_bys'])) {
1126 foreach ($this->_columns as $tableName => $table) {
1127 if ((substr($tableName, 0, 13) == 'civicrm_value' || substr($tableName, 0, 12) == 'custom_value') && !empty($this->_columns[$tableName]['fields'])) {
1128 foreach ($this->_columns[$tableName]['fields'] as $fieldName => $field) {
1129 if (array_key_exists($fieldName, $fields['group_bys']) &&
1130 !array_key_exists($fieldName, $fields['fields'])
1131 ) {
1132 $errors['fields'] = "Please make sure fields selected in 'Group by Columns' section are also selected in 'Display Columns' section.";
1133 }
1134 elseif (array_key_exists($fieldName, $fields['group_bys'])) {
1135 foreach ($fields['fields'] as $fld => $val) {
1136 if (!array_key_exists($fld, $fields['group_bys']) && !in_array($fld, $ignoreFields)) {
1137 $errors['fields'] = "Please ensure that fields selected in 'Display Columns' are also selected in 'Group by Columns' section.";
1138 }
1139 }
1140 }
1141 }
1142 }
1143 }
1144 }
1145 return $errors;
1146 }
1147
1148 // Note: $fieldName param allows inheriting class to build operationPairs
1149 // specific to a field.
1b36206c 1150 function getOperationPair($type = "string", $fieldName = NULL) {
6a488035
TO
1151 // FIXME: At some point we should move these key-val pairs
1152 // to option_group and option_value table.
6a488035 1153 switch ($type) {
160d32e1
E
1154 case CRM_Report_Form::OP_INT:
1155 case CRM_Report_Form::OP_FLOAT:
bc3f7f04 1156 return array(
1157 'lte' => ts('Is less than or equal to'),
6a488035
TO
1158 'gte' => ts('Is greater than or equal to'),
1159 'bw' => ts('Is between'),
1160 'eq' => ts('Is equal to'),
1161 'lt' => ts('Is less than'),
1162 'gt' => ts('Is greater than'),
1163 'neq' => ts('Is not equal to'),
1164 'nbw' => ts('Is not between'),
1165 'nll' => ts('Is empty (Null)'),
1166 'nnll' => ts('Is not empty (Null)'),
1167 );
1168 break;
1169
160d32e1 1170 case CRM_Report_Form::OP_SELECT:
bc3f7f04 1171 return array(
1172 'eq' => ts('Is equal to'),
1173 );
6a488035 1174
160d32e1
E
1175 case CRM_Report_Form::OP_MONTH:
1176 case CRM_Report_Form::OP_MULTISELECT:
bc3f7f04 1177 return array(
1178 'in' => ts('Is one of'),
6a488035
TO
1179 'notin' => ts('Is not one of'),
1180 );
1181 break;
1182
160d32e1 1183 case CRM_Report_Form::OP_DATE:
bc3f7f04 1184 return array(
1185 'nll' => ts('Is empty (Null)'),
6a488035
TO
1186 'nnll' => ts('Is not empty (Null)'),
1187 );
1188 break;
1189
160d32e1 1190 case CRM_Report_Form::OP_MULTISELECT_SEPARATOR:
6a488035
TO
1191 // use this operator for the values, concatenated with separator. For e.g if
1192 // multiple options for a column is stored as ^A{val1}^A{val2}^A
bc3f7f04 1193 return array(
1194 'mhas' => ts('Is one of'),
1195 );
6a488035
TO
1196
1197 default:
1198 // type is string
bc3f7f04 1199 return array(
1200 'has' => ts('Contains'),
6a488035
TO
1201 'sw' => ts('Starts with'),
1202 'ew' => ts('Ends with'),
1203 'nhas' => ts('Does not contain'),
1204 'eq' => ts('Is equal to'),
1205 'neq' => ts('Is not equal to'),
1206 'nll' => ts('Is empty (Null)'),
1207 'nnll' => ts('Is not empty (Null)'),
1208 );
1209 }
1210 }
1211
1212 function buildTagFilter() {
1213 $contactTags = CRM_Core_BAO_Tag::getTags();
1214 if (!empty($contactTags)) {
1215 $this->_columns['civicrm_tag'] = array(
1216 'dao' => 'CRM_Core_DAO_Tag',
1217 'filters' =>
1218 array(
1219 'tagid' =>
1220 array(
1221 'name' => 'tag_id',
1222 'title' => ts('Tag'),
1223 'tag' => TRUE,
1224 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
1225 'options' => $contactTags,
1226 ),
1227 ),
1228 );
1229 }
1230 }
1231
1232 /*
1233 * Adds group filters to _columns (called from _Constuct
1234 */
1235 function buildGroupFilter() {
1236 $this->_columns['civicrm_group']['filters'] = array(
1237 'gid' =>
1238 array(
1239 'name' => 'group_id',
1240 'title' => ts('Group'),
1241 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
1242 'group' => TRUE,
1243 'options' => CRM_Core_PseudoConstant::group(),
1244 ),
1245 );
1246 if (empty($this->_columns['civicrm_group']['dao'])) {
1247 $this->_columns['civicrm_group']['dao'] = 'CRM_Contact_DAO_GroupContact';
1248 }
1249 if (empty($this->_columns['civicrm_group']['alias'])) {
1250 $this->_columns['civicrm_group']['alias'] = 'cgroup';
1251 }
1252 }
1253
29fc2b79 1254 function getSQLOperator($operator = "like") {
6a488035
TO
1255 switch ($operator) {
1256 case 'eq':
1257 return '=';
1258
1259 case 'lt':
1260 return '<';
1261
1262 case 'lte':
1263 return '<=';
1264
1265 case 'gt':
1266 return '>';
1267
1268 case 'gte':
1269 return '>=';
1270
1271 case 'ne':
1272 case 'neq':
1273 return '!=';
1274
1275 case 'nhas':
1276 return 'NOT LIKE';
1277
1278 case 'in':
1279 return 'IN';
1280
1281 case 'notin':
1282 return 'NOT IN';
1283
1284 case 'nll':
1285 return 'IS NULL';
1286
1287 case 'nnll':
1288 return 'IS NOT NULL';
1289
1290 default:
1291 // type is string
1292 return 'LIKE';
1293 }
1294 }
1295
1296 function whereClause(&$field, $op,
1297 $value, $min, $max
1298 ) {
1299
1300 $type = CRM_Utils_Type::typeToString(CRM_Utils_Array::value('type', $field));
1301 $clause = NULL;
1302
1303 switch ($op) {
1304 case 'bw':
1305 case 'nbw':
1306 if (($min !== NULL && strlen($min) > 0) ||
1307 ($max !== NULL && strlen($max) > 0)
1308 ) {
1309 $min = CRM_Utils_Type::escape($min, $type);
1310 $max = CRM_Utils_Type::escape($max, $type);
1311 $clauses = array();
1312 if ($min) {
1313 if ($op == 'bw') {
1314 $clauses[] = "( {$field['dbAlias']} >= $min )";
1315 }
1316 else {
1317 $clauses[] = "( {$field['dbAlias']} < $min )";
1318 }
1319 }
1320 if ($max) {
1321 if ($op == 'bw') {
1322 $clauses[] = "( {$field['dbAlias']} <= $max )";
1323 }
1324 else {
1325 $clauses[] = "( {$field['dbAlias']} > $max )";
1326 }
1327 }
1328
1329 if (!empty($clauses)) {
1330 if ($op == 'bw') {
1331 $clause = implode(' AND ', $clauses);
1332 }
1333 else {
1334 $clause = implode(' OR ', $clauses);
1335 }
1336 }
1337 }
1338 break;
1339
1340 case 'has':
1341 case 'nhas':
1342 if ($value !== NULL && strlen($value) > 0) {
1343 $value = CRM_Utils_Type::escape($value, $type);
1344 if (strpos($value, '%') === FALSE) {
1345 $value = "'%{$value}%'";
1346 }
1347 else {
1348 $value = "'{$value}'";
1349 }
29fc2b79 1350 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1351 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1352 }
1353 break;
1354
1355 case 'in':
1356 case 'notin':
1357 if ($value !== NULL && is_array($value) && count($value) > 0) {
29fc2b79 1358 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1359 if (CRM_Utils_Array::value('type', $field) == CRM_Utils_Type::T_STRING) {
1360 //cycle through selections and esacape values
1361 foreach ($value as $key => $selection) {
1362 $value[$key] = CRM_Utils_Type::escape($selection, $type);
1363 }
1364 $clause = "( {$field['dbAlias']} $sqlOP ( '" . implode("' , '", $value) . "') )";
1365 }
1366 else {
1367 // for numerical values
1368 $clause = "{$field['dbAlias']} $sqlOP (" . implode(', ', $value) . ")";
1369 }
1370 if ($op == 'notin') {
1371 $clause = "( " . $clause . " OR {$field['dbAlias']} IS NULL )";
1372 }
1373 else {
1374 $clause = "( " . $clause . " )";
1375 }
1376 }
1377 break;
1378
1379 case 'mhas':
1380 // mhas == multiple has
1381 if ($value !== NULL && count($value) > 0) {
29fc2b79 1382 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1383 $clause = "{$field['dbAlias']} REGEXP '[[:<:]]" . implode('|', $value) . "[[:>:]]'";
1384 }
1385 break;
1386
1387 case 'sw':
1388 case 'ew':
1389 if ($value !== NULL && strlen($value) > 0) {
1390 $value = CRM_Utils_Type::escape($value, $type);
1391 if (strpos($value, '%') === FALSE) {
1392 if ($op == 'sw') {
1393 $value = "'{$value}%'";
1394 }
1395 else {
1396 $value = "'%{$value}'";
1397 }
1398 }
1399 else {
1400 $value = "'{$value}'";
1401 }
29fc2b79 1402 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1403 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1404 }
1405 break;
1406
1407 case 'nll':
1408 case 'nnll':
29fc2b79 1409 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1410 $clause = "( {$field['dbAlias']} $sqlOP )";
1411 break;
1412
1413 default:
1414 if ($value !== NULL && strlen($value) > 0) {
1415 if (isset($field['clause'])) {
1416 // FIXME: we not doing escape here. Better solution is to use two
1417 // different types - data-type and filter-type
0e6e8724 1418 $clause = $field['clause'];
6a488035
TO
1419 }
1420 else {
1421 $value = CRM_Utils_Type::escape($value, $type);
29fc2b79 1422 $sqlOP = $this->getSQLOperator($op);
6a488035
TO
1423 if ($field['type'] == CRM_Utils_Type::T_STRING) {
1424 $value = "'{$value}'";
1425 }
1426 $clause = "( {$field['dbAlias']} $sqlOP $value )";
1427 }
1428 }
1429 break;
1430 }
1431
1432 if (CRM_Utils_Array::value('group', $field) && $clause) {
1433 $clause = $this->whereGroupClause($field, $value, $op);
1434 }
1435 elseif (CRM_Utils_Array::value('tag', $field) && $clause) {
1436 // not using left join in query because if any contact
1437 // belongs to more than one tag, results duplicate
1438 // entries.
1439 $clause = $this->whereTagClause($field, $value, $op);
1440 }
1441
1442 return $clause;
1443 }
1444
1445 function dateClause($fieldName,
1446 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1447 ) {
1448 $clauses = array();
160d32e1 1449 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form::OP_DATE)))) {
29fc2b79 1450 $sqlOP = $this->getSQLOperator($relative);
6a488035
TO
1451 return "( {$fieldName} {$sqlOP} )";
1452 }
1453
29fc2b79 1454 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
6a488035
TO
1455
1456 if ($from) {
1457 $from = ($type == CRM_Utils_Type::T_DATE) ? substr($from, 0, 8) : $from;
1458 $clauses[] = "( {$fieldName} >= $from )";
1459 }
1460
1461 if ($to) {
1462 $to = ($type == CRM_Utils_Type::T_DATE) ? substr($to, 0, 8) : $to;
1463 $clauses[] = "( {$fieldName} <= {$to} )";
1464 }
1465
1466 if (!empty($clauses)) {
1467 return implode(' AND ', $clauses);
1468 }
1469
1470 return NULL;
1471 }
29fc2b79 1472 /**
1473 * @todo - could not find any instances where this is called
1474 * @param unknown_type $relative
1475 * @param String $from
1476 * @param String_type $to
1477 * @return string|NULL
1478 */
1479 function dateDisplay($relative, $from, $to) {
1480 list($from, $to) = $this->getFromTo($relative, $from, $to);
6a488035
TO
1481
1482 if ($from) {
1483 $clauses[] = CRM_Utils_Date::customFormat($from, NULL, array('m', 'M'));
1484 }
1485 else {
1486 $clauses[] = 'Past';
1487 }
1488
1489 if ($to) {
1490 $clauses[] = CRM_Utils_Date::customFormat($to, NULL, array('m', 'M'));
1491 }
1492 else {
1493 $clauses[] = 'Today';
1494 }
1495
1496 if (!empty($clauses)) {
1497 return implode(' - ', $clauses);
1498 }
1499
1500 return NULL;
1501 }
1502
29fc2b79 1503 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
6a488035
TO
1504 if (empty($totime)) {
1505 $totime = '235959';
1506 }
1507 //FIX ME not working for relative
1508 if ($relative) {
1509 list($term, $unit) = CRM_Utils_System::explode('.', $relative, 2);
1510 $dateRange = CRM_Utils_Date::relativeToAbsolute($term, $unit);
1511 $from = substr($dateRange['from'], 0, 8);
1512 //Take only Date Part, Sometime Time part is also present in 'to'
1513 $to = substr($dateRange['to'], 0, 8);
1514 }
1515 $from = CRM_Utils_Date::processDate($from, $fromtime);
1516 $to = CRM_Utils_Date::processDate($to, $totime);
1517 return array($from, $to);
1518 }
1519
1520 function alterDisplay(&$rows) {
1521 // custom code to alter rows
1522 }
1523
1524 function alterCustomDataDisplay(&$rows) {
1525 // custom code to alter rows having custom values
1526 if (empty($this->_customGroupExtends)) {
1527 return;
1528 }
1529
1530 $customFieldIds = array();
1531 foreach ($this->_params['fields'] as $fieldAlias => $value) {
1532 if ($fieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
1533 $customFieldIds[$fieldAlias] = $fieldId;
1534 }
1535 }
1536 if (empty($customFieldIds)) {
1537 return;
1538 }
1539
1540 $customFields = $fieldValueMap = array();
1541 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1542
1543 // skip for type date and ContactReference since date format is already handled
1544 $query = "
1545SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1546FROM civicrm_custom_field cf
1547INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1548LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1549WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
1550 cg.is_active = 1 AND
1551 cf.is_active = 1 AND
1552 cf.is_searchable = 1 AND
1553 cf.data_type NOT IN ('ContactReference', 'Date') AND
1554 cf.id IN (" . implode(",", $customFieldIds) . ")";
1555
1556 $dao = CRM_Core_DAO::executeQuery($query);
1557 while ($dao->fetch()) {
1558 foreach ($customFieldCols as $key) {
1559 $customFields[$dao->table_name . '_custom_' . $dao->id][$key] = $dao->$key;
1560 }
1561 if ($dao->option_group_id) {
1562 $fieldValueMap[$dao->option_group_id][$dao->value] = $dao->label;
1563 }
1564 }
1565 $dao->free();
1566
1567 $entryFound = FALSE;
1568 foreach ($rows as $rowNum => $row) {
1569 foreach ($row as $tableCol => $val) {
1570 if (array_key_exists($tableCol, $customFields)) {
1571 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1572 $entryFound = TRUE;
1573 }
1574 }
1575
1576 // skip looking further in rows, if first row itself doesn't
1577 // have the column we need
1578 if (!$entryFound) {
1579 break;
1580 }
1581 }
1582 }
1583
1584 function formatCustomValues($value, $customField, $fieldValueMap) {
1585 if (CRM_Utils_System::isNull($value)) {
1586 return;
1587 }
1588
1589 $htmlType = $customField['html_type'];
1590
1591 switch ($customField['data_type']) {
1592 case 'Boolean':
1593 if ($value == '1') {
1594 $retValue = ts('Yes');
1595 }
1596 else {
1597 $retValue = ts('No');
1598 }
1599 break;
1600
1601 case 'Link':
1602 $retValue = CRM_Utils_System::formatWikiURL($value);
1603 break;
1604
1605 case 'File':
1606 $retValue = $value;
1607 break;
1608
1609 case 'Memo':
1610 $retValue = $value;
1611 break;
1612
1613 case 'Float':
1614 if ($htmlType == 'Text') {
1615 $retValue = (float)$value;
1616 break;
1617 }
1618 case 'Money':
1619 if ($htmlType == 'Text') {
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629 $retValue = CRM_Utils_Money::format($value, NULL, '%a');
1630 break;
1631 }
1632 case 'String':
1633 case 'Int':
1634 if (in_array($htmlType, array(
1635 'Text', 'TextArea'))) {
1636 $retValue = $value;
1637 break;
1638 }
1639 case 'StateProvince':
1640 case 'Country':
1641
1642 switch ($htmlType) {
1643 case 'Multi-Select Country':
1644 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1645 $customData = array();
1646 foreach ($value as $val) {
1647 if ($val) {
1648 $customData[] = CRM_Core_PseudoConstant::country($val, FALSE);
1649 }
1650 }
1651 $retValue = implode(', ', $customData);
1652 break;
1653
1654 case 'Select Country':
1655 $retValue = CRM_Core_PseudoConstant::country($value, FALSE);
1656 break;
1657
1658 case 'Select State/Province':
1659 $retValue = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
1660 break;
1661
1662 case 'Multi-Select State/Province':
1663 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1664 $customData = array();
1665 foreach ($value as $val) {
1666 if ($val) {
1667 $customData[] = CRM_Core_PseudoConstant::stateProvince($val, FALSE);
1668 }
1669 }
1670 $retValue = implode(', ', $customData);
1671 break;
1672
1673 case 'Select':
1674 case 'Radio':
1675 case 'Autocomplete-Select':
1676 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1677 break;
1678
1679 case 'CheckBox':
1680 case 'AdvMulti-Select':
1681 case 'Multi-Select':
1682 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1683 $customData = array();
1684 foreach ($value as $val) {
1685 if ($val) {
1686 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1687 }
1688 }
1689 $retValue = implode(', ', $customData);
1690 break;
1691
1692 default:
1693 $retValue = $value;
1694 }
1695 break;
1696
1697 default:
1698 $retValue = $value;
1699 }
1700
1701 return $retValue;
1702 }
1703
1704 function removeDuplicates(&$rows) {
1705 if (empty($this->_noRepeats)) {
1706 return;
1707 }
1708 $checkList = array();
1709
1710 foreach ($rows as $key => $list) {
1711 foreach ($list as $colName => $colVal) {
8f1445ea 1712 if (array_key_exists($colName, $checkList) &&
6a488035
TO
1713 $checkList[$colName] == $colVal) {
1714 $rows[$key][$colName] = "";
1715 }
1716 if (in_array($colName, $this->_noRepeats)) {
1717 $checkList[$colName] = $colVal;
1718 }
1719 }
1720 }
1721 }
1722
1723 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1724 foreach ($row as $colName => $colVal) {
1725 if (in_array($colName, $fields)) {
1726 $row[$colName] = $row[$colName];
1727 }
1728 elseif (isset($this->_columnHeaders[$colName])) {
1729 if ($subtotal) {
1730 $row[$colName] = "Subtotal";
1731 $subtotal = FALSE;
1732 }
1733 else {
1734 unset($row[$colName]);
1735 }
1736 }
1737 }
1738 }
1739
1740 function grandTotal(&$rows) {
1741 if (!$this->_rollup || ($this->_rollup == '') ||
1742 ($this->_limit && count($rows) >= self::ROW_COUNT_LIMIT)
1743 ) {
1744 return FALSE;
1745 }
1746 $lastRow = array_pop($rows);
1747
6a488035
TO
1748 foreach ($this->_columnHeaders as $fld => $val) {
1749 if (!in_array($fld, $this->_statFields)) {
1750 if (!$this->_grandFlag) {
1751 $lastRow[$fld] = "Grand Total";
1752 $this->_grandFlag = TRUE;
1753 }
1754 else {
1755 $lastRow[$fld] = "";
1756 }
1757 }
1758 }
1759
1760 $this->assign('grandStat', $lastRow);
1761 return TRUE;
1762 }
1763
1764 function formatDisplay(&$rows, $pager = TRUE) {
1765 // set pager based on if any limit was applied in the query.
1766 if ($pager) {
1767 $this->setPager();
1768 }
1769
1770 // allow building charts if any
1771 if (!empty($this->_params['charts']) && !empty($rows)) {
1772 $this->buildChart($rows);
1773 $this->assign('chartEnabled', TRUE);
1774 $this->_chartId = "{$this->_params['charts']}_" . ($this->_id ? $this->_id : substr(get_class($this), 16)) . '_' . session_id();
1775 $this->assign('chartId', $this->_chartId);
1776 }
1777
1778 // unset columns not to be displayed.
1779 foreach ($this->_columnHeaders as $key => $value) {
d4997a19 1780 if (CRM_Utils_Array::value('no_display', $value)) {
6a488035
TO
1781 unset($this->_columnHeaders[$key]);
1782 }
1783 }
1784
1785 // unset columns not to be displayed.
1786 if (!empty($rows)) {
1787 foreach ($this->_noDisplay as $noDisplayField) {
1788 foreach ($rows as $rowNum => $row) {
1789 unset($this->_columnHeaders[$noDisplayField]);
1790 }
1791 }
1792 }
1793
1794 // build array of section totals
1795 $this->sectionTotals();
1796
1797 // process grand-total row
1798 $this->grandTotal($rows);
1799
1800 // use this method for formatting rows for display purpose.
1801 $this->alterDisplay($rows);
1802 CRM_Utils_Hook::alterReportVar('rows', $rows, $this);
1803
1804 // use this method for formatting custom rows for display purpose.
1805 $this->alterCustomDataDisplay($rows);
1806 }
1807
1808 function buildChart(&$rows) {
1809 // override this method for building charts.
1810 }
1811
1812 // select() method below has been added recently (v3.3), and many of the report templates might
1813 // still be having their own select() method. We should fix them as and when encountered and move
1814 // towards generalizing the select() method below.
1815 function select() {
1f220d30 1816 $select = $this->_selectAliases = array();
6a488035
TO
1817
1818 foreach ($this->_columns as $tableName => $table) {
1819 if (array_key_exists('fields', $table)) {
1820 foreach ($table['fields'] as $fieldName => $field) {
1821 if ($tableName == 'civicrm_address') {
1822 $this->_addressField = TRUE;
1823 }
1824 if ($tableName == 'civicrm_email') {
1825 $this->_emailField = TRUE;
1826 }
1827 if ($tableName == 'civicrm_phone') {
1828 $this->_phoneField = TRUE;
1829 }
1830
1831 if (CRM_Utils_Array::value('required', $field) ||
1832 CRM_Utils_Array::value($fieldName, $this->_params['fields'])
1833 ) {
1834
1835 // 1. In many cases we want select clause to be built in slightly different way
1836 // for a particular field of a particular type.
1837 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1838 // as needed.
1839 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1840 if ($selectClause) {
1841 $select[] = $selectClause;
1842 continue;
1843 }
1844
1845 // include statistics columns only if set
1846 if (CRM_Utils_Array::value('statistics', $field)) {
1847 foreach ($field['statistics'] as $stat => $label) {
1848 $alias = "{$tableName}_{$fieldName}_{$stat}";
1849 switch (strtolower($stat)) {
1850 case 'max':
1851 case 'sum':
1852 $select[] = "$stat({$field['dbAlias']}) as $alias";
1853 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1854 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
9e6d7767 1855 $this->_statFields[$label] = $alias;
6a488035
TO
1856 $this->_selectAliases[] = $alias;
1857 break;
1858
1859 case 'count':
1860 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1861 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1862 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
9e6d7767 1863 $this->_statFields[$label] = $alias;
6a488035
TO
1864 $this->_selectAliases[] = $alias;
1865 break;
1866
1bfaf6a6
DS
1867 case 'count_distinct':
1868 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1869 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1870 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
1871 $this->_statFields[$label] = $alias;
1872 $this->_selectAliases[] = $alias;
1873 break;
1874
6a488035
TO
1875 case 'avg':
1876 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1877 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1878 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
9e6d7767 1879 $this->_statFields[$label] = $alias;
6a488035
TO
1880 $this->_selectAliases[] = $alias;
1881 break;
1882 }
1883 }
1884 }
1885 else {
1886 $alias = "{$tableName}_{$fieldName}";
1887 $select[] = "{$field['dbAlias']} as $alias";
1888 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
1889 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
1890 $this->_selectAliases[] = $alias;
1891 }
1892 }
1893 }
1894 }
1895
1896 // select for group bys
1897 if (array_key_exists('group_bys', $table)) {
1898 foreach ($table['group_bys'] as $fieldName => $field) {
1899
1900 if ($tableName == 'civicrm_address') {
1901 $this->_addressField = TRUE;
1902 }
1903 if ($tableName == 'civicrm_email') {
1904 $this->_emailField = TRUE;
1905 }
1906 if ($tableName == 'civicrm_phone') {
1907 $this->_phoneField = TRUE;
1908 }
1909 // 1. In many cases we want select clause to be built in slightly different way
1910 // for a particular field of a particular type.
1911 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1912 // as needed.
1913 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
1914 if ($selectClause) {
1915 $select[] = $selectClause;
1916 continue;
1917 }
1918
1919 if (!empty($this->_params['group_bys']) && CRM_Utils_Array::value($fieldName, $this->_params['group_bys'])
1920 && !empty($this->_params['group_bys_freq'])) {
1921 switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
1922 case 'YEARWEEK':
1923 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
1924 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1925 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1926 $field['title'] = 'Week';
1927 break;
1928
1929 case 'YEAR':
1930 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
1931 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1932 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1933 $field['title'] = 'Year';
1934 break;
1935
1936 case 'MONTH':
1937 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
1938 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1939 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1940 $field['title'] = 'Month';
1941 break;
1942
1943 case 'QUARTER':
1944 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
1945 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
1946 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
1947 $field['title'] = 'Quarter';
1948 break;
1949 }
1950 // for graphs and charts -
1951 if (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
1952 $this->_interval = $field['title'];
1953 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
1954 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
1955 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
1956
1957 // just to make sure these values are transfered to rows.
1958 // since we 'll need them for calculation purpose,
1959 // e.g making subtotals look nicer or graphs
1960 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
1961 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
1962 }
1963 }
1964 }
1965 }
1966 }
1967
1f220d30 1968 $this->_selectClauses = $select;
6a488035
TO
1969 $this->_select = "SELECT " . implode(', ', $select) . " ";
1970 }
1971
1972 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
1973 return FALSE;
1974 }
1975
1976 function where() {
adfe2750 1977 $this->storeWhereHavingClauseArray();
1978
1979 if (empty($this->_whereClauses)) {
1980 $this->_where = "WHERE ( 1 ) ";
1981 $this->_having = "";
1982 }
1983 else {
1984 $this->_where = "WHERE " . implode(' AND ', $this->_whereClauses);
1985 }
1986
1987 if ($this->_aclWhere) {
1988 $this->_where .= " AND {$this->_aclWhere} ";
1989 }
1990
1991 if (!empty($this->_havingClauses)) {
1992 // use this clause to construct group by clause.
1993 $this->_having = "HAVING " . implode(' AND ', $this->_havingClauses);
1994 }
1995 }
1996
1997 /**
1998 * Store Where clauses into an array - breaking out this step makes
1999 * over-riding more flexible as the clauses can be used in constructing a
2000 * temp table that may not be part of the final where clause or added
2001 * in other functions
2002 */
2003 function storeWhereHavingClauseArray(){
6a488035
TO
2004 foreach ($this->_columns as $tableName => $table) {
2005 if (array_key_exists('filters', $table)) {
2006 foreach ($table['filters'] as $fieldName => $field) {
d12de91c 2007 // respect pseudofield to filter spec so fields can be marked as
2008 // not to be handled here
2009 if(!empty($field['pseudofield'])){
2010 continue;
2011 }
6a488035
TO
2012 $clause = NULL;
2013 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
2014 if (CRM_Utils_Array::value('operatorType', $field) == CRM_Report_Form::OP_MONTH) {
2015 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2016 $value = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
2017 if (is_array($value) && !empty($value)) {
2018 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2019 }
2020 }
2021 else {
2022 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
2023 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
2024 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
2025 $fromTime = CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params);
2026 $toTime = CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params);
2027 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2028 }
2029 }
2030 else {
2031 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2032 if ($op) {
2033 $clause = $this->whereClause($field,
adfe2750 2034 $op,
2035 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
2036 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
2037 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
6a488035
TO
2038 );
2039 }
2040 }
2041
2042 if (!empty($clause)) {
2043 if (CRM_Utils_Array::value('having', $field)) {
adfe2750 2044 $this->_havingClauses[] = $clause;
6a488035
TO
2045 }
2046 else {
adfe2750 2047 $this->_whereClauses[] = $clause;
6a488035
TO
2048 }
2049 }
2050 }
2051 }
2052 }
2053
6a488035 2054 }
6a488035
TO
2055 function processReportMode() {
2056 $buttonName = $this->controller->getButtonName();
2057
884605ca
DL
2058 $output = CRM_Utils_Request::retrieve(
2059 'output',
2060 'String',
2061 CRM_Core_DAO::$_nullObject
6a488035
TO
2062 );
2063
2064 $this->_sendmail =
884605ca
DL
2065 CRM_Utils_Request::retrieve(
2066 'sendmail',
2067 'Boolean',
2068 CRM_Core_DAO::$_nullObject
2069 );
6a488035
TO
2070
2071 $this->_absoluteUrl = FALSE;
2072 $printOnly = FALSE;
2073 $this->assign('printOnly', FALSE);
2074
2075 if ($this->_printButtonName == $buttonName || $output == 'print' || ($this->_sendmail && !$output)) {
2076 $this->assign('printOnly', TRUE);
2077 $printOnly = TRUE;
2078 $this->assign('outputMode', 'print');
2079 $this->_outputMode = 'print';
2080 if ($this->_sendmail) {
2081 $this->_absoluteUrl = TRUE;
2082 }
2083 }
2084 elseif ($this->_pdfButtonName == $buttonName || $output == 'pdf') {
2085 $this->assign('printOnly', TRUE);
2086 $printOnly = TRUE;
2087 $this->assign('outputMode', 'pdf');
2088 $this->_outputMode = 'pdf';
2089 $this->_absoluteUrl = TRUE;
2090 }
2091 elseif ($this->_csvButtonName == $buttonName || $output == 'csv') {
2092 $this->assign('printOnly', TRUE);
2093 $printOnly = TRUE;
2094 $this->assign('outputMode', 'csv');
2095 $this->_outputMode = 'csv';
2096 $this->_absoluteUrl = TRUE;
2097 }
2098 elseif ($this->_groupButtonName == $buttonName || $output == 'group') {
2099 $this->assign('outputMode', 'group');
2100 $this->_outputMode = 'group';
2101 }
2102 elseif ($output == 'create_report' && $this->_criteriaForm) {
2103 $this->assign('outputMode', 'create_report');
2104 $this->_outputMode = 'create_report';
2105 }
2106 else {
2107 $this->assign('outputMode', 'html');
2108 $this->_outputMode = 'html';
2109 }
2110
2111 // Get today's date to include in printed reports
2112 if ($printOnly) {
2113 $reportDate = CRM_Utils_Date::customFormat(date('Y-m-d H:i'));
2114 $this->assign('reportDate', $reportDate);
2115 }
2116 }
2117
2118 function beginPostProcess() {
c58f66e0 2119 $this->setParams($this->controller->exportValues($this->_name));
6a488035
TO
2120
2121 if (empty($this->_params) &&
2122 $this->_force
2123 ) {
c58f66e0 2124 $this->setParams($this->_formValues);
6a488035
TO
2125 }
2126
2127 // hack to fix params when submitted from dashboard, CRM-8532
2128 // fields array is missing because form building etc is skipped
2129 // in dashboard mode for report
c58f66e0 2130 //@todo - this could be done in the dashboard no we have a setter
6a488035 2131 if (!CRM_Utils_Array::value('fields', $this->_params) && !$this->_noFields) {
c58f66e0 2132 $this->setParams($this->_formValues);
6a488035
TO
2133 }
2134
2135 $this->_formValues = $this->_params;
2136 if (CRM_Core_Permission::check('administer Reports') &&
2137 isset($this->_id) &&
2138 ($this->_instanceButtonName == $this->controller->getButtonName() . '_save' ||
2139 $this->_chartButtonName == $this->controller->getButtonName()
2140 )
2141 ) {
2142 $this->assign('updateReportButton', TRUE);
2143 }
2144 $this->processReportMode();
c58f66e0
E
2145 $this->beginPostProcessCommon();
2146 }
2147
2148 /**
2149 * beginPostProcess function run in both report mode and non-report mode (api)
2150 */
2151 function beginPostProcessCommon() {
2152
6a488035
TO
2153 }
2154
2155 function buildQuery($applyLimit = TRUE) {
2156 $this->select();
2157 $this->from();
2158 $this->customDataFrom();
2159 $this->where();
2160 $this->groupBy();
2161 $this->orderBy();
2162
2163 // order_by columns not selected for display need to be included in SELECT
2164 $unselectedSectionColumns = $this->unselectedSectionColumns();
2165 foreach ($unselectedSectionColumns as $alias => $section) {
2166 $this->_select .= ", {$section['dbAlias']} as {$alias}";
2167 }
2168
2169 if ($applyLimit && !CRM_Utils_Array::value('charts', $this->_params)) {
2170 $this->limit();
2171 }
2172 CRM_Utils_Hook::alterReportVar('sql', $this, $this);
2173
2174 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2175 return $sql;
2176 }
2177
2178 function groupBy() {
2179 $groupBys = array();
2180 if (CRM_Utils_Array::value('group_bys', $this->_params) &&
2181 is_array($this->_params['group_bys']) &&
2182 !empty($this->_params['group_bys'])
2183 ) {
2184 foreach ($this->_columns as $tableName => $table) {
2185 if (array_key_exists('group_bys', $table)) {
2186 foreach ($table['group_bys'] as $fieldName => $field) {
2187 if (CRM_Utils_Array::value($fieldName, $this->_params['group_bys'])) {
2188 $groupBys[] = $field['dbAlias'];
2189 }
2190 }
2191 }
2192 }
2193 }
2194
2195 if (!empty($groupBys)) {
2196 $this->_groupBy = "GROUP BY " . implode(', ', $groupBys);
2197 }
2198 }
2199
2200 function orderBy() {
2201 $this->_orderBy = "";
2202 $this->_sections = array();
2203 $this->storeOrderByArray();
2204 if(!empty($this->_orderByArray) && !$this->_rollup == 'WITH ROLLUP'){
2205 $this->_orderBy = "ORDER BY " . implode(', ', $this->_orderByArray);
2206 }
2207 $this->assign('sections', $this->_sections);
2208 }
f2947aea 2209
6a488035
TO
2210 /*
2211 * In some cases other functions want to know which fields are selected for ordering by
2212 * Separating this into a separate function allows it to be called separately from constructing
2213 * the order by clause
2214 */
2215 function storeOrderByArray() {
2216 $orderBys = array();
2217
2218 if (CRM_Utils_Array::value('order_bys', $this->_params) &&
2219 is_array($this->_params['order_bys']) &&
2220 !empty($this->_params['order_bys'])
2221 ) {
2222
2223 // Proces order_bys in user-specified order
2224 foreach ($this->_params['order_bys'] as $orderBy) {
2225 $orderByField = array();
2226 foreach ($this->_columns as $tableName => $table) {
2227 if (array_key_exists('order_bys', $table)) {
2228 // For DAO columns defined in $this->_columns
2229 $fields = $table['order_bys'];
2230 }
2231 elseif (array_key_exists('extends', $table)) {
2232 // For custom fields referenced in $this->_customGroupExtends
2233 $fields = $table['fields'];
2234 }
2235 if (!empty($fields) && is_array($fields)) {
2236 foreach ($fields as $fieldName => $field) {
2237 if ($fieldName == $orderBy['column']) {
f2947aea 2238 $orderByField = array_merge($field, $orderBy);
6a488035
TO
2239 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2240 break 2;
2241 }
2242 }
2243 }
2244 }
2245
2246 if (!empty($orderByField)) {
f2947aea 2247 $this->_orderByFields[] = $orderByField;
6a488035
TO
2248 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2249
2250 // Record any section headers for assignment to the template
2251 if (CRM_Utils_Array::value('section', $orderBy)) {
b5801e1d 2252 $orderByField['pageBreak'] = CRM_Utils_Array::value('pageBreak', $orderBy);
6a488035
TO
2253 $this->_sections[$orderByField['tplField']] = $orderByField;
2254 }
2255 }
2256 }
2257 }
2258
2259 $this->_orderByArray = $orderBys;
2260
2261 $this->assign('sections', $this->_sections);
2262 }
2263
2264 function unselectedSectionColumns() {
2265 $selectColumns = array();
2266 foreach ($this->_columns as $tableName => $table) {
2267 if (array_key_exists('fields', $table)) {
2268 foreach ($table['fields'] as $fieldName => $field) {
2269 if (CRM_Utils_Array::value('required', $field) ||
2270 CRM_Utils_Array::value($fieldName, $this->_params['fields'])
2271 ) {
2272
2273 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2274 }
2275 }
2276 }
2277 }
f2947aea 2278
6a488035
TO
2279 if (is_array($this->_sections)) {
2280 return array_diff_key($this->_sections, $selectColumns);
2281 }
2282 else {
2283 return array();
2284 }
2285 }
2286
2287 function buildRows($sql, &$rows) {
2288 $dao = CRM_Core_DAO::executeQuery($sql);
2289 if (!is_array($rows)) {
2290 $rows = array();
2291 }
2292
2293 // use this method to modify $this->_columnHeaders
2294 $this->modifyColumnHeaders();
2295
2296 $unselectedSectionColumns = $this->unselectedSectionColumns();
2297
2298 while ($dao->fetch()) {
2299 $row = array();
2300 foreach ($this->_columnHeaders as $key => $value) {
2301 if (property_exists($dao, $key)) {
2302 $row[$key] = $dao->$key;
2303 }
2304 }
2305
2306 // section headers not selected for display need to be added to row
2307 foreach ($unselectedSectionColumns as $key => $values) {
2308 if (property_exists($dao, $key)) {
2309 $row[$key] = $dao->$key;
2310 }
2311 }
2312
2313 $rows[] = $row;
2314 }
2315 }
2316
2317 /**
2318 * When "order by" fields are marked as sections, this assigns to the template
2319 * an array of total counts for each section. This data is used by the Smarty
2320 * plugin {sectionTotal}
2321 */
2322 function sectionTotals() {
2323
2324 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2325 if (empty($this->_selectAliases)) {
2326 return;
2327 }
2328
2329 if (!empty($this->_sections)) {
2330 // build the query with no LIMIT clause
2331 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select);
2332 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2333
2334 // pull section aliases out of $this->_sections
2335 $sectionAliases = array_keys($this->_sections);
2336
2337 $ifnulls = array();
2338 foreach (array_merge($sectionAliases, $this->_selectAliases) as $alias) {
2339 $ifnulls[] = "ifnull($alias, '') as $alias";
2340 }
2341
2342 /* Group (un-limited) report by all aliases and get counts. This might
2343 * be done more efficiently when the contents of $sql are known, ie. by
2344 * overriding this method in the report class.
2345 */
2346
2347
2348 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2349
2350 // initialize array of total counts
2351 $totals = array();
2352 $dao = CRM_Core_DAO::executeQuery($query);
2353 while ($dao->fetch()) {
2354
2355 // let $this->_alterDisplay translate any integer ids to human-readable values.
2356 $rows[0] = $dao->toArray();
2357 $this->alterDisplay($rows);
2358 $row = $rows[0];
2359
2360 // add totals for all permutations of section values
2361 $values = array();
2362 $i = 1;
2363 $aliasCount = count($sectionAliases);
2364 foreach ($sectionAliases as $alias) {
2365 $values[] = $row[$alias];
2366 $key = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values);
2367 if ($i == $aliasCount) {
2368 // the last alias is the lowest-level section header; use count as-is
2369 $totals[$key] = $dao->ct;
2370 }
2371 else {
2372 // other aliases are higher level; roll count into their total
2373 $totals[$key] += $dao->ct;
2374 }
2375 }
2376 }
2377 $this->assign('sectionTotals', $totals);
2378 }
2379 }
2380
2381 function modifyColumnHeaders() {
2382 // use this method to modify $this->_columnHeaders
2383 }
2384
2385 function doTemplateAssignment(&$rows) {
2386 $this->assign_by_ref('columnHeaders', $this->_columnHeaders);
2387 $this->assign_by_ref('rows', $rows);
2388 $this->assign('statistics', $this->statistics($rows));
2389 }
2390
2391 // override this method to build your own statistics
2392 function statistics(&$rows) {
2393 $statistics = array();
2394
2395 $count = count($rows);
2396
2397 if ($this->_rollup && ($this->_rollup != '') && $this->_grandFlag) {
2398 $count++;
2399 }
2400
2401 $this->countStat($statistics, $count);
2402
2403 $this->groupByStat($statistics);
2404
2405 $this->filterStat($statistics);
2406
2407 return $statistics;
2408 }
2409
2410 function countStat(&$statistics, $count) {
2411 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2412 'value' => $count,
2413 );
2414
2415 if ($this->_rowsFound && ($this->_rowsFound > $count)) {
2416 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2417 'value' => $this->_rowsFound,
2418 );
2419 }
2420 }
2421
2422 function groupByStat(&$statistics) {
2423 if (CRM_Utils_Array::value('group_bys', $this->_params) &&
2424 is_array($this->_params['group_bys']) &&
2425 !empty($this->_params['group_bys'])
2426 ) {
2427 foreach ($this->_columns as $tableName => $table) {
2428 if (array_key_exists('group_bys', $table)) {
2429 foreach ($table['group_bys'] as $fieldName => $field) {
2430 if (CRM_Utils_Array::value($fieldName, $this->_params['group_bys'])) {
2431 $combinations[] = $field['title'];
2432 }
2433 }
2434 }
2435 }
2436 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2437 'value' => implode(' & ', $combinations),
2438 );
2439 }
2440 }
2441
2442 function filterStat(&$statistics) {
2443 foreach ($this->_columns as $tableName => $table) {
2444 if (array_key_exists('filters', $table)) {
2445 foreach ($table['filters'] as $fieldName => $field) {
2446 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
2447 list($from, $to) =
2448 $this->getFromTo(
2449 CRM_Utils_Array::value("{$fieldName}_relative", $this->_params),
2450 CRM_Utils_Array::value("{$fieldName}_from", $this->_params),
2451 CRM_Utils_Array::value("{$fieldName}_to", $this->_params),
2452 CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params),
2453 CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params)
2454 );
6a488035
TO
2455 $from_time_format = CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params) ? 'h' : 'd';
2456 $from = CRM_Utils_Date::customFormat($from, null, array($from_time_format));
2457
2458 $to_time_format = CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params) ? 'h' : 'd';
2459 $to = CRM_Utils_Date::customFormat($to, null, array($to_time_format));
2460
2461 if ($from || $to) {
2462 $statistics['filters'][] = array(
2463 'title' => $field['title'],
10a5be27 2464 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
6a488035
TO
2465 );
2466 }
2467 elseif (in_array($rel = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params),
160d32e1 2468 array_keys($this->getOperationPair(CRM_Report_Form::OP_DATE))
6a488035 2469 )) {
160d32e1 2470 $pair = $this->getOperationPair(CRM_Report_Form::OP_DATE);
6a488035
TO
2471 $statistics['filters'][] = array(
2472 'title' => $field['title'],
2473 'value' => $pair[$rel],
2474 );
2475 }
2476 }
2477 else {
2478 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2479 $value = NULL;
2480 if ($op) {
1b36206c 2481 $pair = $this->getOperationPair(
8f1445ea
DL
2482 CRM_Utils_Array::value('operatorType', $field),
2483 $fieldName
6a488035
TO
2484 );
2485 $min = CRM_Utils_Array::value("{$fieldName}_min", $this->_params);
2486 $max = CRM_Utils_Array::value("{$fieldName}_max", $this->_params);
2487 $val = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
2488 if (in_array($op, array(
2489 'bw', 'nbw')) && ($min || $max)) {
2490 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2491 }
2492 elseif ($op == 'nll' || $op == 'nnll') {
2493 $value = $pair[$op];
2494 }
2495 elseif (is_array($val) && (!empty($val))) {
f974e915 2496 $options = CRM_Utils_Array::value('options', $field, array());
6a488035
TO
2497 foreach ($val as $key => $valIds) {
2498 if (isset($options[$valIds])) {
2499 $val[$key] = $options[$valIds];
2500 }
2501 }
f974e915 2502 $pair[$op] = (count($val) == 1) ? (($op == 'notin') ? ts('Is Not') : ts('Is')) : CRM_Utils_Array::value($op, $pair);
6a488035
TO
2503 $val = implode(', ', $val);
2504 $value = "{$pair[$op]} " . $val;
2505 }
2506 elseif (!is_array($val) && (!empty($val) || $val == '0') && isset($field['options']) &&
2507 is_array($field['options']) && !empty($field['options'])
2508 ) {
2509 $value = CRM_Utils_Array::value($op, $pair) . " " . CRM_Utils_Array::value($val, $field['options'], $val);
2510 }
2511 elseif ($val) {
2512 $value = CRM_Utils_Array::value($op, $pair) . " " . $val;
2513 }
2514 }
2515 if ($value) {
2516 $statistics['filters'][] = array('title' => CRM_Utils_Array::value('title', $field),
2517 'value' => $value,
2518 );
2519 }
2520 }
2521 }
2522 }
2523 }
2524 }
2525
2526 function endPostProcess(&$rows = NULL) {
ae555e90
DS
2527 if ( $this->_storeResultSet ) {
2528 $this->_resultSet = $rows;
2529 }
2530
6a488035
TO
2531 if ($this->_outputMode == 'print' ||
2532 $this->_outputMode == 'pdf' ||
2533 $this->_sendmail
2534 ) {
2535
2536 $content = $this->compileContent();
2537 $url = CRM_Utils_System::url("civicrm/report/instance/{$this->_id}",
2538 "reset=1", TRUE
2539 );
2540
2541 if ($this->_sendmail) {
2542 $config = CRM_Core_Config::singleton();
2543 $attachments = array();
2544
2545 if ($this->_outputMode == 'csv') {
2546 $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'];
2547
2548 $csvFullFilename = $config->templateCompileDir . CRM_Utils_File::makeFileName('CiviReport.csv');
2549 $csvContent = CRM_Report_Utils_Report::makeCsv($this, $rows);
2550 file_put_contents($csvFullFilename, $csvContent);
2551 $attachments[] = array(
2552 'fullPath' => $csvFullFilename,
2553 'mime_type' => 'text/csv',
2554 'cleanName' => 'CiviReport.csv',
2555 );
2556 }
2557 if ($this->_outputMode == 'pdf') {
2558 // generate PDF content
2559 $pdfFullFilename = $config->templateCompileDir . CRM_Utils_File::makeFileName('CiviReport.pdf');
2560 file_put_contents($pdfFullFilename,
2561 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf",
2562 TRUE, array('orientation' => 'landscape')
2563 )
2564 );
2565 // generate Email Content
2566 $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'];
2567
2568 $attachments[] = array(
2569 'fullPath' => $pdfFullFilename,
2570 'mime_type' => 'application/pdf',
2571 'cleanName' => 'CiviReport.pdf',
2572 );
2573 }
2574
2575 if (CRM_Report_Utils_Report::mailReport($content, $this->_id,
2576 $this->_outputMode, $attachments
2577 )) {
2578 CRM_Core_Session::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2579 }
2580 else {
2581 CRM_Core_Session::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2582 }
2583
1c4d8c3e 2584 CRM_Utils_System::redirect(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1'));
6a488035
TO
2585 }
2586 elseif ($this->_outputMode == 'print') {
2587 echo $content;
2588 }
2589 else {
2590 if ($chartType = CRM_Utils_Array::value('charts', $this->_params)) {
2591 $config = CRM_Core_Config::singleton();
2592 //get chart image name
2593 $chartImg = $this->_chartId . '.png';
2594 //get image url path
2595 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL) . 'openFlashChart/';
2596 $uploadUrl .= $chartImg;
2597 //get image doc path to overwrite
2598 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir) . 'openFlashChart/' . $chartImg;
2599 //Load the image
2600 $chart = imagecreatefrompng($uploadUrl);
2601 //convert it into formattd png
2602 header('Content-type: image/png');
2603 //overwrite with same image
2604 imagepng($chart, $uploadImg);
2605 //delete the object
2606 imagedestroy($chart);
2607 }
2608 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2609 }
2610 CRM_Utils_System::civiExit();
2611 }
2612 elseif ($this->_outputMode == 'csv') {
2613 CRM_Report_Utils_Report::export2csv($this, $rows);
2614 }
2615 elseif ($this->_outputMode == 'group') {
2616 $group = $this->_params['groups'];
2617 $this->add2group($group);
2618 }
2619 elseif ($this->_instanceButtonName == $this->controller->getButtonName()) {
2620 CRM_Report_Form_Instance::postProcess($this);
2621 }
2622 elseif ($this->_createNewButtonName == $this->controller->getButtonName() ||
2623 $this->_outputMode == 'create_report' ) {
2624 $this->_createNew = TRUE;
2625 CRM_Report_Form_Instance::postProcess($this);
2626 }
2627 }
8f1445ea 2628
ae555e90
DS
2629 function storeResultSet() {
2630 $this->_storeResultSet = TRUE;
2631 }
2632
2633 function getResultSet() {
2634 return $this->_resultSet;
2635 }
2636
6a488035
TO
2637 /*
2638 * Get Template file name - use default form template if a specific one has not been set up for this report
2639 *
2640 */
2641 function getTemplateFileName(){
2642 $defaultTpl = parent::getTemplateFileName();
2643 $template = CRM_Core_Smarty::singleton();
2644 if (!$template->template_exists($defaultTpl)) {
2645 $defaultTpl = 'CRM/Report/Form.tpl';
2646 }
2647 return $defaultTpl;
2648 }
2649
2650 /*
2651 * Compile the report content
2652 *
2653 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2654 */
2655 function compileContent(){
8aac22c8 2656 $templateFile = $this->getHookedTemplateFileName();
6a488035
TO
2657 return $this->_formValues['report_header'] . CRM_Core_Form::$_template->fetch($templateFile) . $this->_formValues['report_footer'];
2658 }
2659
2660
2661 function postProcess() {
2662 // get ready with post process params
2663 $this->beginPostProcess();
2664
2665 // build query
2666 $sql = $this->buildQuery();
2667
2668 // build array of result based on column headers. This method also allows
2669 // modifying column headers before using it to build result set i.e $rows.
2670 $rows = array();
2671 $this->buildRows($sql, $rows);
2672
2673 // format result set.
2674 $this->formatDisplay($rows);
2675
2676 // assign variables to templates
2677 $this->doTemplateAssignment($rows);
2678
2679 // do print / pdf / instance stuff if needed
2680 $this->endPostProcess($rows);
2681 }
2682
2683 function limit($rowCount = self::ROW_COUNT_LIMIT) {
2684 // lets do the pager if in html mode
2685 $this->_limit = NULL;
2686 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
2687 $this->_select = str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select);
2688
2689 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
2690
2691 if (!$pageId && !empty($_POST)) {
2692 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2693 $pageId = max((int)@$_POST['crmPID_B'], 1);
2694 }
2695 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2696 $pageId = max((int)@$_POST['crmPID'], 1);
2697 }
2698 unset($_POST['crmPID_B'], $_POST['crmPID']);
2699 }
2700
2701 $pageId = $pageId ? $pageId : 1;
2702 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
2703 $offset = ($pageId - 1) * $rowCount;
2704
bf00d1b6
DL
2705 $offset = CRM_Utils_Type::escape($offset, 'Int');
2706 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
2707
dd3a4117 2708 $this->_limit = " LIMIT $offset, $rowCount";
6a488035
TO
2709 return array($offset, $rowCount);
2710 }
6f900755
E
2711 if($this->_limitValue) {
2712 if($this->_offsetValue) {
2713 $this->_limit = " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
2714 }
2715 else {
2716 $this->_limit = " LIMIT " . $this->_limitValue;
2717 }
2718 }
6a488035
TO
2719 }
2720
2721 function setPager($rowCount = self::ROW_COUNT_LIMIT) {
2722 if ($this->_limit && ($this->_limit != '')) {
2723 $sql = "SELECT FOUND_ROWS();";
2724 $this->_rowsFound = CRM_Core_DAO::singleValueQuery($sql);
2725 $params = array(
2726 'total' => $this->_rowsFound,
2727 'rowCount' => $rowCount,
2728 'status' => ts('Records') . ' %%StatusMessage%%',
2729 'buttonBottom' => 'PagerBottomButton',
2730 'buttonTop' => 'PagerTopButton',
2731 'pageID' => $this->get(CRM_Utils_Pager::PAGE_ID),
2732 );
2733
2734 $pager = new CRM_Utils_Pager($params);
2735 $this->assign_by_ref('pager', $pager);
ecc20f0e 2736 $this->ajaxResponse['totalRows'] = $this->_rowsFound;
6a488035
TO
2737 }
2738 }
2739
2740 function whereGroupClause($field, $value, $op) {
2741
2742 $smartGroupQuery = "";
2743
2744 $group = new CRM_Contact_DAO_Group();
2745 $group->is_active = 1;
2746 $group->find();
2747 $smartGroups = array();
2748 while ($group->fetch()) {
2749 if (in_array($group->id, $this->_params['gid_value']) && $group->saved_search_id) {
2750 $smartGroups[] = $group->id;
2751 }
2752 }
2753
2754 CRM_Contact_BAO_GroupContactCache::check($smartGroups);
2755
2756 $smartGroupQuery = '';
2757 if (!empty($smartGroups)) {
2758 $smartGroups = implode(',', $smartGroups);
2759 $smartGroupQuery = " UNION DISTINCT
2760 SELECT DISTINCT smartgroup_contact.contact_id
2761 FROM civicrm_group_contact_cache smartgroup_contact
2762 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2763 }
2764
29fc2b79 2765 $sqlOp = $this->getSQLOperator($op);
6a488035
TO
2766 if (!is_array($value)) {
2767 $value = array($value);
2768 }
2769 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2770
2771 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2772 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2773 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2774 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2775 {$smartGroupQuery} ) ";
2776 }
2777
2778 function whereTagClause($field, $value, $op) {
2779 // not using left join in query because if any contact
2780 // belongs to more than one tag, results duplicate
2781 // entries.
29fc2b79 2782 $sqlOp = $this->getSQLOperator($op);
6a488035
TO
2783 if (!is_array($value)) {
2784 $value = array($value);
2785 }
2786 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2787
2788 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2789 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2790 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2791 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2792 }
2793
2794 function buildACLClause($tableAlias = 'contact_a') {
2795 list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
2796 }
2797
2798 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2799 if (empty($this->_customGroupExtends)) {
2800 return;
2801 }
2802 if (!is_array($this->_customGroupExtends)) {
2803 $this->_customGroupExtends = array($this->_customGroupExtends);
2804 }
2805 $customGroupWhere = '';
2806 if (!empty($permCustomGroupIds)) {
2807 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2808 }
2809 $sql = "
2810SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2811 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2812FROM civicrm_custom_group cg
2813INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2814WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
2815 {$customGroupWhere}
2816 cg.is_active = 1 AND
2817 cf.is_active = 1 AND
2818 cf.is_searchable = 1
2819ORDER BY cg.weight, cf.weight";
2820 $customDAO = CRM_Core_DAO::executeQuery($sql);
2821
2822 $curTable = NULL;
2823 while ($customDAO->fetch()) {
2824 if ($customDAO->table_name != $curTable) {
2825 $curTable = $customDAO->table_name;
2826 $curFields = $curFilters = array();
2827
2828 // dummy dao object
2829 $this->_columns[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2830 $this->_columns[$curTable]['extends'] = $customDAO->extends;
2831 $this->_columns[$curTable]['grouping'] = $customDAO->table_name;
2832 $this->_columns[$curTable]['group_title'] = $customDAO->title;
2833
2834 foreach (array(
2835 'fields', 'filters', 'group_bys') as $colKey) {
2836 if (!array_key_exists($colKey, $this->_columns[$curTable])) {
2837 $this->_columns[$curTable][$colKey] = array();
2838 }
2839 }
2840 }
2841 $fieldName = 'custom_' . $customDAO->cf_id;
2842
2843 if ($addFields) {
2844 // this makes aliasing work in favor
2845 $curFields[$fieldName] = array(
2846 'name' => $customDAO->column_name,
2847 'title' => $customDAO->label,
2848 'dataType' => $customDAO->data_type,
2849 'htmlType' => $customDAO->html_type,
2850 );
2851 }
2852 if ($this->_customGroupFilters) {
2853 // this makes aliasing work in favor
2854 $curFilters[$fieldName] = array(
2855 'name' => $customDAO->column_name,
2856 'title' => $customDAO->label,
2857 'dataType' => $customDAO->data_type,
2858 'htmlType' => $customDAO->html_type,
2859 );
2860 }
2861
2862 switch ($customDAO->data_type) {
2863 case 'Date':
2864 // filters
2865 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE;
2866 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_DATE;
2867 // CRM-6946, show time part for datetime date fields
2868 if ($customDAO->time_format) {
2869 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_TIMESTAMP;
2870 }
2871 break;
2872
2873 case 'Boolean':
2874 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT;
2875 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2876 1 => ts('Yes'),
2877 0 => ts('No'),
2878 );
2879 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
2880 break;
2881
2882 case 'Int':
2883 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_INT;
2884 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
2885 break;
2886
2887 case 'Money':
2888 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
2889 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_MONEY;
2890 break;
2891
2892 case 'Float':
2893 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
2894 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_FLOAT;
2895 break;
2896
2897 case 'String':
2898 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2899
2900 if (!empty($customDAO->option_group_id)) {
2901 if (in_array($customDAO->html_type, array(
2902 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2903 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
2904 }
2905 else {
2906 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
2907 }
2908 if ($this->_customGroupFilters) {
2909 $curFilters[$fieldName]['options'] = array();
2910 $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')));
2911 while ($ogDAO->fetch()) {
2912 $curFilters[$fieldName]['options'][$ogDAO->value] = $ogDAO->label;
2913 }
2914 }
2915 }
2916 break;
2917
2918 case 'StateProvince':
2919 if (in_array($customDAO->html_type, array(
2920 'Multi-Select State/Province'))) {
2921 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
2922 }
2923 else {
2924 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
2925 }
2926 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::stateProvince();
2927 break;
2928
2929 case 'Country':
2930 if (in_array($customDAO->html_type, array(
2931 'Multi-Select Country'))) {
2932 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
2933 }
2934 else {
2935 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
2936 }
2937 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::country();
2938 break;
2939
2940 case 'ContactReference':
2941 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2942 $curFilters[$fieldName]['name'] = 'display_name';
2943 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2944
2945 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2946 $curFields[$fieldName]['name'] = 'display_name';
2947 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2948 break;
2949
2950 default:
2951 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2952 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2953 }
2954
2955 if (!array_key_exists('type', $curFields[$fieldName])) {
fc161185 2956 $curFields[$fieldName]['type'] = CRM_Utils_Array::value('type', $curFilters[$fieldName], array());
6a488035
TO
2957 }
2958
2959 if ($addFields) {
2960 $this->_columns[$curTable]['fields'] = array_merge($this->_columns[$curTable]['fields'], $curFields);
2961 }
2962 if ($this->_customGroupFilters) {
2963 $this->_columns[$curTable]['filters'] = array_merge($this->_columns[$curTable]['filters'], $curFilters);
2964 }
2965 if ($this->_customGroupGroupBy) {
2966 $this->_columns[$curTable]['group_bys'] = array_merge($this->_columns[$curTable]['group_bys'], $curFields);
2967 }
2968 }
2969 }
2970
2971 function customDataFrom() {
2972 if (empty($this->_customGroupExtends)) {
2973 return;
2974 }
2975 $mapper = CRM_Core_BAO_CustomQuery::$extendsMap;
2976
2977 foreach ($this->_columns as $table => $prop) {
2978 if (substr($table, 0, 13) == 'civicrm_value' || substr($table, 0, 12) == 'custom_value') {
2979 $extendsTable = $mapper[$prop['extends']];
2980
2981 // check field is in params
2982 if (!$this->isFieldSelected($prop)) {
2983 continue;
2984 }
4c9d78ea 2985 $baseJoin = CRM_Utils_Array::value($prop['extends'], $this->_customGroupExtendsJoin, "{$this->_aliases[$extendsTable]}.id");
6a488035 2986
7a8b61ab 2987 $customJoin = is_array($this->_customGroupJoin) ? $this->_customGroupJoin[$table] : $this->_customGroupJoin;
6a488035 2988 $this->_from .= "
aa1aa08e 2989{$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
6a488035
TO
2990 // handle for ContactReference
2991 if (array_key_exists('fields', $prop)) {
2992 foreach ($prop['fields'] as $fieldName => $field) {
2993 if (CRM_Utils_Array::value('dataType', $field) == 'ContactReference') {
2994 $columnName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField::getKeyID($fieldName), 'column_name');
2995 $this->_from .= "
2996LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
2997 }
2998 }
2999 }
3000 }
3001 }
3002 }
3003
3004 function isFieldSelected($prop) {
3005 if (empty($prop)) {
3006 return FALSE;
3007 }
3008
3009 if (!empty($this->_params['fields'])) {
3010 foreach (array_keys($prop['fields']) as $fieldAlias) {
3011 $customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias);
3012 if ($customFieldId) {
3013 if (array_key_exists($fieldAlias, $this->_params['fields'])) {
3014 return TRUE;
3015 }
3016
3017 //might be survey response field.
3018 if (CRM_Utils_Array::value('survey_response', $this->_params['fields']) &&
3019 CRM_Utils_Array::value('isSurveyResponseField', $prop['fields'][$fieldAlias])
3020 ) {
3021 return TRUE;
3022 }
3023 }
3024 }
3025 }
3026
3027 if (!empty($this->_params['group_bys']) && $this->_customGroupGroupBy) {
3028 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3029 if (array_key_exists($fieldAlias, $this->_params['group_bys']) && CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
3030 return TRUE;
3031 }
3032 }
3033 }
3034
3035 if (!empty($this->_params['order_bys'])) {
3036 foreach (array_keys($prop['fields']) as $fieldAlias) {
3037 foreach ($this->_params['order_bys'] as $orderBy) {
3038 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
3039 return TRUE;
3040 }
3041 }
3042 }
3043 }
3044
3045 if (!empty($prop['filters']) && $this->_customGroupFilters) {
3046 foreach ($prop['filters'] as $fieldAlias => $val) {
3047 foreach (array(
3048 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3049 if (isset($this->_params[$fieldAlias . '_' . $attach]) &&
dfe4b2f5 3050 (!empty($this->_params[$fieldAlias . '_' . $attach])
3051 || ($attach != 'relative' && $this->_params[$fieldAlias . '_' . $attach] == '0')
3052 )
3053 ){
6a488035
TO
3054 return TRUE;
3055 }
3056 }
3057 if (CRM_Utils_Array::value($fieldAlias . '_op', $this->_params) &&
3058 in_array($this->_params[$fieldAlias . '_op'], array('nll', 'nnll'))
3059 ) {
3060 return TRUE;
3061 }
3062 }
3063 }
3064
3065 return FALSE;
3066 }
3067
3068 /**
3069 * Check for empty order_by configurations and remove them; also set
3070 * template to hide them.
3071 */
3072 function preProcessOrderBy(&$formValues) {
3073 // Object to show/hide form elements
ae555e90 3074 $_showHide = new CRM_Core_ShowHideBlocks('', '');
6a488035
TO
3075
3076 $_showHide->addShow('optionField_1');
3077
3078 // Cycle through order_by options; skip any empty ones, and hide them as well
3079 $n = 1;
3080
3081 if (!empty($formValues['order_bys'])) {
3082 foreach ($formValues['order_bys'] as $order_by) {
3083 if ($order_by['column'] && $order_by['column'] != '-') {
3084 $_showHide->addShow('optionField_' . $n);
3085 $orderBys[$n] = $order_by;
3086 $n++;
3087 }
3088 }
3089 }
3090 for ($i = $n; $i <= 5; $i++) {
3091 if ($i > 1) {
3092 $_showHide->addHide('optionField_' . $i);
3093 }
3094 }
3095
3096 // overwrite order_by options with modified values
3097 if (!empty($orderBys)) {
3098 $formValues['order_bys'] = $orderBys;
3099 }
3100 else {
3101 $formValues['order_bys'] = array(1 => array('column' => '-'));
3102 }
3103
3104 // assign show/hide data to template
3105 $_showHide->addToTemplate();
3106 }
3107
3108 /**
3109 * Does table name have columns in SELECT clause?
3110 *
3111 * @param string $tableName Name of table (index of $this->_columns array)
3112 *
3113 * @return bool
3114 */
3115 function isTableSelected($tableName) {
3116 return in_array($tableName, $this->selectedTables());
3117 }
3118
3119 /**
3120 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3121 * (building the array if it's unset)
3122 *
3123 * @return Array $this->_selectedTables
3124 */
3125 function selectedTables() {
3126 if (!$this->_selectedTables) {
3127 $orderByColumns = array();
7a8b61ab 3128 if (array_key_exists('order_bys', $this->_params) && is_array($this->_params['order_bys'])) {
6a488035
TO
3129 foreach ($this->_params['order_bys'] as $orderBy) {
3130 $orderByColumns[] = $orderBy['column'];
3131 }
3132 }
3133
3134 foreach ($this->_columns as $tableName => $table) {
3135 if (array_key_exists('fields', $table)) {
3136 foreach ($table['fields'] as $fieldName => $field) {
3137 if (CRM_Utils_Array::value('required', $field) ||
3138 CRM_Utils_Array::value($fieldName, $this->_params['fields'])
3139 ) {
3140 $this->_selectedTables[] = $tableName;
3141 break;
3142 }
3143 }
3144 }
3145 if (array_key_exists('order_bys', $table)) {
3146 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3147 if (in_array($orderByName, $orderByColumns)) {
3148 $this->_selectedTables[] = $tableName;
3149 break;
3150 }
3151 }
3152 }
3153 if (array_key_exists('filters', $table)) {
3154 foreach ($table['filters'] as $filterName => $filter) {
3155 if (CRM_Utils_Array::value("{$filterName}_value", $this->_params) ||
3156 CRM_Utils_Array::value("{$filterName}_op", $this->_params) == 'nll' ||
3157 CRM_Utils_Array::value("{$filterName}_op", $this->_params) == 'nnll'
3158 ) {
3159 $this->_selectedTables[] = $tableName;
3160 break;
3161 }
3162 }
3163 }
3164 }
3165 }
3166 return $this->_selectedTables;
3167 }
3168
850e4640
E
3169 /**
3170 * @deprecated - use getAddressColumns which is a more accurate description
3171 * and also accepts an array of options rather than a long list
3172 *
6a488035
TO
3173 * function for adding address fields to construct function in reports
3174 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3175 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3176 * @return array address fields for construct clause
3177 */
3178 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3179 'country_id' => TRUE)) {
3180 $addressFields = array(
3181 'civicrm_address' =>
3182 array(
3183 'dao' => 'CRM_Core_DAO_Address',
3184 'fields' =>
3185 array(
3186 'name' =>
3187 array('title' => ts('Address Name'),
3188 'default' => CRM_Utils_Array::value('name', $defaults, FALSE),
3189 ),
3190 'street_address' =>
3191 array('title' => ts('Street Address'),
3192 'default' => CRM_Utils_Array::value('street_address', $defaults, FALSE),
3193 ),
3194 'supplemental_address_1' =>
3195 array('title' => ts('Supplementary Address Field 1'),
3196 'default' => CRM_Utils_Array::value('supplemental_address_1', $defaults, FALSE),
3197 ),
3198 'supplemental_address_2' =>
3199 array('title' => ts('Supplementary Address Field 2'),
3200 'default' => CRM_Utils_Array::value('supplemental_address_2', $defaults, FALSE),
3201 ),
3202 'street_number' =>
3203 array(
3204 'name' => 'street_number',
3205 'title' => ts('Street Number'),
3206 'type' => 1,
3207 'default' => CRM_Utils_Array::value('street_number', $defaults, FALSE),
3208 ),
3209 'street_name' =>
3210 array(
3211 'name' => 'street_name',
3212 'title' => ts('Street Name'),
3213 'type' => 1,
3214 'default' => CRM_Utils_Array::value('street_name', $defaults, FALSE),
3215 ),
3216 'street_unit' =>
3217 array(
3218 'name' => 'street_unit',
3219 'title' => ts('Street Unit'),
3220 'type' => 1,
3221 'default' => CRM_Utils_Array::value('street_unit', $defaults, FALSE),
3222 ),
3223 'city' =>
3224 array('title' => ts('City'),
3225 'default' => CRM_Utils_Array::value('city', $defaults, FALSE),
3226 ),
3227 'postal_code' =>
3228 array('title' => ts('Postal Code'),
3229 'default' => CRM_Utils_Array::value('postal_code', $defaults, FALSE),
4cbdd2b1
JL
3230 ),
3231 'postal_code_suffix' =>
3232 array('title' => ts('Postal Code Suffix'),
3233 'default' => CRM_Utils_Array::value('postal_code_suffix', $defaults, FALSE),
6a488035
TO
3234 ),
3235 'county_id' =>
3236 array('title' => ts('County'),
3237 'default' => CRM_Utils_Array::value('county_id', $defaults, FALSE),
3238 ),
3239 'state_province_id' =>
3240 array('title' => ts('State/Province'),
3241 'default' => CRM_Utils_Array::value('state_province_id', $defaults, FALSE),
3242 ),
3243 'country_id' =>
3244 array('title' => ts('Country'),
3245 'default' => CRM_Utils_Array::value('country_id', $defaults, FALSE),
3246 ),
3247 ),
3248 'grouping' => 'location-fields',
3249 ),
3250 );
3251
3252 if ($filters) {
3253 $addressFields['civicrm_address']['filters'] = array(
3254 'street_number' => array('title' => ts('Street Number'),
3255 'type' => 1,
3256 'name' => 'street_number',
3257 ),
3258 'street_name' => array('title' => ts('Street Name'),
3259 'name' => 'street_name',
3260 'operator' => 'like',
3261 ),
3262 'postal_code' => array('title' => ts('Postal Code'),
3263 'type' => 1,
3264 'name' => 'postal_code',
3265 ),
3266 'city' => array('title' => ts('City'),
3267 'operator' => 'like',
3268 'name' => 'city',
3269 ),
3270 'county_id' => array(
3271 'name' => 'county_id',
3272 'title' => ts('County'),
3273 'type' => CRM_Utils_Type::T_INT,
3274 'operatorType' =>
3275 CRM_Report_Form::OP_MULTISELECT,
3276 'options' =>
3277 CRM_Core_PseudoConstant::county(),
3278 ),
3279 'state_province_id' => array(
3280 'name' => 'state_province_id',
3281 'title' => ts('State/Province'),
3282 'type' => CRM_Utils_Type::T_INT,
3283 'operatorType' =>
3284 CRM_Report_Form::OP_MULTISELECT,
3285 'options' =>
3286 CRM_Core_PseudoConstant::stateProvince(),
3287 ),
3288 'country_id' => array(
3289 'name' => 'country_id',
3290 'title' => ts('Country'),
3291 'type' => CRM_Utils_Type::T_INT,
3292 'operatorType' =>
3293 CRM_Report_Form::OP_MULTISELECT,
3294 'options' =>
3295 CRM_Core_PseudoConstant::country(),
3296 ),
3297 );
3298 }
3299
3300 if ($orderBy) {
3301 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3302 'street_number' => array('title' => 'Odd / Even Street Number'),
3303 'street_address' => NULL,
3304 'city' => NULL,
3305 'postal_code' => NULL,
3306 );
3307 }
3308
3309 if ($groupBy) {
3310 $addressFields['civicrm_address']['group_bys'] = array(
3311 'street_address' => NULL,
3312 'city' => NULL,
3313 'postal_code' => NULL,
3314 'state_province_id' =>
3315 array('title' => ts('State/Province'),
3316 ),
3317 'country_id' =>
3318 array('title' => ts('Country'),
3319 ),
3320 'county_id' =>
3321 array('title' => ts('County'),
3322 ),
3323 );
3324 }
3325 return $addressFields;
3326 }
3327
3328 /*
3329 * Do AlterDisplay processing on Address Fields
3330 */
3331 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3332 $criteriaQueryParams = CRM_Report_Utils_Report::getPreviewCriteriaQueryParams($this->_defaults, $this->_params);
3333 $entryFound = FALSE;
3334 // handle country
3335 if (array_key_exists('civicrm_address_country_id', $row)) {
3336 if ($value = $row['civicrm_address_country_id']) {
3337 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
3338 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
3339 "reset=1&force=1&{$criteriaQueryParams}&" .
3340 "country_id_op=in&country_id_value={$value}",
3341 $this->_absoluteUrl, $this->_id
3342 );
3343 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3344 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3345 array(1 => $urltxt)
3346 );
3347 }
3348
3349 $entryFound = TRUE;
3350 }
3351 if (array_key_exists('civicrm_address_county_id', $row)) {
3352 if ($value = $row['civicrm_address_county_id']) {
3353 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant::county($value, FALSE);
3354 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
3355 "reset=1&force=1&{$criteriaQueryParams}&" .
3356 "county_id_op=in&county_id_value={$value}",
3357 $this->_absoluteUrl, $this->_id
3358 );
3359 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3360 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3361 array(1 => $urltxt)
3362 );
3363 }
3364 $entryFound = TRUE;
3365 }
3366 // handle state province
3367 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3368 if ($value = $row['civicrm_address_state_province_id']) {
3369 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
3370
3371 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
3372 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3373 $this->_absoluteUrl, $this->_id
3374 );
3375 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3376 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3377 array(1 => $urltxt)
3378 );
3379 }
3380 $entryFound = TRUE;
3381 }
3382
3383 return $entryFound;
3384 }
3385
3386 /*
3387 * Adjusts dates passed in to YEAR() for fiscal year.
3388 */
3389 function fiscalYearOffset($fieldName) {
3390 $config = CRM_Core_Config::singleton();
3391 $fy = $config->fiscalYearStart;
3392 if (CRM_Utils_Array::value('yid_op', $this->_params) == 'calendar' || ($fy['d'] == 1 && $fy['M'] == 1)) {
3393 return "YEAR( $fieldName )";
3394 }
3395 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ? (" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3396 }
3397
3398 /*
3399 * Add Address into From Table if required
3400 */
3401 function addAddressFromClause() {
3402 // include address field if address column is to be included
3403 if ((isset($this->_addressField) &&
3404 $this->_addressField
3405 ) ||
3406 $this->isTableSelected('civicrm_address')
3407 ) {
3408 $this->_from .= "
3409 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3410 ON ({$this->_aliases['civicrm_contact']}.id =
3411 {$this->_aliases['civicrm_address']}.contact_id) AND
3412 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3413 }
3414 }
3415
850e4640
E
3416 /**
3417 * Add Phone into From Table if required
3418 */
3419 function addPhoneFromClause() {
3420 // include address field if address column is to be included
3421 if ($this->isTableSelected('civicrm_phone')
3422 ) {
3423 $this->_from .= "
3424 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3425 ON ({$this->_aliases['civicrm_contact']}.id =
3426 {$this->_aliases['civicrm_phone']}.contact_id) AND
3427 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3428 }
3429 }
3430
3431 /**
3432 * Get phone columns to add to array
3433 * @param array $options
3434 * - prefix Prefix to add to table (in case of more than one instance of the table)
3435 * - prefix_label Label to give columns from this phone table instance
3436 * @return array phone columns definition
3437 */
3438 function getPhoneColumns($options = array()){
3439 $defaultOptions = array(
3440 'prefix' => '',
3441 'prefix_label' => '',
3442 );
3443
3444 $options = array_merge($defaultOptions,$options);
3445
3446 $fields = array(
3447 $options['prefix'] . 'civicrm_phone' => array(
3448 'dao' => 'CRM_Core_DAO_Phone',
3449 'fields' => array(
3450 $options['prefix'] . 'phone' => array(
3451 'title' => ts($options['prefix_label'] . 'Phone'),
3452 'name' => 'phone'
3453 ),
3454 ),
3455 ),
3456 );
3457 return $fields;
3458 }
3459
3460 /**
3461 * Get address columns to add to array
3462 * @param array $options
3463 * - prefix Prefix to add to table (in case of more than one instance of the table)
3464 * - prefix_label Label to give columns from this address table instance
3465 * @return array address columns definition
3466 */
3467 function getAddressColumns($options = array()){
3468 $defaultOptions = array(
3469 'prefix' => '',
3470 'prefix_label' => '',
3471 'group_by' => TRUE,
3472 'order_by' => TRUE,
3473 'filters' => TRUE,
3474 'defaults' => array(
3475 ),
3476 );
3477 $options = array_merge($defaultOptions,$options);
3478 return $this->addAddressFields(
3479 $options['group_by'],
3480 $options['order_by'],
3481 $options['filters'],
3482 $options['defaults']
3483 );
3484
3485 }
3486
6a488035
TO
3487 function add2group($groupID) {
3488 if (is_numeric($groupID) && isset($this->_aliases['civicrm_contact'])) {
3489 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3490 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select);
3491
3492 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3493 $dao = CRM_Core_DAO::executeQuery($sql);
3494
3495 $contact_ids = array();
3496 // Add resulting contacts to group
3497 while ($dao->fetch()) {
3498 if ($dao->addtogroup_contact_id) {
3499 $contact_ids[$dao->addtogroup_contact_id] = $dao->addtogroup_contact_id;
3500 }
3501 }
3502
3503 if ( !empty($contact_ids) ) {
3504 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
3505 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3506 }
3507 else {
3508 CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
3509 }
3510 }
3511 }
46065582
PJ
3512
3513 /* function used for showing charts on print screen */
3514 static function uploadChartImage() {
3515 // upload strictly for '.png' images
d04d4eef
PJ
3516 $name = trim(basename(CRM_Utils_Request::retrieve('name', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET')));
3517 if (preg_match('/\.png$/', $name)) {
46065582
PJ
3518 //
3519 // POST data is usually string data, but we are passing a RAW .png
3520 // so PHP is a bit confused and $_POST is empty. But it has saved
3521 // the raw bits into $HTTP_RAW_POST_DATA
3522 //
3523 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3524
3525 // prepare the directory
3526 $config = CRM_Core_Config::singleton();
3527 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir) . '/openFlashChart/';
3528 if (!file_exists($defaultPath)) {
3529 mkdir($defaultPath, 0777, TRUE);
3530 }
3531
3532 // full path to the saved image including filename
d04d4eef 3533 $destination = $defaultPath . $name;
46065582
PJ
3534
3535 //write and save
3536 $jfh = fopen($destination, 'w') or die("can't open file");
3537 fwrite($jfh, $httpRawPostData);
3538 fclose($jfh);
3539 CRM_Utils_System::civiExit();
3540 }
3541 }
232624b1 3542}