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