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