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