Merge pull request #2135 from pratik-joshi/CRM-13861
[civicrm-core.git] / CRM / Report / Form.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.4 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2013 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2013
32 * $Id$
33 *
34 */
35 class CRM_Report_Form extends CRM_Core_Form {
36 CONST ROW_COUNT_LIMIT = 50;
37
38 /**
39 * Operator types - used for displaying filter elements
40 */
41 CONST
42 OP_INT = 1,
43 OP_STRING = 2,
44 OP_DATE = 4,
45 OP_DATETIME = 5,
46 OP_FLOAT = 8,
47 OP_SELECT = 64,
48 OP_MULTISELECT = 65,
49 OP_MULTISELECT_SEPARATOR = 66,
50 OP_MONTH = 128;
51
52 /**
53 * The id of the report instance
54 *
55 * @var integer
56 */
57 protected $_id;
58
59 /**
60 * The id of the report template
61 *
62 * @var integer;
63 */
64 protected $_templateID;
65
66 /**
67 * The report title
68 *
69 * @var string
70 */
71 protected $_title;
72 protected $_noFields = FALSE;
73
74 /**
75 * The set of all columns in the report. An associative array
76 * with column name as the key and attribues as the value
77 *
78 * @var array
79 */
80 protected $_columns = array();
81
82 /**
83 * The set of filters in the report
84 *
85 * @var array
86 */
87 protected $_filters = array();
88
89 /**
90 * The set of optional columns in the report
91 *
92 * @var array
93 */
94 protected $_options = array();
95
96 protected $_defaults = array();
97
98 /*
99 * By default most reports hide contact id.
100 * Setting this to true makes it available
101 */
102 protected $_exposeContactID = TRUE;
103
104 /**
105 * Set of statistic fields
106 *
107 * @var array
108 */
109 protected $_statFields = array();
110
111 /**
112 * Set of statistics data
113 *
114 * @var array
115 */
116 protected $_statistics = array();
117
118 /**
119 * List of fields not to be repeated during display
120 *
121 * @var array
122 */
123 protected $_noRepeats = array();
124
125 /**
126 * List of fields not to be displayed
127 *
128 * @var array
129 */
130 protected $_noDisplay = array();
131
132 /**
133 * Object type that a custom group extends
134 *
135 * @var null
136 */
137 protected $_customGroupExtends = NULL;
138 protected $_customGroupExtendsJoin = array();
139 protected $_customGroupFilters = TRUE;
140 protected $_customGroupGroupBy = FALSE;
141 protected $_customGroupJoin = 'LEFT JOIN';
142
143 /**
144 * build tags filter
145 *
146 */
147 protected $_tagFilter = FALSE;
148
149 /**
150 * build groups filter
151 *
152 */
153 protected $_groupFilter = FALSE;
154
155 /**
156 * Navigation fields
157 *
158 * @var array
159 */
160 public $_navigation = array();
161
162 public $_drilldownReport = array();
163
164 /**
165 * An attribute for checkbox/radio form field layout
166 *
167 * @var array
168 */
169 protected $_fourColumnAttribute = array(
170 '</td><td width="25%">', '</td><td width="25%">',
171 '</td><td width="25%">', '</tr><tr><td>',
172 );
173
174 protected $_force = 1;
175
176 protected $_params = NULL;
177 protected $_formValues = NULL;
178 protected $_instanceValues = NULL;
179
180 protected $_instanceForm = FALSE;
181 protected $_criteriaForm = FALSE;
182
183 protected $_instanceButtonName = NULL;
184 protected $_createNewButtonName = NULL;
185 protected $_printButtonName = NULL;
186 protected $_pdfButtonName = NULL;
187 protected $_csvButtonName = NULL;
188 protected $_groupButtonName = NULL;
189 protected $_chartButtonName = NULL;
190 protected $_csvSupported = TRUE;
191 protected $_add2groupSupported = TRUE;
192 protected $_groups = NULL;
193 protected $_grandFlag = FALSE;
194 protected $_rowsFound = NULL;
195 protected $_selectAliases = array();
196 protected $_rollup = NULL;
197 protected $_limit = NULL;
198 protected $_sections = NULL;
199 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
200 protected $_absoluteUrl = FALSE;
201
202 /**
203 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
204 *
205 * @var boolean
206 */
207 protected $_storeResultSet = FALSE;
208
209 /**
210 * When _storeResultSet Flag is set use this var to store result set in form of array
211 *
212 * @var boolean
213 */
214 protected $_resultSet = array();
215
216 /**
217 * To what frequency group-by a date column
218 *
219 * @var array
220 */
221 protected $_groupByDateFreq = array(
222 'MONTH' => 'Month',
223 'YEARWEEK' => 'Week',
224 'QUARTER' => 'Quarter',
225 'YEAR' => 'Year',
226 );
227
228 /**
229 * Variables to hold the acl inner join and where clause
230 */
231 protected $_aclFrom = NULL;
232 protected $_aclWhere = NULL;
233
234 /**
235 * Array of DAO tables having columns included in SELECT or ORDER BY clause
236 *
237 * @var array
238 */
239 protected $_selectedTables;
240
241 public $_having = NULL;
242 public $_select = NULL;
243 public $_selectClauses = array();
244 public $_columnHeaders = array();
245 public $_orderBy = NULL;
246 public $_orderByFields = array();
247 public $_orderByArray = array();
248 public $_groupBy = NULL;
249 public $_whereClauses = array();
250 public $_havingClauses = array();
251
252 /**
253 * Variable to hold the currency alias
254 */
255 protected $_currencyColumn = NULL;
256
257 /**
258 *
259 */
260 function __construct() {
261 parent::__construct();
262
263 // build tag filter
264 if ($this->_tagFilter) {
265 $this->buildTagFilter();
266 }
267 if ($this->_exposeContactID) {
268 if (array_key_exists('civicrm_contact', $this->_columns)) {
269 $this->_columns['civicrm_contact']['fields']['exposed_id'] = array(
270 'name' => 'id',
271 'title' => 'Contact ID',
272 'no_repeat' => TRUE,
273 );
274 }
275 }
276
277 if ($this->_groupFilter) {
278 $this->buildGroupFilter();
279 }
280
281 // Get all custom groups
282 $allGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id');
283
284 // Get the custom groupIds for which the user has VIEW permission
285 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
286 // and addCustomDataToColumns() will allow access to all custom groups.
287 $permCustomGroupIds = array();
288 if (!CRM_Core_Permission::check('access all custom data')) {
289 $permCustomGroupIds = CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_custom_group', $allGroups, NULL);
290 // do not allow custom data for reports if user doesn't have
291 // permission to access custom data.
292 if (!empty($this->_customGroupExtends) && empty($permCustomGroupIds)) {
293 $this->_customGroupExtends = array();
294 }
295 }
296
297 // merge custom data columns to _columns list, if any
298 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
299
300 // add / modify display columns, filters ..etc
301 CRM_Utils_Hook::alterReportVar('columns', $this->_columns, $this);
302
303 //assign currencyColumn variable to tpl
304 $this->assign('currencyColumn', $this->_currencyColumn);
305 }
306
307 function preProcessCommon() {
308 $this->_force =
309 CRM_Utils_Request::retrieve(
310 'force',
311 'Boolean',
312 CRM_Core_DAO::$_nullObject
313 );
314
315 $this->_section = CRM_Utils_Request::retrieve('section', 'Integer', CRM_Core_DAO::$_nullObject);
316
317 $this->assign('section', $this->_section);
318 CRM_Core_Region::instance('page-header')->add(array(
319 'markup' => sprintf('<!-- Report class: [%s] -->', htmlentities(get_class($this))),
320 ));
321
322 $this->_id = $this->get('instanceId');
323 if (!$this->_id) {
324 $this->_id = CRM_Report_Utils_Report::getInstanceID();
325 if (!$this->_id) {
326 $this->_id = CRM_Report_Utils_Report::getInstanceIDForPath();
327 }
328 }
329
330 // set qfkey so that pager picks it up and use it in the "Next > Last >>" links.
331 // FIXME: Note setting it in $_GET doesn't work, since pager generates link based on QUERY_STRING
332 $_SERVER['QUERY_STRING'] .= "&qfKey={$this->controller->_key}";
333
334 if ($this->_id) {
335 $this->assign('instanceId', $this->_id);
336 $params = array('id' => $this->_id);
337 $this->_instanceValues = array();
338 CRM_Core_DAO::commonRetrieve('CRM_Report_DAO_ReportInstance',
339 $params,
340 $this->_instanceValues
341 );
342 if (empty($this->_instanceValues)) {
343 CRM_Core_Error::fatal("Report could not be loaded.");
344 }
345
346 if (!empty($this->_instanceValues['permission']) &&
347 (!(CRM_Core_Permission::check($this->_instanceValues['permission']) ||
348 CRM_Core_Permission::check('administer Reports')
349 ))
350 ) {
351 CRM_Utils_System::permissionDenied();
352 CRM_Utils_System::civiExit();
353 }
354
355 $formValues = CRM_Utils_Array::value('form_values', $this->_instanceValues);
356 if ($formValues) {
357 $this->_formValues = unserialize($formValues);
358 }
359 else {
360 $this->_formValues = NULL;
361 }
362
363 // lets always do a force if reset is found in the url.
364 if (CRM_Utils_Array::value('reset', $_REQUEST)) {
365 $this->_force = 1;
366 }
367
368 // set the mode
369 $this->assign('mode', 'instance');
370 }
371 else {
372 list($optionValueID, $optionValue) = CRM_Report_Utils_Report::getValueIDFromUrl();
373 $instanceCount = CRM_Report_Utils_Report::getInstanceCount($optionValue);
374 if (($instanceCount > 0) && $optionValueID) {
375 $this->assign('instanceUrl',
376 CRM_Utils_System::url('civicrm/report/list',
377 "reset=1&ovid=$optionValueID"
378 )
379 );
380 }
381 if ($optionValueID) {
382 $this->_description = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_OptionValue', $optionValueID, 'description');
383 }
384
385 // set the mode
386 $this->assign('mode', 'template');
387 }
388
389 // lets display the Report Settings section
390 $this->_instanceForm = $this->_force || $this->_id || (!empty($_POST));
391
392 // Do not display Report Settings section if administer Reports permission is absent OR
393 // if report instance is reserved and administer reserved reports absent
394 if (!CRM_Core_Permission::check('administer Reports') ||
395 ($this->_instanceValues['is_reserved'] && !CRM_Core_Permission::check('administer reserved reports'))) {
396 $this->_instanceForm = FALSE;
397 }
398
399 $this->assign('criteriaForm', FALSE);
400 // Display Report Criteria section if user has access Report Criteria OR administer Reports AND report instance is not reserved
401 if (CRM_Core_Permission::check('administer Reports') || CRM_Core_Permission::check('access Report Criteria')) {
402 if (!$this->_instanceValues['is_reserved'] || CRM_Core_Permission::check('administer reserved reports')) {
403 $this->assign('criteriaForm', TRUE);
404 $this->_criteriaForm = TRUE;
405 }
406 }
407
408 $this->_instanceButtonName = $this->getButtonName('submit', 'save');
409 $this->_createNewButtonName = $this->getButtonName('submit', 'next');
410 $this->_printButtonName = $this->getButtonName('submit', 'print');
411 $this->_pdfButtonName = $this->getButtonName('submit', 'pdf');
412 $this->_csvButtonName = $this->getButtonName('submit', 'csv');
413 $this->_groupButtonName = $this->getButtonName('submit', 'group');
414 $this->_chartButtonName = $this->getButtonName('submit', 'chart');
415 }
416
417 function addBreadCrumb() {
418 $breadCrumbs =
419 array(
420 array(
421 'title' => ts('Report Templates'),
422 'url' => CRM_Utils_System::url('civicrm/admin/report/template/list', 'reset=1'),
423 )
424 );
425
426 CRM_Utils_System::appendBreadCrumb($breadCrumbs);
427 }
428
429 function preProcess() {
430 $this->preProcessCommon();
431
432 if (!$this->_id) {
433 $this->addBreadCrumb();
434 }
435
436 foreach ($this->_columns as $tableName => $table) {
437 // set alias
438 if (!isset($table['alias'])) {
439 $this->_columns[$tableName]['alias'] = substr($tableName, 8) . '_civireport';
440 }
441 else {
442 $this->_columns[$tableName]['alias'] = $table['alias'] . '_civireport';
443 }
444
445 $this->_aliases[$tableName] = $this->_columns[$tableName]['alias'];
446
447 $daoOrBaoName = NULL;
448 // higher preference to bao object
449 if (array_key_exists('bao', $table)) {
450 $daoOrBaoName = $table['bao'];
451 $expFields = $daoOrBaoName::exportableFields( );
452 }
453 elseif (array_key_exists('dao', $table)){
454 $daoOrBaoName = $table['dao'];
455 $expFields = $daoOrBaoName::export( );
456 }
457 else{
458 $expFields = array();
459 }
460
461 $doNotCopy = array('required');
462
463 $fieldGroups = array('fields', 'filters', 'group_bys', 'order_bys');
464 foreach ($fieldGroups as $fieldGrp) {
465 if (CRM_Utils_Array::value($fieldGrp, $table) && is_array($table[$fieldGrp])) {
466 foreach ($table[$fieldGrp] as $fieldName => $field) {
467 // $name is the field name used to reference the BAO/DAO export fields array
468 $name = isset($field['name']) ? $field['name'] : $fieldName;
469
470 // Sometimes the field name key in the BAO/DAO export fields array is
471 // different from the actual database field name.
472 // Unset $field['name'] so that actual database field name can be obtained
473 // from the BAO/DAO export fields array.
474 unset($field['name']);
475
476 if (array_key_exists($name, $expFields)) {
477 foreach ($doNotCopy as $dnc) {
478 // unset the values we don't want to be copied.
479 unset($expFields[$name][$dnc]);
480 }
481 if (empty($field)) {
482 $this->_columns[$tableName][$fieldGrp][$fieldName] = $expFields[$name];
483 }
484 else {
485 foreach ($expFields[$name] as $property => $val) {
486 if (!array_key_exists($property, $field)) {
487 $this->_columns[$tableName][$fieldGrp][$fieldName][$property] = $val;
488 }
489 }
490 }
491 }
492
493 // fill other vars
494 if (CRM_Utils_Array::value('no_repeat', $field)) {
495 $this->_noRepeats[] = "{$tableName}_{$fieldName}";
496 }
497 if (CRM_Utils_Array::value('no_display', $field)) {
498 $this->_noDisplay[] = "{$tableName}_{$fieldName}";
499 }
500
501 // set alias = table-name, unless already set
502 $alias = isset($field['alias']) ? $field['alias'] : (isset($this->_columns[$tableName]['alias']) ?
503 $this->_columns[$tableName]['alias'] : $tableName
504 );
505 $this->_columns[$tableName][$fieldGrp][$fieldName]['alias'] = $alias;
506
507 // set name = fieldName, unless already set
508 if (!isset($this->_columns[$tableName][$fieldGrp][$fieldName]['name'])) {
509 $this->_columns[$tableName][$fieldGrp][$fieldName]['name'] = $name;
510 }
511
512 // set dbAlias = alias.name, unless already set
513 if (!isset($this->_columns[$tableName][$fieldGrp][$fieldName]['dbAlias'])) {
514 $this->_columns[$tableName][$fieldGrp][$fieldName]['dbAlias'] = $alias . '.' . $this->_columns[$tableName][$fieldGrp][$fieldName]['name'];
515 }
516
517 // a few auto fills for filters
518 if ($fieldGrp == 'filters') {
519 // fill operator types
520 if (!array_key_exists('operatorType', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
521 switch (CRM_Utils_Array::value('type', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
522 case CRM_Utils_Type::T_MONEY:
523 case CRM_Utils_Type::T_FLOAT:
524 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
525 break;
526 case CRM_Utils_Type::T_INT:
527 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_INT;
528 break;
529 case CRM_Utils_Type::T_DATE:
530 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE;
531 break;
532 case CRM_Utils_Type::T_BOOLEAN:
533 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT;
534 if (!array_key_exists('options', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
535 $this->_columns[$tableName][$fieldGrp][$fieldName]['options'] =
536 array('' => ts('Any'), '0' => ts('No'), '1' => ts('Yes'));
537 }
538 break;
539 default:
540 if ($daoOrBaoName &&
541 (array_key_exists('pseudoconstant', $this->_columns[$tableName][$fieldGrp][$fieldName])
542 || array_key_exists('enumValues', $this->_columns[$tableName][$fieldGrp][$fieldName]))
543 ) {
544 // with multiple options operator-type is generally multi-select
545 $this->_columns[$tableName][$fieldGrp][$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
546 if (!array_key_exists('options', $this->_columns[$tableName][$fieldGrp][$fieldName])) {
547 // fill options
548 $this->_columns[$tableName][$fieldGrp][$fieldName]['options'] = CRM_Core_PseudoConstant::get($daoOrBaoName, $fieldName);
549 }
550 }
551 break;
552 }
553 }
554 }
555 }
556 }
557 }
558
559 // copy filters to a separate handy variable
560 if (array_key_exists('filters', $table)) {
561 $this->_filters[$tableName] = $this->_columns[$tableName]['filters'];
562 }
563
564 if (array_key_exists('group_bys', $table)) {
565 $groupBys[$tableName] = $this->_columns[$tableName]['group_bys'];
566 }
567
568 if (array_key_exists('fields', $table)) {
569 $reportFields[$tableName] = $this->_columns[$tableName]['fields'];
570 }
571 }
572
573 if ($this->_force) {
574 $this->setDefaultValues(FALSE);
575 }
576
577 CRM_Report_Utils_Get::processFilter($this->_filters, $this->_defaults);
578 CRM_Report_Utils_Get::processGroupBy($groupBys, $this->_defaults);
579 CRM_Report_Utils_Get::processFields($reportFields, $this->_defaults);
580 CRM_Report_Utils_Get::processChart($this->_defaults);
581
582 if ($this->_force) {
583 $this->_formValues = $this->_defaults;
584 $this->postProcess();
585 }
586 }
587
588 function setDefaultValues($freeze = TRUE) {
589 $freezeGroup = array();
590
591 // FIXME: generalizing form field naming conventions would reduce
592 // lots of lines below.
593 foreach ($this->_columns as $tableName => $table) {
594 if (array_key_exists('fields', $table)) {
595 foreach ($table['fields'] as $fieldName => $field) {
596 if (!CRM_Utils_Array::value('no_display', $field)) {
597 if (isset($field['required'])) {
598 // set default
599 $this->_defaults['fields'][$fieldName] = 1;
600
601 if ($freeze) {
602 // find element object, so that we could use quickform's freeze method
603 // for required elements
604 $obj = $this->getElementFromGroup("fields", $fieldName);
605 if ($obj) {
606 $freezeGroup[] = $obj;
607 }
608 }
609 }
610 elseif (isset($field['default'])) {
611 $this->_defaults['fields'][$fieldName] = $field['default'];
612 }
613 }
614 }
615 }
616
617 if (array_key_exists('group_bys', $table)) {
618 foreach ($table['group_bys'] as $fieldName => $field) {
619 if (isset($field['default'])) {
620 if (CRM_Utils_Array::value('frequency', $field)) {
621 $this->_defaults['group_bys_freq'][$fieldName] = 'MONTH';
622 }
623 $this->_defaults['group_bys'][$fieldName] = $field['default'];
624 }
625 }
626 }
627 if (array_key_exists('filters', $table)) {
628 foreach ($table['filters'] as $fieldName => $field) {
629 if (isset($field['default'])) {
630 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
631 if(is_array($field['default'])){
632 $this->_defaults["{$fieldName}_from"] = CRM_Utils_Array::value('from', $field['default']);
633 $this->_defaults["{$fieldName}_to"] = CRM_Utils_Array::value('to', $field['default']);
634 $this->_defaults["{$fieldName}_relative"] = 0;
635 }
636 else{
637 $this->_defaults["{$fieldName}_relative"] = $field['default'];
638 }
639 }
640 else {
641 $this->_defaults["{$fieldName}_value"] = $field['default'];
642 }
643 }
644 //assign default value as "in" for multiselect
645 //operator, To freeze the select element
646 if (CRM_Utils_Array::value('operatorType', $field) == CRM_Report_FORM::OP_MULTISELECT) {
647 $this->_defaults["{$fieldName}_op"] = 'in';
648 }
649 elseif (CRM_Utils_Array::value('operatorType', $field) == CRM_Report_FORM::OP_MULTISELECT_SEPARATOR) {
650 $this->_defaults["{$fieldName}_op"] = 'mhas';
651 }
652 elseif ($op = CRM_Utils_Array::value('default_op', $field)) {
653 $this->_defaults["{$fieldName}_op"] = $op;
654 }
655 }
656 }
657
658 if (
659 array_key_exists('order_bys', $table) &&
660 is_array($table['order_bys'])
661 ) {
662 if (!array_key_exists('order_bys', $this->_defaults)) {
663 $this->_defaults['order_bys'] = array();
664 }
665 foreach ($table['order_bys'] as $fieldName => $field) {
666 if (
667 CRM_Utils_Array::value('default', $field) ||
668 CRM_Utils_Array::value('default_order', $field) ||
669 CRM_Utils_Array::value('default_is_section', $field) ||
670 CRM_Utils_Array::value('default_weight', $field)
671 ) {
672 $order_by = array(
673 'column' => $fieldName,
674 'order' => CRM_Utils_Array::value('default_order', $field, 'ASC'),
675 'section' => CRM_Utils_Array::value('default_is_section', $field, 0),
676 );
677
678 if (CRM_Utils_Array::value('default_weight', $field)) {
679 $this->_defaults['order_bys'][(int) $field['default_weight']] = $order_by;
680 }
681 else {
682 array_unshift($this->_defaults['order_bys'], $order_by);
683 }
684 }
685 }
686 }
687
688 foreach ($this->_options as $fieldName => $field) {
689 if (isset($field['default'])) {
690 $this->_defaults['options'][$fieldName] = $field['default'];
691 }
692 }
693 }
694
695 if (!empty($this->_submitValues)) {
696 $this->preProcessOrderBy($this->_submitValues);
697 }
698 else {
699 $this->preProcessOrderBy($this->_defaults);
700 }
701
702 // lets finish freezing task here itself
703 if (!empty($freezeGroup)) {
704 foreach ($freezeGroup as $elem) {
705 $elem->freeze();
706 }
707 }
708
709 if ($this->_formValues) {
710 $this->_defaults = array_merge($this->_defaults, $this->_formValues);
711 }
712
713 if ($this->_instanceValues) {
714 $this->_defaults = array_merge($this->_defaults, $this->_instanceValues);
715 }
716
717 CRM_Report_Form_Instance::setDefaultValues($this, $this->_defaults);
718
719 return $this->_defaults;
720 }
721
722 function getElementFromGroup($group, $grpFieldName) {
723 $eleObj = $this->getElement($group);
724 foreach ($eleObj->_elements as $index => $obj) {
725 if ($grpFieldName == $obj->_attributes['name']) {
726 return $obj;
727 }
728 }
729 return FALSE;
730 }
731
732 function addColumns() {
733 $options = array();
734 $colGroups = NULL;
735 foreach ($this->_columns as $tableName => $table) {
736 if (array_key_exists('fields', $table)) {
737 foreach ($table['fields'] as $fieldName => $field) {
738 $groupTitle = '';
739 if (!CRM_Utils_Array::value('no_display', $field)) {
740 foreach ( array('table', 'field') as $var) {
741 if (!empty(${$var}['grouping'])) {
742 if (!is_array(${$var}['grouping'])) {
743 $tableName = ${$var}['grouping'];
744 } else {
745 $tableName = array_keys(${$var}['grouping']);
746 $tableName = $tableName[0];
747 $groupTitle = array_values(${$var}['grouping']);
748 $groupTitle = $groupTitle[0];
749 }
750 }
751 }
752
753 if (!$groupTitle && isset($table['group_title'])) {
754 $groupTitle = $table['group_title'];
755 }
756
757 $colGroups[$tableName]['fields'][$fieldName] = CRM_Utils_Array::value('title', $field);
758 if ($groupTitle && !CRM_Utils_Array::value('group_title', $colGroups[$tableName])) {
759 $colGroups[$tableName]['group_title'] = $groupTitle;
760 }
761
762 $options[$fieldName] = CRM_Utils_Array::value('title', $field);
763 }
764 }
765 }
766 }
767
768 $this->addCheckBox("fields", ts('Select Columns'), $options, NULL,
769 NULL, NULL, NULL, $this->_fourColumnAttribute, TRUE
770 );
771 $this->assign('colGroups', $colGroups);
772 }
773
774 function addFilters() {
775 $options = $filters = array();
776 $count = 1;
777 foreach ($this->_filters as $table => $attributes) {
778 foreach ($attributes as $fieldName => $field) {
779 // get ready with option value pair
780 // @ 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
781 // would be useful
782 $operations = $this->getOperationPair(
783 CRM_Utils_Array::value('operatorType', $field),
784 $fieldName);
785
786 $filters[$table][$fieldName] = $field;
787
788 switch (CRM_Utils_Array::value('operatorType', $field)) {
789 case CRM_Report_Form::OP_MONTH:
790 if (!array_key_exists('options', $field) || !is_array($field['options']) || empty($field['options'])) {
791 // If there's no option list for this filter, define one.
792 $field['options'] = array(
793 1 => ts('January'),
794 2 => ts('February'),
795 3 => ts('March'),
796 4 => ts('April'),
797 5 => ts('May'),
798 6 => ts('June'),
799 7 => ts('July'),
800 8 => ts('August'),
801 9 => ts('September'),
802 10 => ts('October'),
803 11 => ts('November'),
804 12 => ts('December'),
805 );
806 // Add this option list to this column _columns. This is
807 // required so that filter statistics show properly.
808 $this->_columns[$table]['filters'][$fieldName]['options'] = $field['options'];
809 }
810 case CRM_Report_FORM::OP_MULTISELECT:
811 case CRM_Report_FORM::OP_MULTISELECT_SEPARATOR:
812 // assume a multi-select field
813 if (!empty($field['options'])) {
814 $element = $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
815 if (count($operations) <= 1) {
816 $element->freeze();
817 }
818 $select = $this->addElement('select', "{$fieldName}_value", NULL,
819 $field['options'], array(
820 'size' => 4,
821 'style' => 'min-width:250px',
822 )
823 );
824 $select->setMultiple(TRUE);
825 }
826 break;
827
828 case CRM_Report_FORM::OP_SELECT:
829 // assume a select field
830 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations);
831 if (!empty($field['options']))
832 $this->addElement('select', "{$fieldName}_value", NULL, $field['options']);
833 break;
834
835 case CRM_Report_FORM::OP_DATE:
836 // build datetime fields
837 CRM_Core_Form_Date::buildDateRange($this, $fieldName, $count, '_from','_to', 'From:', FALSE, $operations);
838 $count++;
839 break;
840
841 case CRM_Report_FORM::OP_DATETIME:
842 // build datetime fields
843 CRM_Core_Form_Date::buildDateRange($this, $fieldName, $count, '_from', '_to', 'From:', FALSE, $operations, 'searchDate', true);
844 $count++;
845 break;
846
847 case CRM_Report_FORM::OP_INT:
848 case CRM_Report_FORM::OP_FLOAT:
849 // and a min value input box
850 $this->add('text', "{$fieldName}_min", ts('Min'));
851 // and a max value input box
852 $this->add('text', "{$fieldName}_max", ts('Max'));
853 default:
854 // default type is string
855 $this->addElement('select', "{$fieldName}_op", ts('Operator:'), $operations,
856 array('onchange' => "return showHideMaxMinVal( '$fieldName', this.value );")
857 );
858 // we need text box for value input
859 $this->add('text', "{$fieldName}_value", NULL);
860 break;
861 }
862 }
863 }
864 $this->assign('filters', $filters);
865 }
866
867 function addOptions() {
868 if (!empty($this->_options)) {
869 // FIXME: For now lets build all elements as checkboxes.
870 // Once we clear with the format we can build elements based on type
871
872 $options = array();
873 foreach ($this->_options as $fieldName => $field) {
874 if ($field['type'] == 'select') {
875 $this->addElement('select', "{$fieldName}", $field['title'], $field['options']);
876 }
877 else if ($field['type'] == 'checkbox') {
878 $options[$field['title']] = $fieldName;
879 $this->addCheckBox($fieldName, NULL,
880 $options, NULL,
881 NULL, NULL, NULL, $this->_fourColumnAttribute
882 );
883 }
884 }
885 }
886 $this->assign('otherOptions', $this->_options);
887 }
888
889 function addChartOptions() {
890 if (!empty($this->_charts)) {
891 $this->addElement('select', "charts", ts('Chart'), $this->_charts, array('onchange' => 'disablePrintPDFButtons(this.value);'));
892 $this->assign('charts', $this->_charts);
893 $this->addElement('submit', $this->_chartButtonName, ts('View'));
894 }
895 }
896
897 function addGroupBys() {
898 $options = $freqElements = array();
899
900 foreach ($this->_columns as $tableName => $table) {
901 if (array_key_exists('group_bys', $table)) {
902 foreach ($table['group_bys'] as $fieldName => $field) {
903 if (!empty($field)) {
904 $options[$field['title']] = $fieldName;
905 if (CRM_Utils_Array::value('frequency', $field)) {
906 $freqElements[$field['title']] = $fieldName;
907 }
908 }
909 }
910 }
911 }
912 $this->addCheckBox("group_bys", ts('Group by columns'), $options, NULL,
913 NULL, NULL, NULL, $this->_fourColumnAttribute
914 );
915 $this->assign('groupByElements', $options);
916
917 foreach ($freqElements as $name) {
918 $this->addElement('select', "group_bys_freq[$name]",
919 ts('Frequency'), $this->_groupByDateFreq
920 );
921 }
922 }
923
924 function addOrderBys() {
925 $options = array();
926 foreach ($this->_columns as $tableName => $table) {
927
928 // Report developer may define any column to order by; include these as order-by options
929 if (array_key_exists('order_bys', $table)) {
930 foreach ($table['order_bys'] as $fieldName => $field) {
931 if (!empty($field)) {
932 $options[$fieldName] = $field['title'];
933 }
934 }
935 }
936
937 /* Add searchable custom fields as order-by options, if so requested
938 * (These are already indexed, so allowing to order on them is cheap.)
939 */
940
941
942 if ($this->_autoIncludeIndexedFieldsAsOrderBys && array_key_exists('extends', $table) && !empty($table['extends'])) {
943 foreach ($table['fields'] as $fieldName => $field) {
944 if (!CRM_Utils_Array::value('no_display', $field)) {
945 $options[$fieldName] = $field['title'];
946 }
947 }
948 }
949 }
950
951 asort($options);
952
953 $this->assign('orderByOptions', $options);
954
955 if (!empty($options)) {
956 $options = array(
957 '-' => ' - none - ') + $options;
958 for ($i = 1; $i <= 5; $i++) {
959 $this->addElement('select', "order_bys[{$i}][column]", ts('Order by Column'), $options);
960 $this->addElement('select', "order_bys[{$i}][order]", ts('Order by Order'), array('ASC' => 'Ascending', 'DESC' => 'Descending'));
961 $this->addElement('checkbox', "order_bys[{$i}][section]", ts('Order by Section'), FALSE, array('id' => "order_by_section_$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 $this->_sections[$orderByField['tplField']] = $orderByField;
2159 }
2160 }
2161 }
2162 }
2163
2164 $this->_orderByArray = $orderBys;
2165
2166 $this->assign('sections', $this->_sections);
2167 }
2168
2169 function unselectedSectionColumns() {
2170 $selectColumns = array();
2171 foreach ($this->_columns as $tableName => $table) {
2172 if (array_key_exists('fields', $table)) {
2173 foreach ($table['fields'] as $fieldName => $field) {
2174 if (CRM_Utils_Array::value('required', $field) ||
2175 CRM_Utils_Array::value($fieldName, $this->_params['fields'])
2176 ) {
2177
2178 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2179 }
2180 }
2181 }
2182 }
2183
2184 if (is_array($this->_sections)) {
2185 return array_diff_key($this->_sections, $selectColumns);
2186 }
2187 else {
2188 return array();
2189 }
2190 }
2191
2192 function buildRows($sql, &$rows) {
2193 $dao = CRM_Core_DAO::executeQuery($sql);
2194 if (!is_array($rows)) {
2195 $rows = array();
2196 }
2197
2198 // use this method to modify $this->_columnHeaders
2199 $this->modifyColumnHeaders();
2200
2201 $unselectedSectionColumns = $this->unselectedSectionColumns();
2202
2203 while ($dao->fetch()) {
2204 $row = array();
2205 foreach ($this->_columnHeaders as $key => $value) {
2206 if (property_exists($dao, $key)) {
2207 $row[$key] = $dao->$key;
2208 }
2209 }
2210
2211 // section headers not selected for display need to be added to row
2212 foreach ($unselectedSectionColumns as $key => $values) {
2213 if (property_exists($dao, $key)) {
2214 $row[$key] = $dao->$key;
2215 }
2216 }
2217
2218 $rows[] = $row;
2219 }
2220 }
2221
2222 /**
2223 * When "order by" fields are marked as sections, this assigns to the template
2224 * an array of total counts for each section. This data is used by the Smarty
2225 * plugin {sectionTotal}
2226 */
2227 function sectionTotals() {
2228
2229 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2230 if (empty($this->_selectAliases)) {
2231 return;
2232 }
2233
2234 if (!empty($this->_sections)) {
2235 // build the query with no LIMIT clause
2236 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select);
2237 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2238
2239 // pull section aliases out of $this->_sections
2240 $sectionAliases = array_keys($this->_sections);
2241
2242 $ifnulls = array();
2243 foreach (array_merge($sectionAliases, $this->_selectAliases) as $alias) {
2244 $ifnulls[] = "ifnull($alias, '') as $alias";
2245 }
2246
2247 /* Group (un-limited) report by all aliases and get counts. This might
2248 * be done more efficiently when the contents of $sql are known, ie. by
2249 * overriding this method in the report class.
2250 */
2251
2252
2253 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2254
2255 // initialize array of total counts
2256 $totals = array();
2257 $dao = CRM_Core_DAO::executeQuery($query);
2258 while ($dao->fetch()) {
2259
2260 // let $this->_alterDisplay translate any integer ids to human-readable values.
2261 $rows[0] = $dao->toArray();
2262 $this->alterDisplay($rows);
2263 $row = $rows[0];
2264
2265 // add totals for all permutations of section values
2266 $values = array();
2267 $i = 1;
2268 $aliasCount = count($sectionAliases);
2269 foreach ($sectionAliases as $alias) {
2270 $values[] = $row[$alias];
2271 $key = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values);
2272 if ($i == $aliasCount) {
2273 // the last alias is the lowest-level section header; use count as-is
2274 $totals[$key] = $dao->ct;
2275 }
2276 else {
2277 // other aliases are higher level; roll count into their total
2278 $totals[$key] += $dao->ct;
2279 }
2280 }
2281 }
2282 $this->assign('sectionTotals', $totals);
2283 }
2284 }
2285
2286 function modifyColumnHeaders() {
2287 // use this method to modify $this->_columnHeaders
2288 }
2289
2290 function doTemplateAssignment(&$rows) {
2291 $this->assign_by_ref('columnHeaders', $this->_columnHeaders);
2292 $this->assign_by_ref('rows', $rows);
2293 $this->assign('statistics', $this->statistics($rows));
2294 }
2295
2296 // override this method to build your own statistics
2297 function statistics(&$rows) {
2298 $statistics = array();
2299
2300 $count = count($rows);
2301
2302 if ($this->_rollup && ($this->_rollup != '') && $this->_grandFlag) {
2303 $count++;
2304 }
2305
2306 $this->countStat($statistics, $count);
2307
2308 $this->groupByStat($statistics);
2309
2310 $this->filterStat($statistics);
2311
2312 return $statistics;
2313 }
2314
2315 function countStat(&$statistics, $count) {
2316 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2317 'value' => $count,
2318 );
2319
2320 if ($this->_rowsFound && ($this->_rowsFound > $count)) {
2321 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2322 'value' => $this->_rowsFound,
2323 );
2324 }
2325 }
2326
2327 function groupByStat(&$statistics) {
2328 if (CRM_Utils_Array::value('group_bys', $this->_params) &&
2329 is_array($this->_params['group_bys']) &&
2330 !empty($this->_params['group_bys'])
2331 ) {
2332 foreach ($this->_columns as $tableName => $table) {
2333 if (array_key_exists('group_bys', $table)) {
2334 foreach ($table['group_bys'] as $fieldName => $field) {
2335 if (CRM_Utils_Array::value($fieldName, $this->_params['group_bys'])) {
2336 $combinations[] = $field['title'];
2337 }
2338 }
2339 }
2340 }
2341 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2342 'value' => implode(' & ', $combinations),
2343 );
2344 }
2345 }
2346
2347 function filterStat(&$statistics) {
2348 foreach ($this->_columns as $tableName => $table) {
2349 if (array_key_exists('filters', $table)) {
2350 foreach ($table['filters'] as $fieldName => $field) {
2351 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE && CRM_Utils_Array::value('operatorType', $field) != CRM_Report_Form::OP_MONTH) {
2352 list($from, $to) =
2353 $this->getFromTo(
2354 CRM_Utils_Array::value("{$fieldName}_relative", $this->_params),
2355 CRM_Utils_Array::value("{$fieldName}_from", $this->_params),
2356 CRM_Utils_Array::value("{$fieldName}_to", $this->_params),
2357 CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params),
2358 CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params)
2359 );
2360 $from_time_format = CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params) ? 'h' : 'd';
2361 $from = CRM_Utils_Date::customFormat($from, null, array($from_time_format));
2362
2363 $to_time_format = CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params) ? 'h' : 'd';
2364 $to = CRM_Utils_Date::customFormat($to, null, array($to_time_format));
2365
2366 if ($from || $to) {
2367 $statistics['filters'][] = array(
2368 'title' => $field['title'],
2369 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2370 );
2371 }
2372 elseif (in_array($rel = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params),
2373 array_keys($this->getOperationPair(CRM_Report_FORM::OP_DATE))
2374 )) {
2375 $pair = $this->getOperationPair(CRM_Report_FORM::OP_DATE);
2376 $statistics['filters'][] = array(
2377 'title' => $field['title'],
2378 'value' => $pair[$rel],
2379 );
2380 }
2381 }
2382 else {
2383 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2384 $value = NULL;
2385 if ($op) {
2386 $pair = $this->getOperationPair(
2387 CRM_Utils_Array::value('operatorType', $field),
2388 $fieldName
2389 );
2390 $min = CRM_Utils_Array::value("{$fieldName}_min", $this->_params);
2391 $max = CRM_Utils_Array::value("{$fieldName}_max", $this->_params);
2392 $val = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
2393 if (in_array($op, array(
2394 'bw', 'nbw')) && ($min || $max)) {
2395 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2396 }
2397 elseif ($op == 'nll' || $op == 'nnll') {
2398 $value = $pair[$op];
2399 }
2400 elseif (is_array($val) && (!empty($val))) {
2401 $options = CRM_Utils_Array::value('options', $field, array());
2402 foreach ($val as $key => $valIds) {
2403 if (isset($options[$valIds])) {
2404 $val[$key] = $options[$valIds];
2405 }
2406 }
2407 $pair[$op] = (count($val) == 1) ? (($op == 'notin') ? ts('Is Not') : ts('Is')) : CRM_Utils_Array::value($op, $pair);
2408 $val = implode(', ', $val);
2409 $value = "{$pair[$op]} " . $val;
2410 }
2411 elseif (!is_array($val) && (!empty($val) || $val == '0') && isset($field['options']) &&
2412 is_array($field['options']) && !empty($field['options'])
2413 ) {
2414 $value = CRM_Utils_Array::value($op, $pair) . " " . CRM_Utils_Array::value($val, $field['options'], $val);
2415 }
2416 elseif ($val) {
2417 $value = CRM_Utils_Array::value($op, $pair) . " " . $val;
2418 }
2419 }
2420 if ($value) {
2421 $statistics['filters'][] = array('title' => CRM_Utils_Array::value('title', $field),
2422 'value' => $value,
2423 );
2424 }
2425 }
2426 }
2427 }
2428 }
2429 }
2430
2431 function endPostProcess(&$rows = NULL) {
2432 if ( $this->_storeResultSet ) {
2433 $this->_resultSet = $rows;
2434 }
2435
2436 if ($this->_outputMode == 'print' ||
2437 $this->_outputMode == 'pdf' ||
2438 $this->_sendmail
2439 ) {
2440
2441 $content = $this->compileContent();
2442 $url = CRM_Utils_System::url("civicrm/report/instance/{$this->_id}",
2443 "reset=1", TRUE
2444 );
2445
2446 if ($this->_sendmail) {
2447 $config = CRM_Core_Config::singleton();
2448 $attachments = array();
2449
2450 if ($this->_outputMode == 'csv') {
2451 $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'];
2452
2453 $csvFullFilename = $config->templateCompileDir . CRM_Utils_File::makeFileName('CiviReport.csv');
2454 $csvContent = CRM_Report_Utils_Report::makeCsv($this, $rows);
2455 file_put_contents($csvFullFilename, $csvContent);
2456 $attachments[] = array(
2457 'fullPath' => $csvFullFilename,
2458 'mime_type' => 'text/csv',
2459 'cleanName' => 'CiviReport.csv',
2460 );
2461 }
2462 if ($this->_outputMode == 'pdf') {
2463 // generate PDF content
2464 $pdfFullFilename = $config->templateCompileDir . CRM_Utils_File::makeFileName('CiviReport.pdf');
2465 file_put_contents($pdfFullFilename,
2466 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf",
2467 TRUE, array('orientation' => 'landscape')
2468 )
2469 );
2470 // generate Email Content
2471 $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'];
2472
2473 $attachments[] = array(
2474 'fullPath' => $pdfFullFilename,
2475 'mime_type' => 'application/pdf',
2476 'cleanName' => 'CiviReport.pdf',
2477 );
2478 }
2479
2480 if (CRM_Report_Utils_Report::mailReport($content, $this->_id,
2481 $this->_outputMode, $attachments
2482 )) {
2483 CRM_Core_Session::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2484 }
2485 else {
2486 CRM_Core_Session::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2487 }
2488
2489 CRM_Utils_System::redirect(CRM_Utils_System::url(CRM_Utils_System::currentPath(), 'reset=1'));
2490 }
2491 elseif ($this->_outputMode == 'print') {
2492 echo $content;
2493 }
2494 else {
2495 if ($chartType = CRM_Utils_Array::value('charts', $this->_params)) {
2496 $config = CRM_Core_Config::singleton();
2497 //get chart image name
2498 $chartImg = $this->_chartId . '.png';
2499 //get image url path
2500 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL) . 'openFlashChart/';
2501 $uploadUrl .= $chartImg;
2502 //get image doc path to overwrite
2503 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir) . 'openFlashChart/' . $chartImg;
2504 //Load the image
2505 $chart = imagecreatefrompng($uploadUrl);
2506 //convert it into formattd png
2507 header('Content-type: image/png');
2508 //overwrite with same image
2509 imagepng($chart, $uploadImg);
2510 //delete the object
2511 imagedestroy($chart);
2512 }
2513 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2514 }
2515 CRM_Utils_System::civiExit();
2516 }
2517 elseif ($this->_outputMode == 'csv') {
2518 CRM_Report_Utils_Report::export2csv($this, $rows);
2519 }
2520 elseif ($this->_outputMode == 'group') {
2521 $group = $this->_params['groups'];
2522 $this->add2group($group);
2523 }
2524 elseif ($this->_instanceButtonName == $this->controller->getButtonName()) {
2525 CRM_Report_Form_Instance::postProcess($this);
2526 }
2527 elseif ($this->_createNewButtonName == $this->controller->getButtonName() ||
2528 $this->_outputMode == 'create_report' ) {
2529 $this->_createNew = TRUE;
2530 CRM_Report_Form_Instance::postProcess($this);
2531 }
2532 }
2533
2534 function storeResultSet() {
2535 $this->_storeResultSet = TRUE;
2536 }
2537
2538 function getResultSet() {
2539 return $this->_resultSet;
2540 }
2541
2542 /*
2543 * Get Template file name - use default form template if a specific one has not been set up for this report
2544 *
2545 */
2546 function getTemplateFileName(){
2547 $defaultTpl = parent::getTemplateFileName();
2548 $template = CRM_Core_Smarty::singleton();
2549 if (!$template->template_exists($defaultTpl)) {
2550 $defaultTpl = 'CRM/Report/Form.tpl';
2551 }
2552 return $defaultTpl;
2553 }
2554
2555 /*
2556 * Compile the report content
2557 *
2558 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2559 */
2560 function compileContent(){
2561 $templateFile = $this->getHookedTemplateFileName();
2562 return $this->_formValues['report_header'] . CRM_Core_Form::$_template->fetch($templateFile) . $this->_formValues['report_footer'];
2563 }
2564
2565
2566 function postProcess() {
2567 // get ready with post process params
2568 $this->beginPostProcess();
2569
2570 // build query
2571 $sql = $this->buildQuery();
2572
2573 // build array of result based on column headers. This method also allows
2574 // modifying column headers before using it to build result set i.e $rows.
2575 $rows = array();
2576 $this->buildRows($sql, $rows);
2577
2578 // format result set.
2579 $this->formatDisplay($rows);
2580
2581 // assign variables to templates
2582 $this->doTemplateAssignment($rows);
2583
2584 // do print / pdf / instance stuff if needed
2585 $this->endPostProcess($rows);
2586 }
2587
2588 function limit($rowCount = self::ROW_COUNT_LIMIT) {
2589 // lets do the pager if in html mode
2590 $this->_limit = NULL;
2591 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
2592 $this->_select = str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select);
2593
2594 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
2595
2596 if (!$pageId && !empty($_POST)) {
2597 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2598 $pageId = max((int)@$_POST['crmPID_B'], 1);
2599 }
2600 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2601 $pageId = max((int)@$_POST['crmPID'], 1);
2602 }
2603 unset($_POST['crmPID_B'], $_POST['crmPID']);
2604 }
2605
2606 $pageId = $pageId ? $pageId : 1;
2607 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
2608 $offset = ($pageId - 1) * $rowCount;
2609
2610 $offset = CRM_Utils_Type::escape($offset, 'Int');
2611 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
2612
2613 $this->_limit = " LIMIT $offset, $rowCount";
2614 return array($offset, $rowCount);
2615 }
2616 }
2617
2618 function setPager($rowCount = self::ROW_COUNT_LIMIT) {
2619 if ($this->_limit && ($this->_limit != '')) {
2620 $sql = "SELECT FOUND_ROWS();";
2621 $this->_rowsFound = CRM_Core_DAO::singleValueQuery($sql);
2622 $params = array(
2623 'total' => $this->_rowsFound,
2624 'rowCount' => $rowCount,
2625 'status' => ts('Records') . ' %%StatusMessage%%',
2626 'buttonBottom' => 'PagerBottomButton',
2627 'buttonTop' => 'PagerTopButton',
2628 'pageID' => $this->get(CRM_Utils_Pager::PAGE_ID),
2629 );
2630
2631 $pager = new CRM_Utils_Pager($params);
2632 $this->assign_by_ref('pager', $pager);
2633 }
2634 }
2635
2636 function whereGroupClause($field, $value, $op) {
2637
2638 $smartGroupQuery = "";
2639
2640 $group = new CRM_Contact_DAO_Group();
2641 $group->is_active = 1;
2642 $group->find();
2643 $smartGroups = array();
2644 while ($group->fetch()) {
2645 if (in_array($group->id, $this->_params['gid_value']) && $group->saved_search_id) {
2646 $smartGroups[] = $group->id;
2647 }
2648 }
2649
2650 CRM_Contact_BAO_GroupContactCache::check($smartGroups);
2651
2652 $smartGroupQuery = '';
2653 if (!empty($smartGroups)) {
2654 $smartGroups = implode(',', $smartGroups);
2655 $smartGroupQuery = " UNION DISTINCT
2656 SELECT DISTINCT smartgroup_contact.contact_id
2657 FROM civicrm_group_contact_cache smartgroup_contact
2658 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2659 }
2660
2661 $sqlOp = $this->getSQLOperator($op);
2662 if (!is_array($value)) {
2663 $value = array($value);
2664 }
2665 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2666
2667 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2668 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2669 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2670 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2671 {$smartGroupQuery} ) ";
2672 }
2673
2674 function whereTagClause($field, $value, $op) {
2675 // not using left join in query because if any contact
2676 // belongs to more than one tag, results duplicate
2677 // entries.
2678 $sqlOp = $this->getSQLOperator($op);
2679 if (!is_array($value)) {
2680 $value = array($value);
2681 }
2682 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2683
2684 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2685 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2686 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2687 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2688 }
2689
2690 function buildACLClause($tableAlias = 'contact_a') {
2691 list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
2692 }
2693
2694 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
2695 if (empty($this->_customGroupExtends)) {
2696 return;
2697 }
2698 if (!is_array($this->_customGroupExtends)) {
2699 $this->_customGroupExtends = array($this->_customGroupExtends);
2700 }
2701 $customGroupWhere = '';
2702 if (!empty($permCustomGroupIds)) {
2703 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
2704 }
2705 $sql = "
2706 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
2707 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
2708 FROM civicrm_custom_group cg
2709 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
2710 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
2711 {$customGroupWhere}
2712 cg.is_active = 1 AND
2713 cf.is_active = 1 AND
2714 cf.is_searchable = 1
2715 ORDER BY cg.weight, cf.weight";
2716 $customDAO = CRM_Core_DAO::executeQuery($sql);
2717
2718 $curTable = NULL;
2719 while ($customDAO->fetch()) {
2720 if ($customDAO->table_name != $curTable) {
2721 $curTable = $customDAO->table_name;
2722 $curFields = $curFilters = array();
2723
2724 // dummy dao object
2725 $this->_columns[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
2726 $this->_columns[$curTable]['extends'] = $customDAO->extends;
2727 $this->_columns[$curTable]['grouping'] = $customDAO->table_name;
2728 $this->_columns[$curTable]['group_title'] = $customDAO->title;
2729
2730 foreach (array(
2731 'fields', 'filters', 'group_bys') as $colKey) {
2732 if (!array_key_exists($colKey, $this->_columns[$curTable])) {
2733 $this->_columns[$curTable][$colKey] = array();
2734 }
2735 }
2736 }
2737 $fieldName = 'custom_' . $customDAO->cf_id;
2738
2739 if ($addFields) {
2740 // this makes aliasing work in favor
2741 $curFields[$fieldName] = array(
2742 'name' => $customDAO->column_name,
2743 'title' => $customDAO->label,
2744 'dataType' => $customDAO->data_type,
2745 'htmlType' => $customDAO->html_type,
2746 );
2747 }
2748 if ($this->_customGroupFilters) {
2749 // this makes aliasing work in favor
2750 $curFilters[$fieldName] = array(
2751 'name' => $customDAO->column_name,
2752 'title' => $customDAO->label,
2753 'dataType' => $customDAO->data_type,
2754 'htmlType' => $customDAO->html_type,
2755 );
2756 }
2757
2758 switch ($customDAO->data_type) {
2759 case 'Date':
2760 // filters
2761 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE;
2762 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_DATE;
2763 // CRM-6946, show time part for datetime date fields
2764 if ($customDAO->time_format) {
2765 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_TIMESTAMP;
2766 }
2767 break;
2768
2769 case 'Boolean':
2770 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT;
2771 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
2772 1 => ts('Yes'),
2773 0 => ts('No'),
2774 );
2775 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
2776 break;
2777
2778 case 'Int':
2779 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_INT;
2780 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
2781 break;
2782
2783 case 'Money':
2784 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
2785 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_MONEY;
2786 break;
2787
2788 case 'Float':
2789 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
2790 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_FLOAT;
2791 break;
2792
2793 case 'String':
2794 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2795
2796 if (!empty($customDAO->option_group_id)) {
2797 if (in_array($customDAO->html_type, array(
2798 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
2799 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
2800 }
2801 else {
2802 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
2803 }
2804 if ($this->_customGroupFilters) {
2805 $curFilters[$fieldName]['options'] = array();
2806 $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')));
2807 while ($ogDAO->fetch()) {
2808 $curFilters[$fieldName]['options'][$ogDAO->value] = $ogDAO->label;
2809 }
2810 }
2811 }
2812 break;
2813
2814 case 'StateProvince':
2815 if (in_array($customDAO->html_type, array(
2816 'Multi-Select State/Province'))) {
2817 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
2818 }
2819 else {
2820 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
2821 }
2822 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::stateProvince();
2823 break;
2824
2825 case 'Country':
2826 if (in_array($customDAO->html_type, array(
2827 'Multi-Select Country'))) {
2828 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
2829 }
2830 else {
2831 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
2832 }
2833 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::country();
2834 break;
2835
2836 case 'ContactReference':
2837 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2838 $curFilters[$fieldName]['name'] = 'display_name';
2839 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2840
2841 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2842 $curFields[$fieldName]['name'] = 'display_name';
2843 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
2844 break;
2845
2846 default:
2847 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2848 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
2849 }
2850
2851 if (!array_key_exists('type', $curFields[$fieldName])) {
2852 $curFields[$fieldName]['type'] = CRM_Utils_Array::value('type', $curFilters[$fieldName], array());
2853 }
2854
2855 if ($addFields) {
2856 $this->_columns[$curTable]['fields'] = array_merge($this->_columns[$curTable]['fields'], $curFields);
2857 }
2858 if ($this->_customGroupFilters) {
2859 $this->_columns[$curTable]['filters'] = array_merge($this->_columns[$curTable]['filters'], $curFilters);
2860 }
2861 if ($this->_customGroupGroupBy) {
2862 $this->_columns[$curTable]['group_bys'] = array_merge($this->_columns[$curTable]['group_bys'], $curFields);
2863 }
2864 }
2865 }
2866
2867 function customDataFrom() {
2868 if (empty($this->_customGroupExtends)) {
2869 return;
2870 }
2871 $mapper = CRM_Core_BAO_CustomQuery::$extendsMap;
2872
2873 foreach ($this->_columns as $table => $prop) {
2874 if (substr($table, 0, 13) == 'civicrm_value' || substr($table, 0, 12) == 'custom_value') {
2875 $extendsTable = $mapper[$prop['extends']];
2876
2877 // check field is in params
2878 if (!$this->isFieldSelected($prop)) {
2879 continue;
2880 }
2881 $baseJoin = CRM_Utils_Array::value($prop['extends'], $this->_customGroupExtendsJoin, "{$this->_aliases[$extendsTable]}.id");
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 = {$baseJoin}";
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 }