Merge pull request #3542 from davecivicrm/CRM-14857
[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 elseif (!empty($field['membership_org']) && $clause) {
1499 $clause = $this->whereMembershipOrgClause($field, $value, $op);
1500 }
1501 elseif (!empty($field['membership_type']) && $clause) {
1502 $clause = $this->whereMembershipTypeClause($field, $value, $op);
1503 }
1504 return $clause;
1505 }
1506
1507 /**
1508 * @param $fieldName
1509 * @param $relative
1510 * @param $from
1511 * @param $to
1512 * @param null $type
1513 * @param null $fromTime
1514 * @param null $toTime
1515 *
1516 * @return null|string
1517 */
1518 function dateClause($fieldName,
1519 $relative, $from, $to, $type = NULL, $fromTime = NULL, $toTime = NULL
1520 ) {
1521 $clauses = array();
1522 if (in_array($relative, array_keys($this->getOperationPair(CRM_Report_Form::OP_DATE)))) {
1523 $sqlOP = $this->getSQLOperator($relative);
1524 return "( {$fieldName} {$sqlOP} )";
1525 }
1526
1527 list($from, $to) = $this->getFromTo($relative, $from, $to, $fromTime, $toTime);
1528
1529 if ($from) {
1530 $from = ($type == CRM_Utils_Type::T_DATE) ? substr($from, 0, 8) : $from;
1531 $clauses[] = "( {$fieldName} >= $from )";
1532 }
1533
1534 if ($to) {
1535 $to = ($type == CRM_Utils_Type::T_DATE) ? substr($to, 0, 8) : $to;
1536 $clauses[] = "( {$fieldName} <= {$to} )";
1537 }
1538
1539 if (!empty($clauses)) {
1540 return implode(' AND ', $clauses);
1541 }
1542
1543 return NULL;
1544 }
1545 /**
1546 * @todo - could not find any instances where this is called
1547 * @param unknown_type $relative
1548 * @param String $from
1549 * @param String_type $to
1550 * @return string|NULL
1551 */
1552 function dateDisplay($relative, $from, $to) {
1553 list($from, $to) = $this->getFromTo($relative, $from, $to);
1554
1555 if ($from) {
1556 $clauses[] = CRM_Utils_Date::customFormat($from, NULL, array('m', 'M'));
1557 }
1558 else {
1559 $clauses[] = 'Past';
1560 }
1561
1562 if ($to) {
1563 $clauses[] = CRM_Utils_Date::customFormat($to, NULL, array('m', 'M'));
1564 }
1565 else {
1566 $clauses[] = 'Today';
1567 }
1568
1569 if (!empty($clauses)) {
1570 return implode(' - ', $clauses);
1571 }
1572
1573 return NULL;
1574 }
1575
1576 /**
1577 * @param $relative
1578 * @param $from
1579 * @param $to
1580 * @param null $fromtime
1581 * @param null $totime
1582 *
1583 * @return array
1584 */
1585 function getFromTo($relative, $from, $to, $fromtime = NULL, $totime = NULL) {
1586 if (empty($totime)) {
1587 $totime = '235959';
1588 }
1589 //FIX ME not working for relative
1590 if ($relative) {
1591 list($term, $unit) = CRM_Utils_System::explode('.', $relative, 2);
1592 $dateRange = CRM_Utils_Date::relativeToAbsolute($term, $unit);
1593 $from = substr($dateRange['from'], 0, 8);
1594 //Take only Date Part, Sometime Time part is also present in 'to'
1595 $to = substr($dateRange['to'], 0, 8);
1596 }
1597 $from = CRM_Utils_Date::processDate($from, $fromtime);
1598 $to = CRM_Utils_Date::processDate($to, $totime);
1599 return array($from, $to);
1600 }
1601
1602 /**
1603 * @param $rows
1604 */
1605 function alterDisplay(&$rows) {
1606 // custom code to alter rows
1607 }
1608
1609 /**
1610 * @param $rows
1611 */
1612 function alterCustomDataDisplay(&$rows) {
1613 // custom code to alter rows having custom values
1614 if (empty($this->_customGroupExtends)) {
1615 return;
1616 }
1617
1618 $customFieldIds = array();
1619 foreach ($this->_params['fields'] as $fieldAlias => $value) {
1620 if ($fieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
1621 $customFieldIds[$fieldAlias] = $fieldId;
1622 }
1623 }
1624 if (empty($customFieldIds)) {
1625 return;
1626 }
1627
1628 $customFields = $fieldValueMap = array();
1629 $customFieldCols = array('column_name', 'data_type', 'html_type', 'option_group_id', 'id');
1630
1631 // skip for type date and ContactReference since date format is already handled
1632 $query = "
1633 SELECT cg.table_name, cf." . implode(", cf.", $customFieldCols) . ", ov.value, ov.label
1634 FROM civicrm_custom_field cf
1635 INNER JOIN civicrm_custom_group cg ON cg.id = cf.custom_group_id
1636 LEFT JOIN civicrm_option_value ov ON cf.option_group_id = ov.option_group_id
1637 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
1638 cg.is_active = 1 AND
1639 cf.is_active = 1 AND
1640 cf.is_searchable = 1 AND
1641 cf.data_type NOT IN ('ContactReference', 'Date') AND
1642 cf.id IN (" . implode(",", $customFieldIds) . ")";
1643
1644 $dao = CRM_Core_DAO::executeQuery($query);
1645 while ($dao->fetch()) {
1646 foreach ($customFieldCols as $key) {
1647 $customFields[$dao->table_name . '_custom_' . $dao->id][$key] = $dao->$key;
1648 }
1649 if ($dao->option_group_id) {
1650 $fieldValueMap[$dao->option_group_id][$dao->value] = $dao->label;
1651 }
1652 }
1653 $dao->free();
1654
1655 $entryFound = FALSE;
1656 foreach ($rows as $rowNum => $row) {
1657 foreach ($row as $tableCol => $val) {
1658 if (array_key_exists($tableCol, $customFields)) {
1659 $rows[$rowNum][$tableCol] = $this->formatCustomValues($val, $customFields[$tableCol], $fieldValueMap);
1660 $entryFound = TRUE;
1661 }
1662 }
1663
1664 // skip looking further in rows, if first row itself doesn't
1665 // have the column we need
1666 if (!$entryFound) {
1667 break;
1668 }
1669 }
1670 }
1671
1672 /**
1673 * @param $value
1674 * @param $customField
1675 * @param $fieldValueMap
1676 *
1677 * @return float|string
1678 */
1679 function formatCustomValues($value, $customField, $fieldValueMap) {
1680 if (CRM_Utils_System::isNull($value)) {
1681 return;
1682 }
1683
1684 $htmlType = $customField['html_type'];
1685
1686 switch ($customField['data_type']) {
1687 case 'Boolean':
1688 if ($value == '1') {
1689 $retValue = ts('Yes');
1690 }
1691 else {
1692 $retValue = ts('No');
1693 }
1694 break;
1695
1696 case 'Link':
1697 $retValue = CRM_Utils_System::formatWikiURL($value);
1698 break;
1699
1700 case 'File':
1701 $retValue = $value;
1702 break;
1703
1704 case 'Memo':
1705 $retValue = $value;
1706 break;
1707
1708 case 'Float':
1709 if ($htmlType == 'Text') {
1710 $retValue = (float)$value;
1711 break;
1712 }
1713 case 'Money':
1714 if ($htmlType == 'Text') {
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724 $retValue = CRM_Utils_Money::format($value, NULL, '%a');
1725 break;
1726 }
1727 case 'String':
1728 case 'Int':
1729 if (in_array($htmlType, array(
1730 'Text', 'TextArea'))) {
1731 $retValue = $value;
1732 break;
1733 }
1734 case 'StateProvince':
1735 case 'Country':
1736
1737 switch ($htmlType) {
1738 case 'Multi-Select Country':
1739 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1740 $customData = array();
1741 foreach ($value as $val) {
1742 if ($val) {
1743 $customData[] = CRM_Core_PseudoConstant::country($val, FALSE);
1744 }
1745 }
1746 $retValue = implode(', ', $customData);
1747 break;
1748
1749 case 'Select Country':
1750 $retValue = CRM_Core_PseudoConstant::country($value, FALSE);
1751 break;
1752
1753 case 'Select State/Province':
1754 $retValue = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
1755 break;
1756
1757 case 'Multi-Select State/Province':
1758 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1759 $customData = array();
1760 foreach ($value as $val) {
1761 if ($val) {
1762 $customData[] = CRM_Core_PseudoConstant::stateProvince($val, FALSE);
1763 }
1764 }
1765 $retValue = implode(', ', $customData);
1766 break;
1767
1768 case 'Select':
1769 case 'Radio':
1770 case 'Autocomplete-Select':
1771 $retValue = $fieldValueMap[$customField['option_group_id']][$value];
1772 break;
1773
1774 case 'CheckBox':
1775 case 'AdvMulti-Select':
1776 case 'Multi-Select':
1777 $value = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
1778 $customData = array();
1779 foreach ($value as $val) {
1780 if ($val) {
1781 $customData[] = $fieldValueMap[$customField['option_group_id']][$val];
1782 }
1783 }
1784 $retValue = implode(', ', $customData);
1785 break;
1786
1787 default:
1788 $retValue = $value;
1789 }
1790 break;
1791
1792 default:
1793 $retValue = $value;
1794 }
1795
1796 return $retValue;
1797 }
1798
1799 /**
1800 * @param $rows
1801 */
1802 function removeDuplicates(&$rows) {
1803 if (empty($this->_noRepeats)) {
1804 return;
1805 }
1806 $checkList = array();
1807
1808 foreach ($rows as $key => $list) {
1809 foreach ($list as $colName => $colVal) {
1810 if (array_key_exists($colName, $checkList) &&
1811 $checkList[$colName] == $colVal) {
1812 $rows[$key][$colName] = "";
1813 }
1814 if (in_array($colName, $this->_noRepeats)) {
1815 $checkList[$colName] = $colVal;
1816 }
1817 }
1818 }
1819 }
1820
1821 /**
1822 * @param $row
1823 * @param $fields
1824 * @param bool $subtotal
1825 */
1826 function fixSubTotalDisplay(&$row, $fields, $subtotal = TRUE) {
1827 foreach ($row as $colName => $colVal) {
1828 if (in_array($colName, $fields)) {
1829 $row[$colName] = $row[$colName];
1830 }
1831 elseif (isset($this->_columnHeaders[$colName])) {
1832 if ($subtotal) {
1833 $row[$colName] = "Subtotal";
1834 $subtotal = FALSE;
1835 }
1836 else {
1837 unset($row[$colName]);
1838 }
1839 }
1840 }
1841 }
1842
1843 /**
1844 * @param $rows
1845 *
1846 * @return bool
1847 */
1848 function grandTotal(&$rows) {
1849 if (!$this->_rollup || ($this->_rollup == '') ||
1850 ($this->_limit && count($rows) >= self::ROW_COUNT_LIMIT)
1851 ) {
1852 return FALSE;
1853 }
1854 $lastRow = array_pop($rows);
1855
1856 foreach ($this->_columnHeaders as $fld => $val) {
1857 if (!in_array($fld, $this->_statFields)) {
1858 if (!$this->_grandFlag) {
1859 $lastRow[$fld] = "Grand Total";
1860 $this->_grandFlag = TRUE;
1861 }
1862 else {
1863 $lastRow[$fld] = "";
1864 }
1865 }
1866 }
1867
1868 $this->assign('grandStat', $lastRow);
1869 return TRUE;
1870 }
1871
1872 /**
1873 * @param $rows
1874 * @param bool $pager
1875 */
1876 function formatDisplay(&$rows, $pager = TRUE) {
1877 // set pager based on if any limit was applied in the query.
1878 if ($pager) {
1879 $this->setPager();
1880 }
1881
1882 // allow building charts if any
1883 if (!empty($this->_params['charts']) && !empty($rows)) {
1884 $this->buildChart($rows);
1885 $this->assign('chartEnabled', TRUE);
1886 $this->_chartId = "{$this->_params['charts']}_" . ($this->_id ? $this->_id : substr(get_class($this), 16)) . '_' . session_id();
1887 $this->assign('chartId', $this->_chartId);
1888 }
1889
1890 // unset columns not to be displayed.
1891 foreach ($this->_columnHeaders as $key => $value) {
1892 if (!empty($value['no_display'])) {
1893 unset($this->_columnHeaders[$key]);
1894 }
1895 }
1896
1897 // unset columns not to be displayed.
1898 if (!empty($rows)) {
1899 foreach ($this->_noDisplay as $noDisplayField) {
1900 foreach ($rows as $rowNum => $row) {
1901 unset($this->_columnHeaders[$noDisplayField]);
1902 }
1903 }
1904 }
1905
1906 // build array of section totals
1907 $this->sectionTotals();
1908
1909 // process grand-total row
1910 $this->grandTotal($rows);
1911
1912 // use this method for formatting rows for display purpose.
1913 $this->alterDisplay($rows);
1914 CRM_Utils_Hook::alterReportVar('rows', $rows, $this);
1915
1916 // use this method for formatting custom rows for display purpose.
1917 $this->alterCustomDataDisplay($rows);
1918 }
1919
1920 /**
1921 * @param $rows
1922 */
1923 function buildChart(&$rows) {
1924 // override this method for building charts.
1925 }
1926
1927 // select() method below has been added recently (v3.3), and many of the report templates might
1928 // still be having their own select() method. We should fix them as and when encountered and move
1929 // towards generalizing the select() method below.
1930 function select() {
1931 $select = $this->_selectAliases = array();
1932
1933 foreach ($this->_columns as $tableName => $table) {
1934 if (array_key_exists('fields', $table)) {
1935 foreach ($table['fields'] as $fieldName => $field) {
1936 if ($tableName == 'civicrm_address') {
1937 $this->_addressField = TRUE;
1938 }
1939 if ($tableName == 'civicrm_email') {
1940 $this->_emailField = TRUE;
1941 }
1942 if ($tableName == 'civicrm_phone') {
1943 $this->_phoneField = TRUE;
1944 }
1945
1946 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
1947
1948 // 1. In many cases we want select clause to be built in slightly different way
1949 // for a particular field of a particular type.
1950 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
1951 // as needed.
1952 $selectClause = $this->selectClause($tableName, 'fields', $fieldName, $field);
1953 if ($selectClause) {
1954 $select[] = $selectClause;
1955 continue;
1956 }
1957
1958 // include statistics columns only if set
1959 if (!empty($field['statistics'])) {
1960 foreach ($field['statistics'] as $stat => $label) {
1961 $alias = "{$tableName}_{$fieldName}_{$stat}";
1962 switch (strtolower($stat)) {
1963 case 'max':
1964 case 'sum':
1965 $select[] = "$stat({$field['dbAlias']}) as $alias";
1966 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1967 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1968 $this->_statFields[$label] = $alias;
1969 $this->_selectAliases[] = $alias;
1970 break;
1971
1972 case 'count':
1973 $select[] = "COUNT({$field['dbAlias']}) as $alias";
1974 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1975 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
1976 $this->_statFields[$label] = $alias;
1977 $this->_selectAliases[] = $alias;
1978 break;
1979
1980 case 'count_distinct':
1981 $select[] = "COUNT(DISTINCT {$field['dbAlias']}) as $alias";
1982 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1983 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = CRM_Utils_Type::T_INT;
1984 $this->_statFields[$label] = $alias;
1985 $this->_selectAliases[] = $alias;
1986 break;
1987
1988 case 'avg':
1989 $select[] = "ROUND(AVG({$field['dbAlias']}),2) as $alias";
1990 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['title'] = $label;
1991 $this->_columnHeaders["{$tableName}_{$fieldName}_{$stat}"]['type'] = $field['type'];
1992 $this->_statFields[$label] = $alias;
1993 $this->_selectAliases[] = $alias;
1994 break;
1995 }
1996 }
1997 }
1998 else {
1999 $alias = "{$tableName}_{$fieldName}";
2000 $select[] = "{$field['dbAlias']} as $alias";
2001 $this->_columnHeaders["{$tableName}_{$fieldName}"]['title'] = CRM_Utils_Array::value('title', $field);
2002 $this->_columnHeaders["{$tableName}_{$fieldName}"]['type'] = CRM_Utils_Array::value('type', $field);
2003 $this->_selectAliases[] = $alias;
2004 }
2005 }
2006 }
2007 }
2008
2009 // select for group bys
2010 if (array_key_exists('group_bys', $table)) {
2011 foreach ($table['group_bys'] as $fieldName => $field) {
2012
2013 if ($tableName == 'civicrm_address') {
2014 $this->_addressField = TRUE;
2015 }
2016 if ($tableName == 'civicrm_email') {
2017 $this->_emailField = TRUE;
2018 }
2019 if ($tableName == 'civicrm_phone') {
2020 $this->_phoneField = TRUE;
2021 }
2022 // 1. In many cases we want select clause to be built in slightly different way
2023 // for a particular field of a particular type.
2024 // 2. This method when used should receive params by reference and modify $this->_columnHeaders
2025 // as needed.
2026 $selectClause = $this->selectClause($tableName, 'group_bys', $fieldName, $field);
2027 if ($selectClause) {
2028 $select[] = $selectClause;
2029 continue;
2030 }
2031
2032 if (!empty($this->_params['group_bys']) && !empty($this->_params['group_bys'][$fieldName]) && !empty($this->_params['group_bys_freq'])) {
2033 switch (CRM_Utils_Array::value($fieldName, $this->_params['group_bys_freq'])) {
2034 case 'YEARWEEK':
2035 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL WEEKDAY({$field['dbAlias']}) DAY) AS {$tableName}_{$fieldName}_start";
2036 $select[] = "YEARWEEK({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2037 $select[] = "WEEKOFYEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2038 $field['title'] = 'Week';
2039 break;
2040
2041 case 'YEAR':
2042 $select[] = "MAKEDATE(YEAR({$field['dbAlias']}), 1) AS {$tableName}_{$fieldName}_start";
2043 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2044 $select[] = "YEAR({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2045 $field['title'] = 'Year';
2046 break;
2047
2048 case 'MONTH':
2049 $select[] = "DATE_SUB({$field['dbAlias']}, INTERVAL (DAYOFMONTH({$field['dbAlias']})-1) DAY) as {$tableName}_{$fieldName}_start";
2050 $select[] = "MONTH({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2051 $select[] = "MONTHNAME({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2052 $field['title'] = 'Month';
2053 break;
2054
2055 case 'QUARTER':
2056 $select[] = "STR_TO_DATE(CONCAT( 3 * QUARTER( {$field['dbAlias']} ) -2 , '/', '1', '/', YEAR( {$field['dbAlias']} ) ), '%m/%d/%Y') AS {$tableName}_{$fieldName}_start";
2057 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_subtotal";
2058 $select[] = "QUARTER({$field['dbAlias']}) AS {$tableName}_{$fieldName}_interval";
2059 $field['title'] = 'Quarter';
2060 break;
2061 }
2062 // for graphs and charts -
2063 if (!empty($this->_params['group_bys_freq'][$fieldName])) {
2064 $this->_interval = $field['title'];
2065 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['title'] = $field['title'] . ' Beginning';
2066 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['type'] = $field['type'];
2067 $this->_columnHeaders["{$tableName}_{$fieldName}_start"]['group_by'] = $this->_params['group_bys_freq'][$fieldName];
2068
2069 // just to make sure these values are transfered to rows.
2070 // since we 'll need them for calculation purpose,
2071 // e.g making subtotals look nicer or graphs
2072 $this->_columnHeaders["{$tableName}_{$fieldName}_interval"] = array('no_display' => TRUE);
2073 $this->_columnHeaders["{$tableName}_{$fieldName}_subtotal"] = array('no_display' => TRUE);
2074 }
2075 }
2076 }
2077 }
2078 }
2079
2080 $this->_selectClauses = $select;
2081 $this->_select = "SELECT " . implode(', ', $select) . " ";
2082 }
2083
2084 /**
2085 * @param $tableName
2086 * @param $tableKey
2087 * @param $fieldName
2088 * @param $field
2089 *
2090 * @return bool
2091 */
2092 function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
2093 return FALSE;
2094 }
2095
2096 function where() {
2097 $this->storeWhereHavingClauseArray();
2098
2099 if (empty($this->_whereClauses)) {
2100 $this->_where = "WHERE ( 1 ) ";
2101 $this->_having = "";
2102 }
2103 else {
2104 $this->_where = "WHERE " . implode(' AND ', $this->_whereClauses);
2105 }
2106
2107 if ($this->_aclWhere) {
2108 $this->_where .= " AND {$this->_aclWhere} ";
2109 }
2110
2111 if (!empty($this->_havingClauses)) {
2112 // use this clause to construct group by clause.
2113 $this->_having = "HAVING " . implode(' AND ', $this->_havingClauses);
2114 }
2115 }
2116
2117 /**
2118 * Store Where clauses into an array - breaking out this step makes
2119 * over-riding more flexible as the clauses can be used in constructing a
2120 * temp table that may not be part of the final where clause or added
2121 * in other functions
2122 */
2123 function storeWhereHavingClauseArray(){
2124 foreach ($this->_columns as $tableName => $table) {
2125 if (array_key_exists('filters', $table)) {
2126 foreach ($table['filters'] as $fieldName => $field) {
2127 // respect pseudofield to filter spec so fields can be marked as
2128 // not to be handled here
2129 if(!empty($field['pseudofield'])){
2130 continue;
2131 }
2132 $clause = NULL;
2133 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE) {
2134 if (CRM_Utils_Array::value('operatorType', $field) == CRM_Report_Form::OP_MONTH) {
2135 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2136 $value = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
2137 if (is_array($value) && !empty($value)) {
2138 $clause = "(month({$field['dbAlias']}) $op (" . implode(', ', $value) . '))';
2139 }
2140 }
2141 else {
2142 $relative = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params);
2143 $from = CRM_Utils_Array::value("{$fieldName}_from", $this->_params);
2144 $to = CRM_Utils_Array::value("{$fieldName}_to", $this->_params);
2145 $fromTime = CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params);
2146 $toTime = CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params);
2147 $clause = $this->dateClause($field['dbAlias'], $relative, $from, $to, $field['type'], $fromTime, $toTime);
2148 }
2149 }
2150 else {
2151 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2152 if ($op) {
2153 $clause = $this->whereClause($field,
2154 $op,
2155 CRM_Utils_Array::value("{$fieldName}_value", $this->_params),
2156 CRM_Utils_Array::value("{$fieldName}_min", $this->_params),
2157 CRM_Utils_Array::value("{$fieldName}_max", $this->_params)
2158 );
2159 }
2160 }
2161
2162 if (!empty($clause)) {
2163 if (!empty($field['having'])) {
2164 $this->_havingClauses[] = $clause;
2165 }
2166 else {
2167 $this->_whereClauses[] = $clause;
2168 }
2169 }
2170 }
2171 }
2172 }
2173
2174 }
2175 function processReportMode() {
2176 $buttonName = $this->controller->getButtonName();
2177
2178 $output = CRM_Utils_Request::retrieve(
2179 'output',
2180 'String',
2181 CRM_Core_DAO::$_nullObject
2182 );
2183
2184 $this->_sendmail =
2185 CRM_Utils_Request::retrieve(
2186 'sendmail',
2187 'Boolean',
2188 CRM_Core_DAO::$_nullObject
2189 );
2190
2191 $this->_absoluteUrl = FALSE;
2192 $printOnly = FALSE;
2193 $this->assign('printOnly', FALSE);
2194
2195 if ($this->_printButtonName == $buttonName || $output == 'print' || ($this->_sendmail && !$output)) {
2196 $this->assign('printOnly', TRUE);
2197 $printOnly = TRUE;
2198 $this->assign('outputMode', 'print');
2199 $this->_outputMode = 'print';
2200 if ($this->_sendmail) {
2201 $this->_absoluteUrl = TRUE;
2202 }
2203 }
2204 elseif ($this->_pdfButtonName == $buttonName || $output == 'pdf') {
2205 $this->assign('printOnly', TRUE);
2206 $printOnly = TRUE;
2207 $this->assign('outputMode', 'pdf');
2208 $this->_outputMode = 'pdf';
2209 $this->_absoluteUrl = TRUE;
2210 }
2211 elseif ($this->_csvButtonName == $buttonName || $output == 'csv') {
2212 $this->assign('printOnly', TRUE);
2213 $printOnly = TRUE;
2214 $this->assign('outputMode', 'csv');
2215 $this->_outputMode = 'csv';
2216 $this->_absoluteUrl = TRUE;
2217 }
2218 elseif ($this->_groupButtonName == $buttonName || $output == 'group') {
2219 $this->assign('outputMode', 'group');
2220 $this->_outputMode = 'group';
2221 }
2222 elseif ($output == 'create_report' && $this->_criteriaForm) {
2223 $this->assign('outputMode', 'create_report');
2224 $this->_outputMode = 'create_report';
2225 }
2226 else {
2227 $this->assign('outputMode', 'html');
2228 $this->_outputMode = 'html';
2229 }
2230
2231 // Get today's date to include in printed reports
2232 if ($printOnly) {
2233 $reportDate = CRM_Utils_Date::customFormat(date('Y-m-d H:i'));
2234 $this->assign('reportDate', $reportDate);
2235 }
2236 }
2237
2238 function beginPostProcess() {
2239 $this->setParams($this->controller->exportValues($this->_name));
2240
2241 if (empty($this->_params) &&
2242 $this->_force
2243 ) {
2244 $this->setParams($this->_formValues);
2245 }
2246
2247 // hack to fix params when submitted from dashboard, CRM-8532
2248 // fields array is missing because form building etc is skipped
2249 // in dashboard mode for report
2250 //@todo - this could be done in the dashboard no we have a setter
2251 if (empty($this->_params['fields']) && !$this->_noFields) {
2252 $this->setParams($this->_formValues);
2253 }
2254
2255 $this->_formValues = $this->_params;
2256 if (CRM_Core_Permission::check('administer Reports') &&
2257 isset($this->_id) &&
2258 ($this->_instanceButtonName == $this->controller->getButtonName() . '_save' ||
2259 $this->_chartButtonName == $this->controller->getButtonName()
2260 )
2261 ) {
2262 $this->assign('updateReportButton', TRUE);
2263 }
2264 $this->processReportMode();
2265 $this->beginPostProcessCommon();
2266 }
2267
2268 /**
2269 * beginPostProcess function run in both report mode and non-report mode (api)
2270 */
2271 function beginPostProcessCommon() {
2272
2273 }
2274
2275 /**
2276 * @param bool $applyLimit
2277 *
2278 * @return string
2279 */
2280 function buildQuery($applyLimit = TRUE) {
2281 $this->select();
2282 $this->from();
2283 $this->customDataFrom();
2284 $this->where();
2285 $this->groupBy();
2286 $this->orderBy();
2287
2288 // order_by columns not selected for display need to be included in SELECT
2289 $unselectedSectionColumns = $this->unselectedSectionColumns();
2290 foreach ($unselectedSectionColumns as $alias => $section) {
2291 $this->_select .= ", {$section['dbAlias']} as {$alias}";
2292 }
2293
2294 if ($applyLimit && empty($this->_params['charts'])) {
2295 $this->limit();
2296 }
2297 CRM_Utils_Hook::alterReportVar('sql', $this, $this);
2298
2299 $sql = "{$this->_select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy} {$this->_limit}";
2300 return $sql;
2301 }
2302
2303 function groupBy() {
2304 $groupBys = array();
2305 if (!empty($this->_params['group_bys']) &&
2306 is_array($this->_params['group_bys']) &&
2307 !empty($this->_params['group_bys'])
2308 ) {
2309 foreach ($this->_columns as $tableName => $table) {
2310 if (array_key_exists('group_bys', $table)) {
2311 foreach ($table['group_bys'] as $fieldName => $field) {
2312 if (!empty($this->_params['group_bys'][$fieldName])) {
2313 $groupBys[] = $field['dbAlias'];
2314 }
2315 }
2316 }
2317 }
2318 }
2319
2320 if (!empty($groupBys)) {
2321 $this->_groupBy = "GROUP BY " . implode(', ', $groupBys);
2322 }
2323 }
2324
2325 function orderBy() {
2326 $this->_orderBy = "";
2327 $this->_sections = array();
2328 $this->storeOrderByArray();
2329 if(!empty($this->_orderByArray) && !$this->_rollup == 'WITH ROLLUP'){
2330 $this->_orderBy = "ORDER BY " . implode(', ', $this->_orderByArray);
2331 }
2332 $this->assign('sections', $this->_sections);
2333 }
2334
2335 /*
2336 * In some cases other functions want to know which fields are selected for ordering by
2337 * Separating this into a separate function allows it to be called separately from constructing
2338 * the order by clause
2339 */
2340 function storeOrderByArray() {
2341 $orderBys = array();
2342
2343 if (!empty($this->_params['order_bys']) &&
2344 is_array($this->_params['order_bys']) &&
2345 !empty($this->_params['order_bys'])
2346 ) {
2347
2348 // Proces order_bys in user-specified order
2349 foreach ($this->_params['order_bys'] as $orderBy) {
2350 $orderByField = array();
2351 foreach ($this->_columns as $tableName => $table) {
2352 if (array_key_exists('order_bys', $table)) {
2353 // For DAO columns defined in $this->_columns
2354 $fields = $table['order_bys'];
2355 }
2356 elseif (array_key_exists('extends', $table)) {
2357 // For custom fields referenced in $this->_customGroupExtends
2358 $fields = CRM_Utils_Array::value('fields', $table, array());
2359 }
2360 if (!empty($fields) && is_array($fields)) {
2361 foreach ($fields as $fieldName => $field) {
2362 if ($fieldName == $orderBy['column']) {
2363 $orderByField = array_merge($field, $orderBy);
2364 $orderByField['tplField'] = "{$tableName}_{$fieldName}";
2365 break 2;
2366 }
2367 }
2368 }
2369 }
2370
2371 if (!empty($orderByField)) {
2372 $this->_orderByFields[] = $orderByField;
2373 $orderBys[] = "{$orderByField['dbAlias']} {$orderBy['order']}";
2374
2375 // Record any section headers for assignment to the template
2376 if (!empty($orderBy['section'])) {
2377 $orderByField['pageBreak'] = CRM_Utils_Array::value('pageBreak', $orderBy);
2378 $this->_sections[$orderByField['tplField']] = $orderByField;
2379 }
2380 }
2381 }
2382 }
2383
2384 $this->_orderByArray = $orderBys;
2385
2386 $this->assign('sections', $this->_sections);
2387 }
2388
2389 /**
2390 * @return array
2391 */
2392 function unselectedSectionColumns() {
2393 $selectColumns = array();
2394 foreach ($this->_columns as $tableName => $table) {
2395 if (array_key_exists('fields', $table)) {
2396 foreach ($table['fields'] as $fieldName => $field) {
2397 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
2398
2399 $selectColumns["{$tableName}_{$fieldName}"] = 1;
2400 }
2401 }
2402 }
2403 }
2404
2405 if (is_array($this->_sections)) {
2406 return array_diff_key($this->_sections, $selectColumns);
2407 }
2408 else {
2409 return array();
2410 }
2411 }
2412
2413 /**
2414 * @param $sql
2415 * @param $rows
2416 */
2417 function buildRows($sql, &$rows) {
2418 $dao = CRM_Core_DAO::executeQuery($sql);
2419 if (!is_array($rows)) {
2420 $rows = array();
2421 }
2422
2423 // use this method to modify $this->_columnHeaders
2424 $this->modifyColumnHeaders();
2425
2426 $unselectedSectionColumns = $this->unselectedSectionColumns();
2427
2428 while ($dao->fetch()) {
2429 $row = array();
2430 foreach ($this->_columnHeaders as $key => $value) {
2431 if (property_exists($dao, $key)) {
2432 $row[$key] = $dao->$key;
2433 }
2434 }
2435
2436 // section headers not selected for display need to be added to row
2437 foreach ($unselectedSectionColumns as $key => $values) {
2438 if (property_exists($dao, $key)) {
2439 $row[$key] = $dao->$key;
2440 }
2441 }
2442
2443 $rows[] = $row;
2444 }
2445 }
2446
2447 /**
2448 * When "order by" fields are marked as sections, this assigns to the template
2449 * an array of total counts for each section. This data is used by the Smarty
2450 * plugin {sectionTotal}
2451 */
2452 function sectionTotals() {
2453
2454 // Reports using order_bys with sections must populate $this->_selectAliases in select() method.
2455 if (empty($this->_selectAliases)) {
2456 return;
2457 }
2458
2459 if (!empty($this->_sections)) {
2460 // build the query with no LIMIT clause
2461 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', 'SELECT ', $this->_select);
2462 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
2463
2464 // pull section aliases out of $this->_sections
2465 $sectionAliases = array_keys($this->_sections);
2466
2467 $ifnulls = array();
2468 foreach (array_merge($sectionAliases, $this->_selectAliases) as $alias) {
2469 $ifnulls[] = "ifnull($alias, '') as $alias";
2470 }
2471
2472 /* Group (un-limited) report by all aliases and get counts. This might
2473 * be done more efficiently when the contents of $sql are known, ie. by
2474 * overriding this method in the report class.
2475 */
2476
2477
2478 $query = "select " . implode(", ", $ifnulls) . ", count(*) as ct from ($sql) as subquery group by " . implode(", ", $sectionAliases);
2479
2480 // initialize array of total counts
2481 $totals = array();
2482 $dao = CRM_Core_DAO::executeQuery($query);
2483 while ($dao->fetch()) {
2484
2485 // let $this->_alterDisplay translate any integer ids to human-readable values.
2486 $rows[0] = $dao->toArray();
2487 $this->alterDisplay($rows);
2488 $row = $rows[0];
2489
2490 // add totals for all permutations of section values
2491 $values = array();
2492 $i = 1;
2493 $aliasCount = count($sectionAliases);
2494 foreach ($sectionAliases as $alias) {
2495 $values[] = $row[$alias];
2496 $key = implode(CRM_Core_DAO::VALUE_SEPARATOR, $values);
2497 if ($i == $aliasCount) {
2498 // the last alias is the lowest-level section header; use count as-is
2499 $totals[$key] = $dao->ct;
2500 }
2501 else {
2502 // other aliases are higher level; roll count into their total
2503 $totals[$key] += $dao->ct;
2504 }
2505 }
2506 }
2507 $this->assign('sectionTotals', $totals);
2508 }
2509 }
2510
2511 function modifyColumnHeaders() {
2512 // use this method to modify $this->_columnHeaders
2513 }
2514
2515 /**
2516 * @param $rows
2517 */
2518 function doTemplateAssignment(&$rows) {
2519 $this->assign_by_ref('columnHeaders', $this->_columnHeaders);
2520 $this->assign_by_ref('rows', $rows);
2521 $this->assign('statistics', $this->statistics($rows));
2522 }
2523
2524 // override this method to build your own statistics
2525 /**
2526 * @param $rows
2527 *
2528 * @return array
2529 */
2530 function statistics(&$rows) {
2531 $statistics = array();
2532
2533 $count = count($rows);
2534
2535 if ($this->_rollup && ($this->_rollup != '') && $this->_grandFlag) {
2536 $count++;
2537 }
2538
2539 $this->countStat($statistics, $count);
2540
2541 $this->groupByStat($statistics);
2542
2543 $this->filterStat($statistics);
2544
2545 return $statistics;
2546 }
2547
2548 /**
2549 * @param $statistics
2550 * @param $count
2551 */
2552 function countStat(&$statistics, $count) {
2553 $statistics['counts']['rowCount'] = array('title' => ts('Row(s) Listed'),
2554 'value' => $count,
2555 );
2556
2557 if ($this->_rowsFound && ($this->_rowsFound > $count)) {
2558 $statistics['counts']['rowsFound'] = array('title' => ts('Total Row(s)'),
2559 'value' => $this->_rowsFound,
2560 );
2561 }
2562 }
2563
2564 /**
2565 * @param $statistics
2566 */
2567 function groupByStat(&$statistics) {
2568 if (!empty($this->_params['group_bys']) &&
2569 is_array($this->_params['group_bys']) &&
2570 !empty($this->_params['group_bys'])
2571 ) {
2572 foreach ($this->_columns as $tableName => $table) {
2573 if (array_key_exists('group_bys', $table)) {
2574 foreach ($table['group_bys'] as $fieldName => $field) {
2575 if (!empty($this->_params['group_bys'][$fieldName])) {
2576 $combinations[] = $field['title'];
2577 }
2578 }
2579 }
2580 }
2581 $statistics['groups'][] = array('title' => ts('Grouping(s)'),
2582 'value' => implode(' & ', $combinations),
2583 );
2584 }
2585 }
2586
2587 /**
2588 * @param $statistics
2589 */
2590 function filterStat(&$statistics) {
2591 foreach ($this->_columns as $tableName => $table) {
2592 if (array_key_exists('filters', $table)) {
2593 foreach ($table['filters'] as $fieldName => $field) {
2594 if (CRM_Utils_Array::value('type', $field) & CRM_Utils_Type::T_DATE && CRM_Utils_Array::value('operatorType', $field) != CRM_Report_Form::OP_MONTH) {
2595 list($from, $to) =
2596 $this->getFromTo(
2597 CRM_Utils_Array::value("{$fieldName}_relative", $this->_params),
2598 CRM_Utils_Array::value("{$fieldName}_from", $this->_params),
2599 CRM_Utils_Array::value("{$fieldName}_to", $this->_params),
2600 CRM_Utils_Array::value("{$fieldName}_from_time", $this->_params),
2601 CRM_Utils_Array::value("{$fieldName}_to_time", $this->_params)
2602 );
2603 $from_time_format = !empty($this->_params["{$fieldName}_from_time"]) ? 'h' : 'd';
2604 $from = CRM_Utils_Date::customFormat($from, null, array($from_time_format));
2605
2606 $to_time_format = !empty($this->_params["{$fieldName}_to_time"]) ? 'h' : 'd';
2607 $to = CRM_Utils_Date::customFormat($to, null, array($to_time_format));
2608
2609 if ($from || $to) {
2610 $statistics['filters'][] = array(
2611 'title' => $field['title'],
2612 'value' => ts("Between %1 and %2", array(1 => $from, 2 => $to)),
2613 );
2614 }
2615 elseif (in_array($rel = CRM_Utils_Array::value("{$fieldName}_relative", $this->_params),
2616 array_keys($this->getOperationPair(CRM_Report_Form::OP_DATE))
2617 )) {
2618 $pair = $this->getOperationPair(CRM_Report_Form::OP_DATE);
2619 $statistics['filters'][] = array(
2620 'title' => $field['title'],
2621 'value' => $pair[$rel],
2622 );
2623 }
2624 }
2625 else {
2626 $op = CRM_Utils_Array::value("{$fieldName}_op", $this->_params);
2627 $value = NULL;
2628 if ($op) {
2629 $pair = $this->getOperationPair(
2630 CRM_Utils_Array::value('operatorType', $field),
2631 $fieldName
2632 );
2633 $min = CRM_Utils_Array::value("{$fieldName}_min", $this->_params);
2634 $max = CRM_Utils_Array::value("{$fieldName}_max", $this->_params);
2635 $val = CRM_Utils_Array::value("{$fieldName}_value", $this->_params);
2636 if (in_array($op, array(
2637 'bw', 'nbw')) && ($min || $max)) {
2638 $value = "{$pair[$op]} " . $min . ' and ' . $max;
2639 }
2640 elseif ($op == 'nll' || $op == 'nnll') {
2641 $value = $pair[$op];
2642 }
2643 elseif (is_array($val) && (!empty($val))) {
2644 $options = CRM_Utils_Array::value('options', $field, array());
2645 foreach ($val as $key => $valIds) {
2646 if (isset($options[$valIds])) {
2647 $val[$key] = $options[$valIds];
2648 }
2649 }
2650 $pair[$op] = (count($val) == 1) ? (($op == 'notin' || $op == 'mnot') ? ts('Is Not') : ts('Is')) : CRM_Utils_Array::value($op, $pair);
2651 $val = implode(', ', $val);
2652 $value = "{$pair[$op]} " . $val;
2653 }
2654 elseif (!is_array($val) && (!empty($val) || $val == '0') && isset($field['options']) &&
2655 is_array($field['options']) && !empty($field['options'])
2656 ) {
2657 $value = CRM_Utils_Array::value($op, $pair) . " " . CRM_Utils_Array::value($val, $field['options'], $val);
2658 }
2659 elseif ($val) {
2660 $value = CRM_Utils_Array::value($op, $pair) . " " . $val;
2661 }
2662 }
2663 if ($value) {
2664 $statistics['filters'][] = array('title' => CRM_Utils_Array::value('title', $field),
2665 'value' => $value,
2666 );
2667 }
2668 }
2669 }
2670 }
2671 }
2672 }
2673
2674 /**
2675 * @param null $rows
2676 */
2677 function endPostProcess(&$rows = NULL) {
2678 if ( $this->_storeResultSet ) {
2679 $this->_resultSet = $rows;
2680 }
2681
2682 if ($this->_outputMode == 'print' ||
2683 $this->_outputMode == 'pdf' ||
2684 $this->_sendmail
2685 ) {
2686
2687 $content = $this->compileContent();
2688 $url = CRM_Utils_System::url("civicrm/report/instance/{$this->_id}",
2689 "reset=1", TRUE
2690 );
2691
2692 if ($this->_sendmail) {
2693 $config = CRM_Core_Config::singleton();
2694 $attachments = array();
2695
2696 if ($this->_outputMode == 'csv') {
2697 $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'];
2698
2699 $csvFullFilename = $config->templateCompileDir . CRM_Utils_File::makeFileName('CiviReport.csv');
2700 $csvContent = CRM_Report_Utils_Report::makeCsv($this, $rows);
2701 file_put_contents($csvFullFilename, $csvContent);
2702 $attachments[] = array(
2703 'fullPath' => $csvFullFilename,
2704 'mime_type' => 'text/csv',
2705 'cleanName' => 'CiviReport.csv',
2706 );
2707 }
2708 if ($this->_outputMode == 'pdf') {
2709 // generate PDF content
2710 $pdfFullFilename = $config->templateCompileDir . CRM_Utils_File::makeFileName('CiviReport.pdf');
2711 file_put_contents($pdfFullFilename,
2712 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf",
2713 TRUE, array('orientation' => 'landscape')
2714 )
2715 );
2716 // generate Email Content
2717 $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'];
2718
2719 $attachments[] = array(
2720 'fullPath' => $pdfFullFilename,
2721 'mime_type' => 'application/pdf',
2722 'cleanName' => 'CiviReport.pdf',
2723 );
2724 }
2725
2726 if (CRM_Report_Utils_Report::mailReport($content, $this->_id,
2727 $this->_outputMode, $attachments
2728 )) {
2729 CRM_Core_Session::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
2730 }
2731 else {
2732 CRM_Core_Session::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
2733 }
2734 return TRUE;
2735 }
2736 elseif ($this->_outputMode == 'print') {
2737 echo $content;
2738 }
2739 else {
2740 if ($chartType = CRM_Utils_Array::value('charts', $this->_params)) {
2741 $config = CRM_Core_Config::singleton();
2742 //get chart image name
2743 $chartImg = $this->_chartId . '.png';
2744 //get image url path
2745 $uploadUrl = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL) . 'openFlashChart/';
2746 $uploadUrl .= $chartImg;
2747 //get image doc path to overwrite
2748 $uploadImg = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir) . 'openFlashChart/' . $chartImg;
2749 //Load the image
2750 $chart = imagecreatefrompng($uploadUrl);
2751 //convert it into formattd png
2752 header('Content-type: image/png');
2753 //overwrite with same image
2754 imagepng($chart, $uploadImg);
2755 //delete the object
2756 imagedestroy($chart);
2757 }
2758 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
2759 }
2760 CRM_Utils_System::civiExit();
2761 }
2762 elseif ($this->_outputMode == 'csv') {
2763 CRM_Report_Utils_Report::export2csv($this, $rows);
2764 }
2765 elseif ($this->_outputMode == 'group') {
2766 $group = $this->_params['groups'];
2767 $this->add2group($group);
2768 }
2769 elseif ($this->_instanceButtonName == $this->controller->getButtonName()) {
2770 CRM_Report_Form_Instance::postProcess($this);
2771 }
2772 elseif ($this->_createNewButtonName == $this->controller->getButtonName() ||
2773 $this->_outputMode == 'create_report' ) {
2774 $this->_createNew = TRUE;
2775 CRM_Report_Form_Instance::postProcess($this);
2776 }
2777 }
2778
2779 function storeResultSet() {
2780 $this->_storeResultSet = TRUE;
2781 }
2782
2783 /**
2784 * @return bool
2785 */
2786 function getResultSet() {
2787 return $this->_resultSet;
2788 }
2789
2790 /*
2791 * Get Template file name - use default form template if a specific one has not been set up for this report
2792 *
2793 */
2794 /**
2795 * Use the form name to create the tpl file name
2796 *
2797 * @return string
2798 * @access public
2799 */
2800 /**
2801 * @return string
2802 */
2803 function getTemplateFileName(){
2804 $defaultTpl = parent::getTemplateFileName();
2805 $template = CRM_Core_Smarty::singleton();
2806 if (!$template->template_exists($defaultTpl)) {
2807 $defaultTpl = 'CRM/Report/Form.tpl';
2808 }
2809 return $defaultTpl;
2810 }
2811
2812 /*
2813 * Compile the report content
2814 *
2815 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
2816 */
2817 /**
2818 * @return string
2819 */
2820 function compileContent(){
2821 $templateFile = $this->getHookedTemplateFileName();
2822 return $this->_formValues['report_header'] . CRM_Core_Form::$_template->fetch($templateFile) . $this->_formValues['report_footer'];
2823 }
2824
2825
2826 function postProcess() {
2827 // get ready with post process params
2828 $this->beginPostProcess();
2829
2830 // build query
2831 $sql = $this->buildQuery();
2832
2833 // build array of result based on column headers. This method also allows
2834 // modifying column headers before using it to build result set i.e $rows.
2835 $rows = array();
2836 $this->buildRows($sql, $rows);
2837
2838 // format result set.
2839 $this->formatDisplay($rows);
2840
2841 // assign variables to templates
2842 $this->doTemplateAssignment($rows);
2843
2844 // do print / pdf / instance stuff if needed
2845 $this->endPostProcess($rows);
2846 }
2847
2848 /**
2849 * @param int $rowCount
2850 */
2851 function limit($rowCount = self::ROW_COUNT_LIMIT) {
2852 // lets do the pager if in html mode
2853 $this->_limit = NULL;
2854
2855 // CRM-14115, over-ride row count if rowCount is specified in URL
2856 if ($this->_dashBoardRowCount) {
2857 $rowCount = $this->_dashBoardRowCount;
2858 }
2859 if ($this->_outputMode == 'html' || $this->_outputMode == 'group') {
2860 $this->_select = str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select);
2861
2862 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer', CRM_Core_DAO::$_nullObject);
2863
2864 if (!$pageId && !empty($_POST)) {
2865 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
2866 $pageId = max((int)@$_POST['crmPID_B'], 1);
2867 }
2868 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
2869 $pageId = max((int)@$_POST['crmPID'], 1);
2870 }
2871 unset($_POST['crmPID_B'], $_POST['crmPID']);
2872 }
2873
2874 $pageId = $pageId ? $pageId : 1;
2875 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
2876 $offset = ($pageId - 1) * $rowCount;
2877
2878 $offset = CRM_Utils_Type::escape($offset, 'Int');
2879 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
2880
2881 $this->_limit = " LIMIT $offset, $rowCount";
2882 return array($offset, $rowCount);
2883 }
2884 if($this->_limitValue) {
2885 if($this->_offsetValue) {
2886 $this->_limit = " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
2887 }
2888 else {
2889 $this->_limit = " LIMIT " . $this->_limitValue;
2890 }
2891 }
2892 }
2893
2894 /**
2895 * @param int $rowCount
2896 */
2897 function setPager($rowCount = self::ROW_COUNT_LIMIT) {
2898
2899 // CRM-14115, over-ride row count if rowCount is specified in URL
2900 if ($this->_dashBoardRowCount) {
2901 $rowCount = $this->_dashBoardRowCount;
2902 }
2903
2904 if ($this->_limit && ($this->_limit != '')) {
2905 $sql = "SELECT FOUND_ROWS();";
2906 $this->_rowsFound = CRM_Core_DAO::singleValueQuery($sql);
2907 $params = array(
2908 'total' => $this->_rowsFound,
2909 'rowCount' => $rowCount,
2910 'status' => ts('Records') . ' %%StatusMessage%%',
2911 'buttonBottom' => 'PagerBottomButton',
2912 'buttonTop' => 'PagerTopButton',
2913 'pageID' => $this->get(CRM_Utils_Pager::PAGE_ID),
2914 );
2915
2916 $pager = new CRM_Utils_Pager($params);
2917 $this->assign_by_ref('pager', $pager);
2918 $this->ajaxResponse['totalRows'] = $this->_rowsFound;
2919 }
2920 }
2921
2922 /**
2923 * @param $field
2924 * @param $value
2925 * @param $op
2926 *
2927 * @return string
2928 */
2929 function whereGroupClause($field, $value, $op) {
2930
2931 $smartGroupQuery = "";
2932
2933 $group = new CRM_Contact_DAO_Group();
2934 $group->is_active = 1;
2935 $group->find();
2936 $smartGroups = array();
2937 while ($group->fetch()) {
2938 if (in_array($group->id, $this->_params['gid_value']) && $group->saved_search_id) {
2939 $smartGroups[] = $group->id;
2940 }
2941 }
2942
2943 CRM_Contact_BAO_GroupContactCache::check($smartGroups);
2944
2945 $smartGroupQuery = '';
2946 if (!empty($smartGroups)) {
2947 $smartGroups = implode(',', $smartGroups);
2948 $smartGroupQuery = " UNION DISTINCT
2949 SELECT DISTINCT smartgroup_contact.contact_id
2950 FROM civicrm_group_contact_cache smartgroup_contact
2951 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
2952 }
2953
2954 $sqlOp = $this->getSQLOperator($op);
2955 if (!is_array($value)) {
2956 $value = array($value);
2957 }
2958 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2959
2960 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2961 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
2962 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
2963 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
2964 {$smartGroupQuery} ) ";
2965 }
2966
2967 /**
2968 * @param $field
2969 * @param $value
2970 * @param $op
2971 *
2972 * @return string
2973 */
2974 function whereTagClause($field, $value, $op) {
2975 // not using left join in query because if any contact
2976 // belongs to more than one tag, results duplicate
2977 // entries.
2978 $sqlOp = $this->getSQLOperator($op);
2979 if (!is_array($value)) {
2980 $value = array($value);
2981 }
2982 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
2983
2984 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2985 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
2986 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
2987 WHERE entity_table = 'civicrm_contact' AND {$clause} ) ";
2988 }
2989
2990 function whereMembershipOrgClause($field, $value, $op) {
2991 $sqlOp = $this->getSQLOperator($op);
2992 if (!is_array($value)) {
2993 $value = array($value);
2994 }
2995
2996 $tmp_membership_org_sql_list = implode(', ', $value);
2997 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
2998 SELECT DISTINCT mem.contact_id
2999 FROM civicrm_membership mem
3000 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3001 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3002 WHERE mt.member_of_contact_id IN (".$tmp_membership_org_sql_list.")
3003 AND mt.is_active = '1'
3004 AND mem_status.is_current_member = '1'
3005 AND mem_status.is_active = '1' ) ";
3006 }
3007
3008 function whereMembershipTypeClause($field, $value, $op) {
3009 $sqlOp = $this->getSQLOperator($op);
3010 if (!is_array($value)) {
3011 $value = array($value);
3012 }
3013
3014 $tmp_membership_sql_list = implode(', ', $value);
3015 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3016 SELECT DISTINCT mem.contact_id
3017 FROM civicrm_membership mem
3018 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3019 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3020 WHERE mem.membership_type_id IN (".$tmp_membership_sql_list.")
3021 AND mt.is_active = '1'
3022 AND mem_status.is_current_member = '1'
3023 AND mem_status.is_active = '1' ) ";
3024 }
3025
3026 /**
3027 * @param string $tableAlias
3028 */
3029 function buildACLClause($tableAlias = 'contact_a') {
3030 list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
3031 }
3032
3033 /**
3034 * @param bool $addFields
3035 * @param array $permCustomGroupIds
3036 */
3037 function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3038 if (empty($this->_customGroupExtends)) {
3039 return;
3040 }
3041 if (!is_array($this->_customGroupExtends)) {
3042 $this->_customGroupExtends = array($this->_customGroupExtends);
3043 }
3044 $customGroupWhere = '';
3045 if (!empty($permCustomGroupIds)) {
3046 $customGroupWhere = "cg.id IN (".implode(',' , $permCustomGroupIds).") AND";
3047 }
3048 $sql = "
3049 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3050 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3051 FROM civicrm_custom_group cg
3052 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3053 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
3054 {$customGroupWhere}
3055 cg.is_active = 1 AND
3056 cf.is_active = 1 AND
3057 cf.is_searchable = 1
3058 ORDER BY cg.weight, cf.weight";
3059 $customDAO = CRM_Core_DAO::executeQuery($sql);
3060
3061 $curTable = NULL;
3062 while ($customDAO->fetch()) {
3063 if ($customDAO->table_name != $curTable) {
3064 $curTable = $customDAO->table_name;
3065 $curFields = $curFilters = array();
3066
3067 // dummy dao object
3068 $this->_columns[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3069 $this->_columns[$curTable]['extends'] = $customDAO->extends;
3070 $this->_columns[$curTable]['grouping'] = $customDAO->table_name;
3071 $this->_columns[$curTable]['group_title'] = $customDAO->title;
3072
3073 foreach (array(
3074 'fields', 'filters', 'group_bys') as $colKey) {
3075 if (!array_key_exists($colKey, $this->_columns[$curTable])) {
3076 $this->_columns[$curTable][$colKey] = array();
3077 }
3078 }
3079 }
3080 $fieldName = 'custom_' . $customDAO->cf_id;
3081
3082 if ($addFields) {
3083 // this makes aliasing work in favor
3084 $curFields[$fieldName] = array(
3085 'name' => $customDAO->column_name,
3086 'title' => $customDAO->label,
3087 'dataType' => $customDAO->data_type,
3088 'htmlType' => $customDAO->html_type,
3089 );
3090 }
3091 if ($this->_customGroupFilters) {
3092 // this makes aliasing work in favor
3093 $curFilters[$fieldName] = array(
3094 'name' => $customDAO->column_name,
3095 'title' => $customDAO->label,
3096 'dataType' => $customDAO->data_type,
3097 'htmlType' => $customDAO->html_type,
3098 );
3099 }
3100
3101 switch ($customDAO->data_type) {
3102 case 'Date':
3103 // filters
3104 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE;
3105 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_DATE;
3106 // CRM-6946, show time part for datetime date fields
3107 if ($customDAO->time_format) {
3108 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_TIMESTAMP;
3109 }
3110 break;
3111
3112 case 'Boolean':
3113 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT;
3114 $curFilters[$fieldName]['options'] = array('' => ts('- select -'),
3115 1 => ts('Yes'),
3116 0 => ts('No'),
3117 );
3118 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
3119 break;
3120
3121 case 'Int':
3122 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_INT;
3123 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
3124 break;
3125
3126 case 'Money':
3127 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
3128 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_MONEY;
3129 break;
3130
3131 case 'Float':
3132 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
3133 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_FLOAT;
3134 break;
3135
3136 case 'String':
3137 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3138
3139 if (!empty($customDAO->option_group_id)) {
3140 if (in_array($customDAO->html_type, array(
3141 'Multi-Select', 'AdvMulti-Select', 'CheckBox'))) {
3142 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
3143 }
3144 else {
3145 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
3146 }
3147 if ($this->_customGroupFilters) {
3148 $curFilters[$fieldName]['options'] = array();
3149 $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')));
3150 while ($ogDAO->fetch()) {
3151 $curFilters[$fieldName]['options'][$ogDAO->value] = $ogDAO->label;
3152 }
3153 }
3154 }
3155 break;
3156
3157 case 'StateProvince':
3158 if (in_array($customDAO->html_type, array(
3159 'Multi-Select State/Province'))) {
3160 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
3161 }
3162 else {
3163 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
3164 }
3165 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::stateProvince();
3166 break;
3167
3168 case 'Country':
3169 if (in_array($customDAO->html_type, array(
3170 'Multi-Select Country'))) {
3171 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT_SEPARATOR;
3172 }
3173 else {
3174 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_MULTISELECT;
3175 }
3176 $curFilters[$fieldName]['options'] = CRM_Core_PseudoConstant::country();
3177 break;
3178
3179 case 'ContactReference':
3180 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3181 $curFilters[$fieldName]['name'] = 'display_name';
3182 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3183
3184 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3185 $curFields[$fieldName]['name'] = 'display_name';
3186 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3187 break;
3188
3189 default:
3190 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3191 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3192 }
3193
3194 if (!array_key_exists('type', $curFields[$fieldName])) {
3195 $curFields[$fieldName]['type'] = CRM_Utils_Array::value('type', $curFilters[$fieldName], array());
3196 }
3197
3198 if ($addFields) {
3199 $this->_columns[$curTable]['fields'] = array_merge($this->_columns[$curTable]['fields'], $curFields);
3200 }
3201 if ($this->_customGroupFilters) {
3202 $this->_columns[$curTable]['filters'] = array_merge($this->_columns[$curTable]['filters'], $curFilters);
3203 }
3204 if ($this->_customGroupGroupBy) {
3205 $this->_columns[$curTable]['group_bys'] = array_merge($this->_columns[$curTable]['group_bys'], $curFields);
3206 }
3207 }
3208 }
3209
3210 function customDataFrom() {
3211 if (empty($this->_customGroupExtends)) {
3212 return;
3213 }
3214 $mapper = CRM_Core_BAO_CustomQuery::$extendsMap;
3215
3216 foreach ($this->_columns as $table => $prop) {
3217 if (substr($table, 0, 13) == 'civicrm_value' || substr($table, 0, 12) == 'custom_value') {
3218 $extendsTable = $mapper[$prop['extends']];
3219
3220 // check field is in params
3221 if (!$this->isFieldSelected($prop)) {
3222 continue;
3223 }
3224 $baseJoin = CRM_Utils_Array::value($prop['extends'], $this->_customGroupExtendsJoin, "{$this->_aliases[$extendsTable]}.id");
3225
3226 $customJoin = is_array($this->_customGroupJoin) ? $this->_customGroupJoin[$table] : $this->_customGroupJoin;
3227 $this->_from .= "
3228 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3229 // handle for ContactReference
3230 if (array_key_exists('fields', $prop)) {
3231 foreach ($prop['fields'] as $fieldName => $field) {
3232 if (CRM_Utils_Array::value('dataType', $field) == 'ContactReference') {
3233 $columnName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField::getKeyID($fieldName), 'column_name');
3234 $this->_from .= "
3235 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3236 }
3237 }
3238 }
3239 }
3240 }
3241 }
3242
3243 /**
3244 * @param $prop
3245 *
3246 * @return bool
3247 */
3248 function isFieldSelected($prop) {
3249 if (empty($prop)) {
3250 return FALSE;
3251 }
3252
3253 if (!empty($this->_params['fields'])) {
3254 foreach (array_keys($prop['fields']) as $fieldAlias) {
3255 $customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias);
3256 if ($customFieldId) {
3257 if (array_key_exists($fieldAlias, $this->_params['fields'])) {
3258 return TRUE;
3259 }
3260
3261 //might be survey response field.
3262 if (!empty($this->_params['fields']['survey_response']) && !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])) {
3263 return TRUE;
3264 }
3265 }
3266 }
3267 }
3268
3269 if (!empty($this->_params['group_bys']) && $this->_customGroupGroupBy) {
3270 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3271 if (array_key_exists($fieldAlias, $this->_params['group_bys']) && CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
3272 return TRUE;
3273 }
3274 }
3275 }
3276
3277 if (!empty($this->_params['order_bys'])) {
3278 foreach (array_keys($prop['fields']) as $fieldAlias) {
3279 foreach ($this->_params['order_bys'] as $orderBy) {
3280 if ($fieldAlias == $orderBy['column'] && CRM_Core_BAO_CustomField::getKeyID($fieldAlias)) {
3281 return TRUE;
3282 }
3283 }
3284 }
3285 }
3286
3287 if (!empty($prop['filters']) && $this->_customGroupFilters) {
3288 foreach ($prop['filters'] as $fieldAlias => $val) {
3289 foreach (array(
3290 'value', 'min', 'max', 'relative', 'from', 'to') as $attach) {
3291 if (isset($this->_params[$fieldAlias . '_' . $attach]) &&
3292 (!empty($this->_params[$fieldAlias . '_' . $attach])
3293 || ($attach != 'relative' && $this->_params[$fieldAlias . '_' . $attach] == '0')
3294 )
3295 ){
3296 return TRUE;
3297 }
3298 }
3299 if (!empty($this->_params[$fieldAlias . '_op']) &&
3300 in_array($this->_params[$fieldAlias . '_op'], array('nll', 'nnll'))
3301 ) {
3302 return TRUE;
3303 }
3304 }
3305 }
3306
3307 return FALSE;
3308 }
3309
3310 /**
3311 * Check for empty order_by configurations and remove them; also set
3312 * template to hide them.
3313 */
3314 function preProcessOrderBy(&$formValues) {
3315 // Object to show/hide form elements
3316 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3317
3318 $_showHide->addShow('optionField_1');
3319
3320 // Cycle through order_by options; skip any empty ones, and hide them as well
3321 $n = 1;
3322
3323 if (!empty($formValues['order_bys'])) {
3324 foreach ($formValues['order_bys'] as $order_by) {
3325 if ($order_by['column'] && $order_by['column'] != '-') {
3326 $_showHide->addShow('optionField_' . $n);
3327 $orderBys[$n] = $order_by;
3328 $n++;
3329 }
3330 }
3331 }
3332 for ($i = $n; $i <= 5; $i++) {
3333 if ($i > 1) {
3334 $_showHide->addHide('optionField_' . $i);
3335 }
3336 }
3337
3338 // overwrite order_by options with modified values
3339 if (!empty($orderBys)) {
3340 $formValues['order_bys'] = $orderBys;
3341 }
3342 else {
3343 $formValues['order_bys'] = array(1 => array('column' => '-'));
3344 }
3345
3346 // assign show/hide data to template
3347 $_showHide->addToTemplate();
3348 }
3349
3350 /**
3351 * Does table name have columns in SELECT clause?
3352 *
3353 * @param string $tableName Name of table (index of $this->_columns array)
3354 *
3355 * @return bool
3356 */
3357 function isTableSelected($tableName) {
3358 return in_array($tableName, $this->selectedTables());
3359 }
3360
3361 /**
3362 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause
3363 * (building the array if it's unset)
3364 *
3365 * @return Array $this->_selectedTables
3366 */
3367 function selectedTables() {
3368 if (!$this->_selectedTables) {
3369 $orderByColumns = array();
3370 if (array_key_exists('order_bys', $this->_params) && is_array($this->_params['order_bys'])) {
3371 foreach ($this->_params['order_bys'] as $orderBy) {
3372 $orderByColumns[] = $orderBy['column'];
3373 }
3374 }
3375
3376 foreach ($this->_columns as $tableName => $table) {
3377 if (array_key_exists('fields', $table)) {
3378 foreach ($table['fields'] as $fieldName => $field) {
3379 if (!empty($field['required']) || !empty($this->_params['fields'][$fieldName])) {
3380 $this->_selectedTables[] = $tableName;
3381 break;
3382 }
3383 }
3384 }
3385 if (array_key_exists('order_bys', $table)) {
3386 foreach ($table['order_bys'] as $orderByName => $orderBy) {
3387 if (in_array($orderByName, $orderByColumns)) {
3388 $this->_selectedTables[] = $tableName;
3389 break;
3390 }
3391 }
3392 }
3393 if (array_key_exists('filters', $table)) {
3394 foreach ($table['filters'] as $filterName => $filter) {
3395 if (!empty($this->_params["{$filterName}_value"]) ||
3396 CRM_Utils_Array::value("{$filterName}_op", $this->_params) == 'nll' ||
3397 CRM_Utils_Array::value("{$filterName}_op", $this->_params) == 'nnll'
3398 ) {
3399 $this->_selectedTables[] = $tableName;
3400 break;
3401 }
3402 }
3403 }
3404 }
3405 }
3406 return $this->_selectedTables;
3407 }
3408
3409 /**
3410 * @deprecated - use getAddressColumns which is a more accurate description
3411 * and also accepts an array of options rather than a long list
3412 *
3413 * function for adding address fields to construct function in reports
3414 *
3415 * @param bool $groupBy Add GroupBy? Not appropriate for detail report
3416 * @param bool $orderBy Add GroupBy? Not appropriate for detail report
3417 * @param bool $filters
3418 * @param array $defaults
3419 *
3420 * @return array address fields for construct clause
3421 */
3422 function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array(
3423 'country_id' => TRUE)) {
3424 $addressFields = array(
3425 'civicrm_address' =>
3426 array(
3427 'dao' => 'CRM_Core_DAO_Address',
3428 'fields' =>
3429 array(
3430 'name' =>
3431 array('title' => ts('Address Name'),
3432 'default' => CRM_Utils_Array::value('name', $defaults, FALSE),
3433 ),
3434 'street_address' =>
3435 array('title' => ts('Street Address'),
3436 'default' => CRM_Utils_Array::value('street_address', $defaults, FALSE),
3437 ),
3438 'supplemental_address_1' =>
3439 array('title' => ts('Supplementary Address Field 1'),
3440 'default' => CRM_Utils_Array::value('supplemental_address_1', $defaults, FALSE),
3441 ),
3442 'supplemental_address_2' =>
3443 array('title' => ts('Supplementary Address Field 2'),
3444 'default' => CRM_Utils_Array::value('supplemental_address_2', $defaults, FALSE),
3445 ),
3446 'street_number' =>
3447 array(
3448 'name' => 'street_number',
3449 'title' => ts('Street Number'),
3450 'type' => 1,
3451 'default' => CRM_Utils_Array::value('street_number', $defaults, FALSE),
3452 ),
3453 'street_name' =>
3454 array(
3455 'name' => 'street_name',
3456 'title' => ts('Street Name'),
3457 'type' => 1,
3458 'default' => CRM_Utils_Array::value('street_name', $defaults, FALSE),
3459 ),
3460 'street_unit' =>
3461 array(
3462 'name' => 'street_unit',
3463 'title' => ts('Street Unit'),
3464 'type' => 1,
3465 'default' => CRM_Utils_Array::value('street_unit', $defaults, FALSE),
3466 ),
3467 'city' =>
3468 array('title' => ts('City'),
3469 'default' => CRM_Utils_Array::value('city', $defaults, FALSE),
3470 ),
3471 'postal_code' =>
3472 array('title' => ts('Postal Code'),
3473 'default' => CRM_Utils_Array::value('postal_code', $defaults, FALSE),
3474 ),
3475 'postal_code_suffix' =>
3476 array('title' => ts('Postal Code Suffix'),
3477 'default' => CRM_Utils_Array::value('postal_code_suffix', $defaults, FALSE),
3478 ),
3479 'county_id' =>
3480 array('title' => ts('County'),
3481 'default' => CRM_Utils_Array::value('county_id', $defaults, FALSE),
3482 ),
3483 'state_province_id' =>
3484 array('title' => ts('State/Province'),
3485 'default' => CRM_Utils_Array::value('state_province_id', $defaults, FALSE),
3486 ),
3487 'country_id' =>
3488 array('title' => ts('Country'),
3489 'default' => CRM_Utils_Array::value('country_id', $defaults, FALSE),
3490 ),
3491 ),
3492 'grouping' => 'location-fields',
3493 ),
3494 );
3495
3496 if ($filters) {
3497 $addressFields['civicrm_address']['filters'] = array(
3498 'street_number' => array('title' => ts('Street Number'),
3499 'type' => 1,
3500 'name' => 'street_number',
3501 ),
3502 'street_name' => array('title' => ts('Street Name'),
3503 'name' => 'street_name',
3504 'operator' => 'like',
3505 ),
3506 'postal_code' => array('title' => ts('Postal Code'),
3507 'type' => 1,
3508 'name' => 'postal_code',
3509 ),
3510 'city' => array('title' => ts('City'),
3511 'operator' => 'like',
3512 'name' => 'city',
3513 ),
3514 'county_id' => array(
3515 'name' => 'county_id',
3516 'title' => ts('County'),
3517 'type' => CRM_Utils_Type::T_INT,
3518 'operatorType' =>
3519 CRM_Report_Form::OP_MULTISELECT,
3520 'options' =>
3521 CRM_Core_PseudoConstant::county(),
3522 ),
3523 'state_province_id' => array(
3524 'name' => 'state_province_id',
3525 'title' => ts('State/Province'),
3526 'type' => CRM_Utils_Type::T_INT,
3527 'operatorType' =>
3528 CRM_Report_Form::OP_MULTISELECT,
3529 'options' =>
3530 CRM_Core_PseudoConstant::stateProvince(),
3531 ),
3532 'country_id' => array(
3533 'name' => 'country_id',
3534 'title' => ts('Country'),
3535 'type' => CRM_Utils_Type::T_INT,
3536 'operatorType' =>
3537 CRM_Report_Form::OP_MULTISELECT,
3538 'options' =>
3539 CRM_Core_PseudoConstant::country(),
3540 ),
3541 );
3542 }
3543
3544 if ($orderBy) {
3545 $addressFields['civicrm_address']['order_bys'] = array('street_name' => array('title' => ts('Street Name')),
3546 'street_number' => array('title' => 'Odd / Even Street Number'),
3547 'street_address' => NULL,
3548 'city' => NULL,
3549 'postal_code' => NULL,
3550 );
3551 }
3552
3553 if ($groupBy) {
3554 $addressFields['civicrm_address']['group_bys'] = array(
3555 'street_address' => NULL,
3556 'city' => NULL,
3557 'postal_code' => NULL,
3558 'state_province_id' =>
3559 array('title' => ts('State/Province'),
3560 ),
3561 'country_id' =>
3562 array('title' => ts('Country'),
3563 ),
3564 'county_id' =>
3565 array('title' => ts('County'),
3566 ),
3567 );
3568 }
3569 return $addressFields;
3570 }
3571
3572 /*
3573 * Do AlterDisplay processing on Address Fields
3574 */
3575 /**
3576 * @param $row
3577 * @param $rows
3578 * @param $rowNum
3579 * @param $baseUrl
3580 * @param $urltxt
3581 *
3582 * @return bool
3583 */
3584 function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $urltxt) {
3585 $criteriaQueryParams = CRM_Report_Utils_Report::getPreviewCriteriaQueryParams($this->_defaults, $this->_params);
3586 $entryFound = FALSE;
3587 // handle country
3588 if (array_key_exists('civicrm_address_country_id', $row)) {
3589 if ($value = $row['civicrm_address_country_id']) {
3590 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
3591 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
3592 "reset=1&force=1&{$criteriaQueryParams}&" .
3593 "country_id_op=in&country_id_value={$value}",
3594 $this->_absoluteUrl, $this->_id
3595 );
3596 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
3597 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
3598 array(1 => $urltxt)
3599 );
3600 }
3601
3602 $entryFound = TRUE;
3603 }
3604 if (array_key_exists('civicrm_address_county_id', $row)) {
3605 if ($value = $row['civicrm_address_county_id']) {
3606 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant::county($value, FALSE);
3607 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
3608 "reset=1&force=1&{$criteriaQueryParams}&" .
3609 "county_id_op=in&county_id_value={$value}",
3610 $this->_absoluteUrl, $this->_id
3611 );
3612 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
3613 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
3614 array(1 => $urltxt)
3615 );
3616 }
3617 $entryFound = TRUE;
3618 }
3619 // handle state province
3620 if (array_key_exists('civicrm_address_state_province_id', $row)) {
3621 if ($value = $row['civicrm_address_state_province_id']) {
3622 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
3623
3624 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
3625 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
3626 $this->_absoluteUrl, $this->_id
3627 );
3628 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
3629 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
3630 array(1 => $urltxt)
3631 );
3632 }
3633 $entryFound = TRUE;
3634 }
3635
3636 return $entryFound;
3637 }
3638
3639 /*
3640 * Adjusts dates passed in to YEAR() for fiscal year.
3641 */
3642 /**
3643 * @param $fieldName
3644 *
3645 * @return string
3646 */
3647 function fiscalYearOffset($fieldName) {
3648 $config = CRM_Core_Config::singleton();
3649 $fy = $config->fiscalYearStart;
3650 if (CRM_Utils_Array::value('yid_op', $this->_params) == 'calendar' || ($fy['d'] == 1 && $fy['M'] == 1)) {
3651 return "YEAR( $fieldName )";
3652 }
3653 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" . ($fy['d'] > 1 ? (" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
3654 }
3655
3656 /*
3657 * Add Address into From Table if required
3658 */
3659 function addAddressFromClause() {
3660 // include address field if address column is to be included
3661 if ((isset($this->_addressField) &&
3662 $this->_addressField
3663 ) ||
3664 $this->isTableSelected('civicrm_address')
3665 ) {
3666 $this->_from .= "
3667 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
3668 ON ({$this->_aliases['civicrm_contact']}.id =
3669 {$this->_aliases['civicrm_address']}.contact_id) AND
3670 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
3671 }
3672 }
3673
3674 /**
3675 * Add Phone into From Table if required
3676 */
3677 function addPhoneFromClause() {
3678 // include address field if address column is to be included
3679 if ($this->isTableSelected('civicrm_phone')
3680 ) {
3681 $this->_from .= "
3682 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
3683 ON ({$this->_aliases['civicrm_contact']}.id =
3684 {$this->_aliases['civicrm_phone']}.contact_id) AND
3685 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
3686 }
3687 }
3688
3689 /**
3690 * Get phone columns to add to array
3691 * @param array $options
3692 * - prefix Prefix to add to table (in case of more than one instance of the table)
3693 * - prefix_label Label to give columns from this phone table instance
3694 * @return array phone columns definition
3695 */
3696 function getPhoneColumns($options = array()){
3697 $defaultOptions = array(
3698 'prefix' => '',
3699 'prefix_label' => '',
3700 );
3701
3702 $options = array_merge($defaultOptions,$options);
3703
3704 $fields = array(
3705 $options['prefix'] . 'civicrm_phone' => array(
3706 'dao' => 'CRM_Core_DAO_Phone',
3707 'fields' => array(
3708 $options['prefix'] . 'phone' => array(
3709 'title' => ts($options['prefix_label'] . 'Phone'),
3710 'name' => 'phone'
3711 ),
3712 ),
3713 ),
3714 );
3715 return $fields;
3716 }
3717
3718 /**
3719 * Get address columns to add to array
3720 * @param array $options
3721 * - prefix Prefix to add to table (in case of more than one instance of the table)
3722 * - prefix_label Label to give columns from this address table instance
3723 * @return array address columns definition
3724 */
3725 function getAddressColumns($options = array()){
3726 $defaultOptions = array(
3727 'prefix' => '',
3728 'prefix_label' => '',
3729 'group_by' => TRUE,
3730 'order_by' => TRUE,
3731 'filters' => TRUE,
3732 'defaults' => array(
3733 ),
3734 );
3735 $options = array_merge($defaultOptions,$options);
3736 return $this->addAddressFields(
3737 $options['group_by'],
3738 $options['order_by'],
3739 $options['filters'],
3740 $options['defaults']
3741 );
3742
3743 }
3744
3745 /**
3746 * @param $groupID
3747 */
3748 function add2group($groupID) {
3749 if (is_numeric($groupID) && isset($this->_aliases['civicrm_contact'])) {
3750 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
3751 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select);
3752
3753 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
3754 $dao = CRM_Core_DAO::executeQuery($sql);
3755
3756 $contact_ids = array();
3757 // Add resulting contacts to group
3758 while ($dao->fetch()) {
3759 if ($dao->addtogroup_contact_id) {
3760 $contact_ids[$dao->addtogroup_contact_id] = $dao->addtogroup_contact_id;
3761 }
3762 }
3763
3764 if ( !empty($contact_ids) ) {
3765 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
3766 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
3767 }
3768 else {
3769 CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
3770 }
3771 }
3772 }
3773
3774 /* function used for showing charts on print screen */
3775 static function uploadChartImage() {
3776 // upload strictly for '.png' images
3777 $name = trim(basename(CRM_Utils_Request::retrieve('name', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET')));
3778 if (preg_match('/\.png$/', $name)) {
3779 //
3780 // POST data is usually string data, but we are passing a RAW .png
3781 // so PHP is a bit confused and $_POST is empty. But it has saved
3782 // the raw bits into $HTTP_RAW_POST_DATA
3783 //
3784 $httpRawPostData = $GLOBALS['HTTP_RAW_POST_DATA'];
3785
3786 // prepare the directory
3787 $config = CRM_Core_Config::singleton();
3788 $defaultPath = str_replace('/persist/contribute/' , '/persist/', $config->imageUploadDir) . '/openFlashChart/';
3789 if (!file_exists($defaultPath)) {
3790 mkdir($defaultPath, 0777, TRUE);
3791 }
3792
3793 // full path to the saved image including filename
3794 $destination = $defaultPath . $name;
3795
3796 //write and save
3797 $jfh = fopen($destination, 'w') or die("can't open file");
3798 fwrite($jfh, $httpRawPostData);
3799 fclose($jfh);
3800 CRM_Utils_System::civiExit();
3801 }
3802 }
3803 }