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