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