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