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