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