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