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