Merge pull request #9372 from agh1/no-notification-offline-text
[civicrm-core.git] / CRM / Report / Form.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 4.7 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2016 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 * Class CRM_Report_Form
30 */
31 class CRM_Report_Form extends CRM_Core_Form {
32 const ROW_COUNT_LIMIT = 50;
33
34 /**
35 * Operator types - used for displaying filter elements
36 */
37 const
38 OP_INT = 1,
39 OP_STRING = 2,
40 OP_DATE = 4,
41 OP_DATETIME = 5,
42 OP_FLOAT = 8,
43 OP_SELECT = 64,
44 OP_MULTISELECT = 65,
45 OP_MULTISELECT_SEPARATOR = 66,
46 OP_MONTH = 128,
47 OP_ENTITYREF = 256;
48
49 /**
50 * The id of the report instance
51 *
52 * @var integer
53 */
54 protected $_id;
55
56 /**
57 * The id of the report template
58 *
59 * @var integer;
60 */
61 protected $_templateID;
62
63 /**
64 * The report title
65 *
66 * @var string
67 */
68 protected $_title;
69 protected $_noFields = FALSE;
70
71 /**
72 * The set of all columns in the report. An associative array
73 * with column name as the key and attributes as the value
74 *
75 * @var array
76 */
77 protected $_columns = array();
78
79 /**
80 * The set of filters in the report
81 *
82 * @var array
83 */
84 protected $_filters = array();
85
86 /**
87 * The set of optional columns in the report
88 *
89 * @var array
90 */
91 public $_options = array();
92
93 /**
94 * By default most reports hide contact id.
95 * Setting this to true makes it available
96 */
97 protected $_exposeContactID = TRUE;
98
99 /**
100 * Set of statistic fields
101 *
102 * @var array
103 */
104 protected $_statFields = array();
105
106 /**
107 * Set of statistics data
108 *
109 * @var array
110 */
111 protected $_statistics = array();
112
113 /**
114 * List of fields not to be repeated during display
115 *
116 * @var array
117 */
118 protected $_noRepeats = array();
119
120 /**
121 * List of fields not to be displayed
122 *
123 * @var array
124 */
125 protected $_noDisplay = array();
126
127 /**
128 * Object type that a custom group extends
129 *
130 * @var null
131 */
132 protected $_customGroupExtends = NULL;
133 protected $_customGroupExtendsJoin = array();
134 protected $_customGroupFilters = TRUE;
135 protected $_customGroupGroupBy = FALSE;
136 protected $_customGroupJoin = 'LEFT JOIN';
137
138 /**
139 * Build tags filter
140 */
141 protected $_tagFilter = FALSE;
142
143 /**
144 * specify entity table for tags filter
145 */
146 protected $_tagFilterTable = 'civicrm_contact';
147
148 /**
149 * Build groups filter.
150 *
151 * @var bool
152 */
153 protected $_groupFilter = FALSE;
154
155 /**
156 * Has the report been optimised for group filtering.
157 *
158 * The functionality for group filtering has been improved but not
159 * all reports have been adjusted to take care of it.
160 *
161 * This property exists to highlight the reports which are still using the
162 * slow method & allow group filtering to still work for them until they
163 * can be migrated.
164 *
165 * In order to protect extensions we have to default to TRUE - but I have
166 * separately marked every class with a groupFilter in the hope that will trigger
167 * people to fix them as they touch them.
168 *
169 * CRM-19170
170 *
171 * @var bool
172 */
173 protected $groupFilterNotOptimised = TRUE;
174
175 /**
176 * Navigation fields
177 *
178 * @var array
179 */
180 public $_navigation = array();
181
182 public $_drilldownReport = array();
183
184 /**
185 * Array of tabs to display on report.
186 *
187 * E.g we define the tab title, the tpl and the tab-specific part of the css or html link.
188 *
189 * $this->tabs['OrderBy'] = array(
190 * 'title' => ts('Sorting'),
191 * 'tpl' => 'OrderBy',
192 * 'div_label' => 'order-by',
193 * );
194 *
195 * @var array
196 */
197 protected $tabs = array();
198
199 /**
200 * Should we add paging.
201 *
202 * @var bool
203 */
204 protected $addPaging = TRUE;
205
206 /**
207 * An attribute for checkbox/radio form field layout
208 *
209 * @var array
210 */
211 protected $_fourColumnAttribute = array(
212 '</td><td width="25%">',
213 '</td><td width="25%">',
214 '</td><td width="25%">',
215 '</tr><tr><td>',
216 );
217
218 protected $_force = 1;
219
220 protected $_params = NULL;
221 protected $_formValues = NULL;
222 protected $_instanceValues = NULL;
223
224 protected $_instanceForm = FALSE;
225 protected $_criteriaForm = FALSE;
226
227 protected $_instanceButtonName = NULL;
228 protected $_createNewButtonName = NULL;
229 protected $_printButtonName = NULL;
230 protected $_pdfButtonName = NULL;
231 protected $_csvButtonName = NULL;
232 protected $_groupButtonName = NULL;
233 protected $_chartButtonName = NULL;
234 protected $_csvSupported = TRUE;
235 protected $_add2groupSupported = TRUE;
236 protected $_groups = NULL;
237 protected $_grandFlag = FALSE;
238 protected $_rowsFound = NULL;
239 protected $_selectAliases = array();
240 protected $_rollup = NULL;
241
242 /**
243 * Table containing list of contact IDs within the group filter.
244 *
245 * @var string
246 */
247 protected $groupTempTable = '';
248
249 /**
250 * @var array
251 */
252 protected $_aliases = array();
253
254 /**
255 * @var string
256 */
257 protected $_where;
258
259 /**
260 * @var string
261 */
262 protected $_from;
263
264 /**
265 * SQL Limit clause
266 * @var string
267 */
268 protected $_limit = NULL;
269
270 /**
271 * This can be set to specify a limit to the number of rows
272 * Since it is currently envisaged as part of the api usage it is only being applied
273 * when $_output mode is not 'html' or 'group' so as not to have to interpret / mess with that part
274 * of the code (see limit() fn.
275 *
276 * @var integer
277 */
278 protected $_limitValue = NULL;
279
280 /**
281 * This can be set to specify row offset
282 * See notes on _limitValue
283 * @var integer
284 */
285 protected $_offsetValue = NULL;
286 /**
287 * @var null
288 */
289 protected $_sections = NULL;
290 protected $_autoIncludeIndexedFieldsAsOrderBys = 0;
291 protected $_absoluteUrl = FALSE;
292
293 /**
294 * Flag to indicate if result-set is to be stored in a class variable which could be retrieved using getResultSet() method.
295 *
296 * @var boolean
297 */
298 protected $_storeResultSet = FALSE;
299
300 /**
301 * When _storeResultSet Flag is set use this var to store result set in form of array
302 *
303 * @var boolean
304 */
305 protected $_resultSet = array();
306
307 /**
308 * To what frequency group-by a date column
309 *
310 * @var array
311 */
312 protected $_groupByDateFreq = array(
313 'MONTH' => 'Month',
314 'YEARWEEK' => 'Week',
315 'QUARTER' => 'Quarter',
316 'YEAR' => 'Year',
317 );
318
319 /**
320 * Variables to hold the acl inner join and where clause
321 */
322 protected $_aclFrom = NULL;
323 protected $_aclWhere = NULL;
324
325 /**
326 * Array of DAO tables having columns included in SELECT or ORDER BY clause.
327 *
328 * Where has also been added to this although perhaps the 'includes both' array should have a different name.
329 *
330 * @var array
331 */
332 protected $_selectedTables;
333
334 /**
335 * Array of DAO tables having columns included in WHERE or HAVING clause
336 *
337 * @var array
338 */
339 protected $filteredTables;
340
341 /**
342 * Output mode e.g 'print', 'csv', 'pdf'.
343 *
344 * @var string
345 */
346 protected $_outputMode;
347
348 /**
349 * Format of any chart in use.
350 *
351 * (it's unclear if this could be merged with outputMode at this stage)
352 *
353 * @var
354 */
355 protected $_format;
356
357 public $_having = NULL;
358 public $_select = NULL;
359 public $_selectClauses = array();
360 public $_columnHeaders = array();
361 public $_orderBy = NULL;
362 public $_orderByFields = array();
363 public $_orderByArray = array();
364 public $_groupBy = NULL;
365 public $_whereClauses = array();
366 public $_havingClauses = array();
367
368 /**
369 * DashBoardRowCount Dashboard row count
370 * @var Integer
371 */
372 public $_dashBoardRowCount;
373
374 /**
375 * Is this being called without a form controller (ie. the report is being render outside the normal form
376 * - e.g the api is retrieving the rows
377 * @var boolean
378 */
379 public $noController = FALSE;
380
381 /**
382 * Variable to hold the currency alias
383 */
384 protected $_currencyColumn = NULL;
385
386 /**
387 * @var string
388 */
389 protected $_interval;
390
391 /**
392 * @var bool
393 */
394 protected $_sendmail;
395
396 /**
397 * @var int
398 */
399 protected $_chartId;
400
401 /**
402 * @var int
403 */
404 public $_section;
405
406 /**
407 * @var string Report description.
408 */
409 public $_description;
410
411 /**
412 * @var bool Is an address field selected.
413 * This was intended to determine if the address table should be joined in
414 * The isTableSelected function is now preferred for this purpose
415 */
416 protected $_addressField;
417
418 /**
419 * @var bool Is an email field selected.
420 * This was intended to determine if the email table should be joined in
421 * The isTableSelected function is now preferred for this purpose
422 */
423 protected $_emailField;
424
425 /**
426 * @var bool Is a phone field selected.
427 * This was intended to determine if the phone table should be joined in
428 * The isTableSelected function is now preferred for this purpose
429 */
430 protected $_phoneField;
431
432 /**
433 * @var bool Create new report instance? (or update existing) on save.
434 */
435 protected $_createNew;
436
437 /**
438 * When a grand total row has calculated the status we pop it off to here.
439 *
440 * This allows us to access it from the stats function and avoid recalculating.
441 */
442 protected $rollupRow = array();
443
444 /**
445 * @var string Database attributes - character set and collation
446 */
447 protected $_databaseAttributes = 'DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci';
448
449 /**
450 * SQL being run in this report.
451 *
452 * The sql in the report is stored in this variable in order to be displayed on the developer tab.
453 *
454 * @var string
455 */
456
457 protected $sql;
458
459 /**
460 * SQL being run in this report as an array.
461 *
462 * The sql in the report is stored in this variable in order to be returned to api & test calls.
463 *
464 * @var string
465 */
466
467 protected $sqlArray;
468 /**
469 * Class constructor.
470 */
471 public function __construct() {
472 parent::__construct();
473
474 $this->addClass('crm-report-form');
475
476 if ($this->_tagFilter) {
477 $this->buildTagFilter();
478 }
479 if ($this->_exposeContactID) {
480 if (array_key_exists('civicrm_contact', $this->_columns)) {
481 $this->_columns['civicrm_contact']['fields']['exposed_id'] = array(
482 'name' => 'id',
483 'title' => ts('Contact ID'),
484 'no_repeat' => TRUE,
485 );
486 }
487 }
488
489 if ($this->_groupFilter) {
490 $this->buildGroupFilter();
491 }
492
493 // Get all custom groups
494 $allGroups = CRM_Core_PseudoConstant::get('CRM_Core_DAO_CustomField', 'custom_group_id');
495
496 // Get the custom groupIds for which the user has VIEW permission
497 // If the user has 'access all custom data' permission, we'll leave $permCustomGroupIds empty
498 // and addCustomDataToColumns() will allow access to all custom groups.
499 $permCustomGroupIds = array();
500 if (!CRM_Core_Permission::check('access all custom data')) {
501 $permCustomGroupIds = CRM_ACL_API::group(CRM_Core_Permission::VIEW, NULL, 'civicrm_custom_group', $allGroups, NULL);
502 // do not allow custom data for reports if user doesn't have
503 // permission to access custom data.
504 if (!empty($this->_customGroupExtends) && empty($permCustomGroupIds)) {
505 $this->_customGroupExtends = array();
506 }
507 }
508
509 // merge custom data columns to _columns list, if any
510 $this->addCustomDataToColumns(TRUE, $permCustomGroupIds);
511
512 // add / modify display columns, filters ..etc
513 CRM_Utils_Hook::alterReportVar('columns', $this->_columns, $this);
514
515 //assign currencyColumn variable to tpl
516 $this->assign('currencyColumn', $this->_currencyColumn);
517 }
518
519 /**
520 * Shared pre-process function.
521 *
522 * If overriding preProcess function this should still be called.
523 *
524 * @throws \Exception
525 */
526 public function preProcessCommon() {
527 $this->_force = 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 if ($this->_storeResultSet) {
3116 $this->_resultSet = $rows;
3117 }
3118
3119 if ($this->_outputMode == 'print' ||
3120 $this->_outputMode == 'pdf' ||
3121 $this->_sendmail
3122 ) {
3123
3124 $content = $this->compileContent();
3125 $url = CRM_Utils_System::url("civicrm/report/instance/{$this->_id}",
3126 "reset=1", TRUE
3127 );
3128
3129 if ($this->_sendmail) {
3130 $config = CRM_Core_Config::singleton();
3131 $attachments = array();
3132
3133 if ($this->_outputMode == 'csv') {
3134 $content
3135 = $this->_formValues['report_header'] . '<p>' . ts('Report URL') .
3136 ": {$url}</p>" . '<p>' .
3137 ts('The report is attached as a CSV file.') . '</p>' .
3138 $this->_formValues['report_footer'];
3139
3140 $csvFullFilename = $config->templateCompileDir .
3141 CRM_Utils_File::makeFileName('CiviReport.csv');
3142 $csvContent = CRM_Report_Utils_Report::makeCsv($this, $rows);
3143 file_put_contents($csvFullFilename, $csvContent);
3144 $attachments[] = array(
3145 'fullPath' => $csvFullFilename,
3146 'mime_type' => 'text/csv',
3147 'cleanName' => 'CiviReport.csv',
3148 );
3149 }
3150 if ($this->_outputMode == 'pdf') {
3151 // generate PDF content
3152 $pdfFullFilename = $config->templateCompileDir .
3153 CRM_Utils_File::makeFileName('CiviReport.pdf');
3154 file_put_contents($pdfFullFilename,
3155 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf",
3156 TRUE, array('orientation' => 'landscape')
3157 )
3158 );
3159 // generate Email Content
3160 $content
3161 = $this->_formValues['report_header'] . '<p>' . ts('Report URL') .
3162 ": {$url}</p>" . '<p>' .
3163 ts('The report is attached as a PDF file.') . '</p>' .
3164 $this->_formValues['report_footer'];
3165
3166 $attachments[] = array(
3167 'fullPath' => $pdfFullFilename,
3168 'mime_type' => 'application/pdf',
3169 'cleanName' => 'CiviReport.pdf',
3170 );
3171 }
3172
3173 if (CRM_Report_Utils_Report::mailReport($content, $this->_id,
3174 $this->_outputMode, $attachments
3175 )
3176 ) {
3177 CRM_Core_Session::setStatus(ts("Report mail has been sent."), ts('Sent'), 'success');
3178 }
3179 else {
3180 CRM_Core_Session::setStatus(ts("Report mail could not be sent."), ts('Mail Error'), 'error');
3181 }
3182 return;
3183 }
3184 elseif ($this->_outputMode == 'print') {
3185 echo $content;
3186 }
3187 else {
3188 if ($chartType = CRM_Utils_Array::value('charts', $this->_params)) {
3189 $config = CRM_Core_Config::singleton();
3190 //get chart image name
3191 $chartImg = $this->_chartId . '.png';
3192 //get image url path
3193 $uploadUrl
3194 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadURL) .
3195 'openFlashChart/';
3196 $uploadUrl .= $chartImg;
3197 //get image doc path to overwrite
3198 $uploadImg
3199 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir) .
3200 'openFlashChart/' . $chartImg;
3201 //Load the image
3202 $chart = imagecreatefrompng($uploadUrl);
3203 //convert it into formatted png
3204 CRM_Utils_System::setHttpHeader('Content-type', 'image/png');
3205 //overwrite with same image
3206 imagepng($chart, $uploadImg);
3207 //delete the object
3208 imagedestroy($chart);
3209 }
3210 CRM_Utils_PDF_Utils::html2pdf($content, "CiviReport.pdf", FALSE, array('orientation' => 'landscape'));
3211 }
3212 CRM_Utils_System::civiExit();
3213 }
3214 elseif ($this->_outputMode == 'csv') {
3215 CRM_Report_Utils_Report::export2csv($this, $rows);
3216 }
3217 elseif ($this->_outputMode == 'group') {
3218 $group = $this->_params['groups'];
3219 $this->add2group($group);
3220 }
3221 }
3222
3223 /**
3224 * Set store result set indicator to TRUE.
3225 *
3226 * @todo explain what this does
3227 */
3228 public function storeResultSet() {
3229 $this->_storeResultSet = TRUE;
3230 }
3231
3232 /**
3233 * Get result set.
3234 *
3235 * @return bool
3236 */
3237 public function getResultSet() {
3238 return $this->_resultSet;
3239 }
3240
3241 /**
3242 * Get the sql used to generate the report.
3243 *
3244 * @return string
3245 */
3246 public function getReportSql() {
3247 return $this->sqlArray;
3248 }
3249
3250 /**
3251 * Use the form name to create the tpl file name.
3252 *
3253 * @return string
3254 */
3255 public function getTemplateFileName() {
3256 $defaultTpl = parent::getTemplateFileName();
3257 $template = CRM_Core_Smarty::singleton();
3258 if (!$template->template_exists($defaultTpl)) {
3259 $defaultTpl = 'CRM/Report/Form.tpl';
3260 }
3261 return $defaultTpl;
3262 }
3263
3264 /**
3265 * Compile the report content.
3266 *
3267 * Although this function is super-short it is useful to keep separate so it can be over-ridden by report classes.
3268 *
3269 * @return string
3270 */
3271 public function compileContent() {
3272 $templateFile = $this->getHookedTemplateFileName();
3273 return CRM_Utils_Array::value('report_header', $this->_formValues) .
3274 CRM_Core_Form::$_template->fetch($templateFile) .
3275 CRM_Utils_Array::value('report_footer', $this->_formValues);
3276 }
3277
3278
3279 /**
3280 * Post process function.
3281 */
3282 public function postProcess() {
3283 // get ready with post process params
3284 $this->beginPostProcess();
3285
3286 // build query
3287 $sql = $this->buildQuery();
3288
3289 // build array of result based on column headers. This method also allows
3290 // modifying column headers before using it to build result set i.e $rows.
3291 $rows = array();
3292 $this->buildRows($sql, $rows);
3293
3294 // format result set.
3295 $this->formatDisplay($rows);
3296
3297 // assign variables to templates
3298 $this->doTemplateAssignment($rows);
3299
3300 // do print / pdf / instance stuff if needed
3301 $this->endPostProcess($rows);
3302 }
3303
3304 /**
3305 * Set limit.
3306 *
3307 * @param int $rowCount
3308 *
3309 * @return array
3310 */
3311 public function limit($rowCount = self::ROW_COUNT_LIMIT) {
3312 // lets do the pager if in html mode
3313 $this->_limit = NULL;
3314
3315 // CRM-14115, over-ride row count if rowCount is specified in URL
3316 if ($this->_dashBoardRowCount) {
3317 $rowCount = $this->_dashBoardRowCount;
3318 }
3319 if ($this->addPaging) {
3320 $this->_select = str_ireplace('SELECT ', 'SELECT SQL_CALC_FOUND_ROWS ', $this->_select);
3321
3322 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer');
3323
3324 // @todo all http vars should be extracted in the preProcess
3325 // - not randomly in the class
3326 if (!$pageId && !empty($_POST)) {
3327 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
3328 $pageId = max((int) $_POST['crmPID_B'], 1);
3329 }
3330 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
3331 $pageId = max((int) $_POST['crmPID'], 1);
3332 }
3333 unset($_POST['crmPID_B'], $_POST['crmPID']);
3334 }
3335
3336 $pageId = $pageId ? $pageId : 1;
3337 $this->set(CRM_Utils_Pager::PAGE_ID, $pageId);
3338 $offset = ($pageId - 1) * $rowCount;
3339
3340 $offset = CRM_Utils_Type::escape($offset, 'Int');
3341 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
3342
3343 $this->_limit = " LIMIT $offset, $rowCount";
3344 return array($offset, $rowCount);
3345 }
3346 if ($this->_limitValue) {
3347 if ($this->_offsetValue) {
3348 $this->_limit = " LIMIT {$this->_offsetValue}, {$this->_limitValue} ";
3349 }
3350 else {
3351 $this->_limit = " LIMIT " . $this->_limitValue;
3352 }
3353 }
3354 }
3355
3356 /**
3357 * Set pager.
3358 *
3359 * @param int $rowCount
3360 */
3361 public function setPager($rowCount = self::ROW_COUNT_LIMIT) {
3362 // CRM-14115, over-ride row count if rowCount is specified in URL
3363 if ($this->_dashBoardRowCount) {
3364 $rowCount = $this->_dashBoardRowCount;
3365 }
3366
3367 if ($this->_limit && ($this->_limit != '')) {
3368 if (!$this->_rowsFound) {
3369 $sql = "SELECT FOUND_ROWS();";
3370 $this->_rowsFound = CRM_Core_DAO::singleValueQuery($sql);
3371 }
3372 $params = array(
3373 'total' => $this->_rowsFound,
3374 'rowCount' => $rowCount,
3375 'status' => ts('Records') . ' %%StatusMessage%%',
3376 'buttonBottom' => 'PagerBottomButton',
3377 'buttonTop' => 'PagerTopButton',
3378 );
3379 if (!empty($this->controller)) {
3380 // This happens when being called from the api Really we want the api to be able to
3381 // pass paging parameters, but at this stage just preventing test crashes.
3382 $params['pageID'] = $this->get(CRM_Utils_Pager::PAGE_ID);
3383 }
3384
3385 $pager = new CRM_Utils_Pager($params);
3386 $this->assign_by_ref('pager', $pager);
3387 $this->ajaxResponse['totalRows'] = $this->_rowsFound;
3388 }
3389 }
3390
3391 /**
3392 * Build a group filter with contempt for large data sets.
3393 *
3394 * This function has been retained as it takes time to migrate the reports over
3395 * to the new method which will not crash on large datasets.
3396 *
3397 * @deprecated
3398 *
3399 * @param string $field
3400 * @param mixed $value
3401 * @param string $op
3402 *
3403 * @return string
3404 */
3405 public function legacySlowGroupFilterClause($field, $value, $op) {
3406 $smartGroupQuery = "";
3407
3408 $group = new CRM_Contact_DAO_Group();
3409 $group->is_active = 1;
3410 $group->find();
3411 $smartGroups = array();
3412 while ($group->fetch()) {
3413 if (in_array($group->id, $this->_params['gid_value']) &&
3414 $group->saved_search_id
3415 ) {
3416 $smartGroups[] = $group->id;
3417 }
3418 }
3419
3420 CRM_Contact_BAO_GroupContactCache::check($smartGroups);
3421
3422 $smartGroupQuery = '';
3423 if (!empty($smartGroups)) {
3424 $smartGroups = implode(',', $smartGroups);
3425 $smartGroupQuery = " UNION DISTINCT
3426 SELECT DISTINCT smartgroup_contact.contact_id
3427 FROM civicrm_group_contact_cache smartgroup_contact
3428 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3429 }
3430
3431 $sqlOp = $this->getSQLOperator($op);
3432 if (!is_array($value)) {
3433 $value = array($value);
3434 }
3435 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3436
3437 $contactAlias = $this->_aliases['civicrm_contact'];
3438 if (!empty($this->relationType) && $this->relationType == 'b_a') {
3439 $contactAlias = $this->_aliases['civicrm_contact_b'];
3440 }
3441 return " {$contactAlias}.id {$sqlOp} (
3442 SELECT DISTINCT {$this->_aliases['civicrm_group']}.contact_id
3443 FROM civicrm_group_contact {$this->_aliases['civicrm_group']}
3444 WHERE {$clause} AND {$this->_aliases['civicrm_group']}.status = 'Added'
3445 {$smartGroupQuery} ) ";
3446 }
3447
3448 /**
3449 * Build where clause for groups.
3450 *
3451 * @param string $field
3452 * @param mixed $value
3453 * @param string $op
3454 *
3455 * @return string
3456 */
3457 public function whereGroupClause($field, $value, $op) {
3458 if ($this->groupFilterNotOptimised) {
3459 return $this->legacySlowGroupFilterClause($field, $value, $op);
3460 }
3461 if ($op === 'notin') {
3462 return " group_temp_table.id IS NULL ";
3463 }
3464 // We will have used an inner join instead.
3465 return "1";
3466 }
3467
3468
3469 /**
3470 * Create a table of the contact ids included by the group filter.
3471 *
3472 * This function is called by both the api (tests) and the UI.
3473 */
3474 public function buildGroupTempTable() {
3475 if (!empty($this->groupTempTable) || empty ($this->_params['gid_value']) || $this->groupFilterNotOptimised) {
3476 return;
3477 }
3478 $filteredGroups = (array) $this->_params['gid_value'];
3479
3480 $groups = civicrm_api3('Group', 'get', array(
3481 'is_active' => 1,
3482 'id' => array('IN' => $filteredGroups),
3483 'saved_search_id' => array('>' => 0),
3484 'return' => 'id',
3485 ));
3486 $smartGroups = array_keys($groups['values']);
3487
3488 $query = "
3489 SELECT group_contact.contact_id as id
3490 FROM civicrm_group_contact group_contact
3491 WHERE group_contact.group_id IN (" . implode(', ', $filteredGroups) . ")
3492 AND group_contact.status = 'Added' ";
3493
3494 if (!empty($smartGroups)) {
3495 CRM_Contact_BAO_GroupContactCache::check($smartGroups);
3496 $smartGroups = implode(',', $smartGroups);
3497 $query .= "
3498 UNION DISTINCT
3499 SELECT smartgroup_contact.contact_id as id
3500 FROM civicrm_group_contact_cache smartgroup_contact
3501 WHERE smartgroup_contact.group_id IN ({$smartGroups}) ";
3502 }
3503
3504 $this->groupTempTable = 'civicrm_report_temp_group_' . date('Ymd_') . uniqid();
3505 $this->executeReportQuery("
3506 CREATE TEMPORARY TABLE $this->groupTempTable
3507 $query
3508 ");
3509 CRM_Core_DAO::executeQuery("ALTER TABLE $this->groupTempTable ADD INDEX i_id(id)");
3510 }
3511
3512 /**
3513 * Execute query and add it to the developer tab.
3514 *
3515 * @param string $query
3516 * @param array $params
3517 *
3518 * @return \CRM_Core_DAO|object
3519 */
3520 protected function executeReportQuery($query, $params = array()) {
3521 $this->addToDeveloperTab($query);
3522 return CRM_Core_DAO::executeQuery($query, $params);
3523 }
3524
3525 /**
3526 * Build where clause for tags.
3527 *
3528 * @param string $field
3529 * @param mixed $value
3530 * @param string $op
3531 *
3532 * @return string
3533 */
3534 public function whereTagClause($field, $value, $op) {
3535 // not using left join in query because if any contact
3536 // belongs to more than one tag, results duplicate
3537 // entries.
3538 $sqlOp = $this->getSQLOperator($op);
3539 if (!is_array($value)) {
3540 $value = array($value);
3541 }
3542 $clause = "{$field['dbAlias']} IN (" . implode(', ', $value) . ")";
3543 $entity_table = $this->_tagFilterTable;
3544 return " {$this->_aliases[$entity_table]}.id {$sqlOp} (
3545 SELECT DISTINCT {$this->_aliases['civicrm_tag']}.entity_id
3546 FROM civicrm_entity_tag {$this->_aliases['civicrm_tag']}
3547 WHERE entity_table = '$entity_table' AND {$clause} ) ";
3548 }
3549
3550 /**
3551 * Generate membership organization clause.
3552 *
3553 * @param mixed $value
3554 * @param string $op SQL Operator
3555 *
3556 * @return string
3557 */
3558 public function whereMembershipOrgClause($value, $op) {
3559 $sqlOp = $this->getSQLOperator($op);
3560 if (!is_array($value)) {
3561 $value = array($value);
3562 }
3563
3564 $tmp_membership_org_sql_list = implode(', ', $value);
3565 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3566 SELECT DISTINCT mem.contact_id
3567 FROM civicrm_membership mem
3568 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3569 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3570 WHERE mt.member_of_contact_id IN (" .
3571 $tmp_membership_org_sql_list . ")
3572 AND mt.is_active = '1'
3573 AND mem_status.is_current_member = '1'
3574 AND mem_status.is_active = '1' ) ";
3575 }
3576
3577 /**
3578 * Generate Membership Type SQL Clause.
3579 *
3580 * @param mixed $value
3581 * @param string $op
3582 *
3583 * @return string
3584 * SQL query string
3585 */
3586 public function whereMembershipTypeClause($value, $op) {
3587 $sqlOp = $this->getSQLOperator($op);
3588 if (!is_array($value)) {
3589 $value = array($value);
3590 }
3591
3592 $tmp_membership_sql_list = implode(', ', $value);
3593 return " {$this->_aliases['civicrm_contact']}.id {$sqlOp} (
3594 SELECT DISTINCT mem.contact_id
3595 FROM civicrm_membership mem
3596 LEFT JOIN civicrm_membership_status mem_status ON mem.status_id = mem_status.id
3597 LEFT JOIN civicrm_membership_type mt ON mem.membership_type_id = mt.id
3598 WHERE mem.membership_type_id IN (" .
3599 $tmp_membership_sql_list . ")
3600 AND mt.is_active = '1'
3601 AND mem_status.is_current_member = '1'
3602 AND mem_status.is_active = '1' ) ";
3603 }
3604
3605 /**
3606 * Build acl clauses.
3607 *
3608 * @param string $tableAlias
3609 */
3610 public function buildACLClause($tableAlias = 'contact_a') {
3611 list($this->_aclFrom, $this->_aclWhere) = CRM_Contact_BAO_Contact_Permission::cacheClause($tableAlias);
3612 }
3613
3614 /**
3615 * Add custom data to the columns.
3616 *
3617 * @param bool $addFields
3618 * @param array $permCustomGroupIds
3619 */
3620 public function addCustomDataToColumns($addFields = TRUE, $permCustomGroupIds = array()) {
3621 if (empty($this->_customGroupExtends)) {
3622 return;
3623 }
3624 if (!is_array($this->_customGroupExtends)) {
3625 $this->_customGroupExtends = array($this->_customGroupExtends);
3626 }
3627 $customGroupWhere = '';
3628 if (!empty($permCustomGroupIds)) {
3629 $customGroupWhere = "cg.id IN (" . implode(',', $permCustomGroupIds) .
3630 ") AND";
3631 }
3632 $sql = "
3633 SELECT cg.table_name, cg.title, cg.extends, cf.id as cf_id, cf.label,
3634 cf.column_name, cf.data_type, cf.html_type, cf.option_group_id, cf.time_format
3635 FROM civicrm_custom_group cg
3636 INNER JOIN civicrm_custom_field cf ON cg.id = cf.custom_group_id
3637 WHERE cg.extends IN ('" . implode("','", $this->_customGroupExtends) . "') AND
3638 {$customGroupWhere}
3639 cg.is_active = 1 AND
3640 cf.is_active = 1 AND
3641 cf.is_searchable = 1
3642 ORDER BY cg.weight, cf.weight";
3643 $customDAO = CRM_Core_DAO::executeQuery($sql);
3644
3645 $curTable = NULL;
3646 while ($customDAO->fetch()) {
3647 if ($customDAO->table_name != $curTable) {
3648 $curTable = $customDAO->table_name;
3649 $curFields = $curFilters = array();
3650
3651 // dummy dao object
3652 $this->_columns[$curTable]['dao'] = 'CRM_Contact_DAO_Contact';
3653 $this->_columns[$curTable]['extends'] = $customDAO->extends;
3654 $this->_columns[$curTable]['grouping'] = $customDAO->table_name;
3655 $this->_columns[$curTable]['group_title'] = $customDAO->title;
3656
3657 foreach (array('fields', 'filters', 'group_bys') as $colKey) {
3658 if (!array_key_exists($colKey, $this->_columns[$curTable])) {
3659 $this->_columns[$curTable][$colKey] = array();
3660 }
3661 }
3662 }
3663 $fieldName = 'custom_' . $customDAO->cf_id;
3664
3665 if ($addFields) {
3666 // this makes aliasing work in favor
3667 $curFields[$fieldName] = array(
3668 'name' => $customDAO->column_name,
3669 'title' => $customDAO->label,
3670 'dataType' => $customDAO->data_type,
3671 'htmlType' => $customDAO->html_type,
3672 );
3673 }
3674 if ($this->_customGroupFilters) {
3675 // this makes aliasing work in favor
3676 $curFilters[$fieldName] = array(
3677 'name' => $customDAO->column_name,
3678 'title' => $customDAO->label,
3679 'dataType' => $customDAO->data_type,
3680 'htmlType' => $customDAO->html_type,
3681 );
3682 }
3683
3684 switch ($customDAO->data_type) {
3685 case 'Date':
3686 // filters
3687 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_DATE;
3688 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_DATE;
3689 // CRM-6946, show time part for datetime date fields
3690 if ($customDAO->time_format) {
3691 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_TIMESTAMP;
3692 }
3693 break;
3694
3695 case 'Boolean':
3696 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_SELECT;
3697 $curFilters[$fieldName]['options'] = array('' => ts('- select -')) + CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id, array(), 'search');
3698 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
3699 break;
3700
3701 case 'Int':
3702 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_INT;
3703 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_INT;
3704 break;
3705
3706 case 'Money':
3707 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
3708 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_MONEY;
3709 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_MONEY;
3710 break;
3711
3712 case 'Float':
3713 $curFilters[$fieldName]['operatorType'] = CRM_Report_Form::OP_FLOAT;
3714 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_FLOAT;
3715 break;
3716
3717 case 'String':
3718 case 'StateProvince':
3719 case 'Country':
3720 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3721
3722 $options = CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id, array(), 'search');
3723 if ($options !== FALSE) {
3724 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField::isSerialized($customDAO) ? CRM_Report_Form::OP_MULTISELECT_SEPARATOR : CRM_Report_Form::OP_MULTISELECT;
3725 $curFilters[$fieldName]['options'] = $options;
3726 }
3727 break;
3728
3729 case 'ContactReference':
3730 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3731 $curFilters[$fieldName]['name'] = 'display_name';
3732 $curFilters[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3733
3734 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3735 $curFields[$fieldName]['name'] = 'display_name';
3736 $curFields[$fieldName]['alias'] = "contact_{$fieldName}_civireport";
3737 break;
3738
3739 default:
3740 $curFields[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3741 $curFilters[$fieldName]['type'] = CRM_Utils_Type::T_STRING;
3742 }
3743
3744 // CRM-19401 fix
3745 if ($customDAO->html_type == 'Select' && !array_key_exists('options', $curFilters[$fieldName])) {
3746 $options = CRM_Core_PseudoConstant::get('CRM_Core_BAO_CustomField', 'custom_' . $customDAO->cf_id, array(), 'search');
3747 if ($options !== FALSE) {
3748 $curFilters[$fieldName]['operatorType'] = CRM_Core_BAO_CustomField::isSerialized($customDAO) ? CRM_Report_Form::OP_MULTISELECT_SEPARATOR : CRM_Report_Form::OP_MULTISELECT;
3749 $curFilters[$fieldName]['options'] = $options;
3750 }
3751 }
3752
3753 if (!array_key_exists('type', $curFields[$fieldName])) {
3754 $curFields[$fieldName]['type'] = CRM_Utils_Array::value('type', $curFilters[$fieldName], array());
3755 }
3756
3757 if ($addFields) {
3758 $this->_columns[$curTable]['fields'] = array_merge($this->_columns[$curTable]['fields'], $curFields);
3759 }
3760 if ($this->_customGroupFilters) {
3761 $this->_columns[$curTable]['filters'] = array_merge($this->_columns[$curTable]['filters'], $curFilters);
3762 }
3763 if ($this->_customGroupGroupBy) {
3764 $this->_columns[$curTable]['group_bys'] = array_merge($this->_columns[$curTable]['group_bys'], $curFields);
3765 }
3766 }
3767 }
3768
3769 /**
3770 * Build custom data from clause.
3771 *
3772 * @param bool $joinsForFiltersOnly
3773 * Only include joins to support filters. This would be used if creating a table of contacts to include first.
3774 */
3775 public function customDataFrom($joinsForFiltersOnly = FALSE) {
3776 if (empty($this->_customGroupExtends)) {
3777 return;
3778 }
3779 $mapper = CRM_Core_BAO_CustomQuery::$extendsMap;
3780 //CRM-18276 GROUP_CONCAT could be used with singleValueQuery and then exploded,
3781 //but by default that truncates to 1024 characters, which causes errors with installs with lots of custom field sets
3782 $customTables = array();
3783 $customTablesDAO = CRM_Core_DAO::executeQuery("SELECT table_name FROM civicrm_custom_group");
3784 while ($customTablesDAO->fetch()) {
3785 $customTables[] = $customTablesDAO->table_name;
3786 }
3787
3788 foreach ($this->_columns as $table => $prop) {
3789 if (in_array($table, $customTables)) {
3790 $extendsTable = $mapper[$prop['extends']];
3791 // Check field is required for rendering the report.
3792 if ((!$this->isFieldSelected($prop)) || ($joinsForFiltersOnly && !$this->isFieldFiltered($prop))) {
3793 continue;
3794 }
3795 $baseJoin = CRM_Utils_Array::value($prop['extends'], $this->_customGroupExtendsJoin, "{$this->_aliases[$extendsTable]}.id");
3796
3797 $customJoin = is_array($this->_customGroupJoin) ? $this->_customGroupJoin[$table] : $this->_customGroupJoin;
3798 $this->_from .= "
3799 {$customJoin} {$table} {$this->_aliases[$table]} ON {$this->_aliases[$table]}.entity_id = {$baseJoin}";
3800 // handle for ContactReference
3801 if (array_key_exists('fields', $prop)) {
3802 foreach ($prop['fields'] as $fieldName => $field) {
3803 if (CRM_Utils_Array::value('dataType', $field) ==
3804 'ContactReference'
3805 ) {
3806 $columnName = CRM_Core_DAO::getFieldValue('CRM_Core_DAO_CustomField', CRM_Core_BAO_CustomField::getKeyID($fieldName), 'column_name');
3807 $this->_from .= "
3808 LEFT JOIN civicrm_contact {$field['alias']} ON {$field['alias']}.id = {$this->_aliases[$table]}.{$columnName} ";
3809 }
3810 }
3811 }
3812 }
3813 }
3814 }
3815
3816 /**
3817 * Check if the field is selected.
3818 *
3819 * @param string $prop
3820 *
3821 * @return bool
3822 */
3823 public function isFieldSelected($prop) {
3824 if (empty($prop)) {
3825 return FALSE;
3826 }
3827
3828 if (!empty($this->_params['fields'])) {
3829 foreach (array_keys($prop['fields']) as $fieldAlias) {
3830 $customFieldId = CRM_Core_BAO_CustomField::getKeyID($fieldAlias);
3831 if ($customFieldId) {
3832 if (array_key_exists($fieldAlias, $this->_params['fields'])) {
3833 return TRUE;
3834 }
3835
3836 //might be survey response field.
3837 if (!empty($this->_params['fields']['survey_response']) &&
3838 !empty($prop['fields'][$fieldAlias]['isSurveyResponseField'])
3839 ) {
3840 return TRUE;
3841 }
3842 }
3843 }
3844 }
3845
3846 if (!empty($this->_params['group_bys']) && $this->_customGroupGroupBy) {
3847 foreach (array_keys($prop['group_bys']) as $fieldAlias) {
3848 if (array_key_exists($fieldAlias, $this->_params['group_bys']) &&
3849 CRM_Core_BAO_CustomField::getKeyID($fieldAlias)
3850 ) {
3851 return TRUE;
3852 }
3853 }
3854 }
3855
3856 if (!empty($this->_params['order_bys'])) {
3857 foreach (array_keys($prop['fields']) as $fieldAlias) {
3858 foreach ($this->_params['order_bys'] as $orderBy) {
3859 if ($fieldAlias == $orderBy['column'] &&
3860 CRM_Core_BAO_CustomField::getKeyID($fieldAlias)
3861 ) {
3862 return TRUE;
3863 }
3864 }
3865 }
3866 }
3867 return $this->isFieldFiltered($prop);
3868
3869 }
3870
3871 /**
3872 * Check if the field is used as a filter.
3873 *
3874 * @param string $prop
3875 *
3876 * @return bool
3877 */
3878 protected function isFieldFiltered($prop) {
3879 if (!empty($prop['filters']) && $this->_customGroupFilters) {
3880 foreach ($prop['filters'] as $fieldAlias => $val) {
3881 foreach (array(
3882 'value',
3883 'min',
3884 'max',
3885 'relative',
3886 'from',
3887 'to',
3888 ) as $attach) {
3889 if (isset($this->_params[$fieldAlias . '_' . $attach]) &&
3890 (!empty($this->_params[$fieldAlias . '_' . $attach])
3891 || ($attach != 'relative' &&
3892 $this->_params[$fieldAlias . '_' . $attach] == '0')
3893 )
3894 ) {
3895 return TRUE;
3896 }
3897 }
3898 if (!empty($this->_params[$fieldAlias . '_op']) &&
3899 in_array($this->_params[$fieldAlias . '_op'], array('nll', 'nnll'))
3900 ) {
3901 return TRUE;
3902 }
3903 }
3904 }
3905
3906 return FALSE;
3907 }
3908
3909 /**
3910 * Check for empty order_by configurations and remove them.
3911 *
3912 * Also set template to hide them.
3913 *
3914 * @param array $formValues
3915 */
3916 public function preProcessOrderBy(&$formValues) {
3917 // Object to show/hide form elements
3918 $_showHide = new CRM_Core_ShowHideBlocks('', '');
3919
3920 $_showHide->addShow('optionField_1');
3921
3922 // Cycle through order_by options; skip any empty ones, and hide them as well
3923 $n = 1;
3924
3925 if (!empty($formValues['order_bys'])) {
3926 foreach ($formValues['order_bys'] as $order_by) {
3927 if ($order_by['column'] && $order_by['column'] != '-') {
3928 $_showHide->addShow('optionField_' . $n);
3929 $orderBys[$n] = $order_by;
3930 $n++;
3931 }
3932 }
3933 }
3934 for ($i = $n; $i <= 5; $i++) {
3935 if ($i > 1) {
3936 $_showHide->addHide('optionField_' . $i);
3937 }
3938 }
3939
3940 // overwrite order_by options with modified values
3941 if (!empty($orderBys)) {
3942 $formValues['order_bys'] = $orderBys;
3943 }
3944 else {
3945 $formValues['order_bys'] = array(1 => array('column' => '-'));
3946 }
3947
3948 // assign show/hide data to template
3949 $_showHide->addToTemplate();
3950 }
3951
3952 /**
3953 * Check if table name has columns in SELECT clause.
3954 *
3955 * @param string $tableName
3956 * Name of table (index of $this->_columns array).
3957 *
3958 * @return bool
3959 */
3960 public function isTableSelected($tableName) {
3961 return in_array($tableName, $this->selectedTables());
3962 }
3963
3964 /**
3965 * Check if table name has columns in WHERE or HAVING clause.
3966 *
3967 * @param string $tableName
3968 * Name of table (index of $this->_columns array).
3969 *
3970 * @return bool
3971 */
3972 public function isTableFiltered($tableName) {
3973 // Cause the array to be generated if not previously done.
3974 if (!$this->_selectedTables && !$this->filteredTables) {
3975 $this->selectedTables();
3976 }
3977 return in_array($tableName, $this->filteredTables);
3978 }
3979
3980 /**
3981 * Fetch array of DAO tables having columns included in SELECT or ORDER BY clause.
3982 *
3983 * If the array is unset it will be built.
3984 *
3985 * @return array
3986 * selectedTables
3987 */
3988 public function selectedTables() {
3989 if (!$this->_selectedTables) {
3990 $orderByColumns = array();
3991 if (array_key_exists('order_bys', $this->_params) &&
3992 is_array($this->_params['order_bys'])
3993 ) {
3994 foreach ($this->_params['order_bys'] as $orderBy) {
3995 $orderByColumns[] = $orderBy['column'];
3996 }
3997 }
3998
3999 foreach ($this->_columns as $tableName => $table) {
4000 if (array_key_exists('fields', $table)) {
4001 foreach ($table['fields'] as $fieldName => $field) {
4002 if (!empty($field['required']) ||
4003 !empty($this->_params['fields'][$fieldName])
4004 ) {
4005 $this->_selectedTables[] = $tableName;
4006 break;
4007 }
4008 }
4009 }
4010 if (array_key_exists('order_bys', $table)) {
4011 foreach ($table['order_bys'] as $orderByName => $orderBy) {
4012 if (in_array($orderByName, $orderByColumns)) {
4013 $this->_selectedTables[] = $tableName;
4014 break;
4015 }
4016 }
4017 }
4018 if (array_key_exists('filters', $table)) {
4019 foreach ($table['filters'] as $filterName => $filter) {
4020 if (!empty($this->_params["{$filterName}_value"]) ||
4021 CRM_Utils_Array::value("{$filterName}_op", $this->_params) ==
4022 'nll' ||
4023 CRM_Utils_Array::value("{$filterName}_op", $this->_params) ==
4024 'nnll'
4025 ) {
4026 $this->_selectedTables[] = $tableName;
4027 $this->filteredTables[] = $tableName;
4028 break;
4029 }
4030 }
4031 }
4032 }
4033 }
4034 return $this->_selectedTables;
4035 }
4036
4037 /**
4038 * Add address fields.
4039 *
4040 * @deprecated - use getAddressColumns which is a more accurate description
4041 * and also accepts an array of options rather than a long list
4042 *
4043 * adding address fields to construct function in reports
4044 *
4045 * @param bool $groupBy
4046 * Add GroupBy? Not appropriate for detail report.
4047 * @param bool $orderBy
4048 * Add GroupBy? Not appropriate for detail report.
4049 * @param bool $filters
4050 * @param array $defaults
4051 *
4052 * @return array
4053 * address fields for construct clause
4054 */
4055 public function addAddressFields($groupBy = TRUE, $orderBy = FALSE, $filters = TRUE, $defaults = array('country_id' => TRUE)) {
4056 $defaultAddressFields = array(
4057 'street_address' => ts('Street Address'),
4058 'supplemental_address_1' => ts('Supplementary Address Field 1'),
4059 'supplemental_address_2' => ts('Supplementary Address Field 2'),
4060 'street_number' => ts('Street Number'),
4061 'street_name' => ts('Street Name'),
4062 'street_unit' => ts('Street Unit'),
4063 'city' => ts('City'),
4064 'postal_code' => ts('Postal Code'),
4065 'postal_code_suffix' => ts('Postal Code Suffix'),
4066 'country_id' => ts('Country'),
4067 'state_province_id' => ts('State/Province'),
4068 'county_id' => ts('County'),
4069 );
4070 $addressFields = array(
4071 'civicrm_address' => array(
4072 'dao' => 'CRM_Core_DAO_Address',
4073 'fields' => array(
4074 'address_name' => array(
4075 'title' => ts('Address Name'),
4076 'default' => CRM_Utils_Array::value('name', $defaults, FALSE),
4077 'name' => 'name',
4078 ),
4079 ),
4080 'grouping' => 'location-fields',
4081 ),
4082 );
4083 foreach ($defaultAddressFields as $fieldName => $fieldLabel) {
4084 $addressFields['civicrm_address']['fields'][$fieldName] = array(
4085 'title' => $fieldLabel,
4086 'default' => CRM_Utils_Array::value($fieldName, $defaults, FALSE),
4087 );
4088 }
4089
4090 $street_address_filters = $general_address_filters = array();
4091 if ($filters) {
4092 // Address filter depends on whether street address parsing is enabled.
4093 // (CRM-18696)
4094 $addressOptions = CRM_Core_BAO_Setting::valueOptions(CRM_Core_BAO_Setting::SYSTEM_PREFERENCES_NAME,
4095 'address_options'
4096 );
4097 if ($addressOptions['street_address_parsing']) {
4098 $street_address_filters = array(
4099 'street_number' => array(
4100 'title' => ts('Street Number'),
4101 'type' => CRM_Utils_Type::T_INT,
4102 'name' => 'street_number',
4103 ),
4104 'street_name' => array(
4105 'title' => ts('Street Name'),
4106 'name' => 'street_name',
4107 'type' => CRM_Utils_Type::T_STRING,
4108 ),
4109 );
4110 }
4111 else {
4112 $street_address_filters = array(
4113 'street_address' => array(
4114 'title' => ts('Street Address'),
4115 'type' => CRM_Utils_Type::T_STRING,
4116 'name' => 'street_address',
4117 ),
4118 );
4119 }
4120 $general_address_filters = array(
4121 'postal_code' => array(
4122 'title' => ts('Postal Code'),
4123 'type' => CRM_Utils_Type::T_STRING,
4124 'name' => 'postal_code',
4125 ),
4126 'city' => array(
4127 'title' => ts('City'),
4128 'type' => CRM_Utils_Type::T_STRING,
4129 'name' => 'city',
4130 ),
4131 'country_id' => array(
4132 'name' => 'country_id',
4133 'title' => ts('Country'),
4134 'type' => CRM_Utils_Type::T_INT,
4135 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
4136 'options' => CRM_Core_PseudoConstant::country(),
4137 ),
4138 'state_province_id' => array(
4139 'name' => 'state_province_id',
4140 'title' => ts('State/Province'),
4141 'type' => CRM_Utils_Type::T_INT,
4142 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
4143 'options' => array(),
4144 ),
4145 'county_id' => array(
4146 'name' => 'county_id',
4147 'title' => ts('County'),
4148 'type' => CRM_Utils_Type::T_INT,
4149 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
4150 'options' => array(),
4151 ),
4152 );
4153 }
4154 $addressFields['civicrm_address']['filters'] = array_merge(
4155 $street_address_filters,
4156 $general_address_filters);
4157
4158 if ($orderBy) {
4159 $addressFields['civicrm_address']['order_bys'] = array(
4160 'street_name' => array('title' => ts('Street Name')),
4161 'street_number' => array('title' => ts('Odd / Even Street Number')),
4162 'street_address' => NULL,
4163 'city' => NULL,
4164 'postal_code' => NULL,
4165 );
4166 }
4167
4168 if ($groupBy) {
4169 $addressFields['civicrm_address']['group_bys'] = array(
4170 'street_address' => NULL,
4171 'city' => NULL,
4172 'postal_code' => NULL,
4173 'state_province_id' => array(
4174 'title' => ts('State/Province'),
4175 ),
4176 'country_id' => array(
4177 'title' => ts('Country'),
4178 ),
4179 'county_id' => array(
4180 'title' => ts('County'),
4181 ),
4182 );
4183 }
4184 return $addressFields;
4185 }
4186
4187 /**
4188 * Do AlterDisplay processing on Address Fields.
4189 *
4190 * @param array $row
4191 * @param array $rows
4192 * @param int $rowNum
4193 * @param string $baseUrl
4194 * @param string $linkText
4195 *
4196 * @return bool
4197 */
4198 public function alterDisplayAddressFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4199 $criteriaQueryParams = CRM_Report_Utils_Report::getPreviewCriteriaQueryParams($this->_defaults, $this->_params);
4200 $entryFound = FALSE;
4201 // handle country
4202 if (array_key_exists('civicrm_address_country_id', $row)) {
4203 if ($value = $row['civicrm_address_country_id']) {
4204 $rows[$rowNum]['civicrm_address_country_id'] = CRM_Core_PseudoConstant::country($value, FALSE);
4205 if ($baseUrl) {
4206 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
4207 "reset=1&force=1&{$criteriaQueryParams}&" .
4208 "country_id_op=in&country_id_value={$value}",
4209 $this->_absoluteUrl, $this->_id
4210 );
4211 $rows[$rowNum]['civicrm_address_country_id_link'] = $url;
4212 $rows[$rowNum]['civicrm_address_country_id_hover'] = ts("%1 for this country.",
4213 array(1 => $linkText)
4214 );
4215 }
4216 }
4217
4218 $entryFound = TRUE;
4219 }
4220 if (array_key_exists('civicrm_address_county_id', $row)) {
4221 if ($value = $row['civicrm_address_county_id']) {
4222 $rows[$rowNum]['civicrm_address_county_id'] = CRM_Core_PseudoConstant::county($value, FALSE);
4223 if ($baseUrl) {
4224 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
4225 "reset=1&force=1&{$criteriaQueryParams}&" .
4226 "county_id_op=in&county_id_value={$value}",
4227 $this->_absoluteUrl, $this->_id
4228 );
4229 $rows[$rowNum]['civicrm_address_county_id_link'] = $url;
4230 $rows[$rowNum]['civicrm_address_county_id_hover'] = ts("%1 for this county.",
4231 array(1 => $linkText)
4232 );
4233 }
4234 }
4235 $entryFound = TRUE;
4236 }
4237 // handle state province
4238 if (array_key_exists('civicrm_address_state_province_id', $row)) {
4239 if ($value = $row['civicrm_address_state_province_id']) {
4240 $rows[$rowNum]['civicrm_address_state_province_id'] = CRM_Core_PseudoConstant::stateProvince($value, FALSE);
4241 if ($baseUrl) {
4242 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
4243 "reset=1&force=1&{$criteriaQueryParams}&state_province_id_op=in&state_province_id_value={$value}",
4244 $this->_absoluteUrl, $this->_id
4245 );
4246 $rows[$rowNum]['civicrm_address_state_province_id_link'] = $url;
4247 $rows[$rowNum]['civicrm_address_state_province_id_hover'] = ts("%1 for this state.",
4248 array(1 => $linkText)
4249 );
4250 }
4251 }
4252 $entryFound = TRUE;
4253 }
4254
4255 return $entryFound;
4256 }
4257
4258 /**
4259 * Do AlterDisplay processing on Address Fields.
4260 *
4261 * @param array $row
4262 * @param array $rows
4263 * @param int $rowNum
4264 * @param string $baseUrl
4265 * @param string $linkText
4266 *
4267 * @return bool
4268 */
4269 public function alterDisplayContactFields(&$row, &$rows, &$rowNum, $baseUrl, $linkText) {
4270 $entryFound = FALSE;
4271 // There is no reason not to add links for all fields but it seems a bit odd to be able to click on
4272 // 'Mrs'. Also, we don't have metadata about the title. So, add selectively to addLinks.
4273 $addLinks = array('gender_id' => 'Gender');
4274 foreach (array('prefix_id', 'suffix_id', 'gender_id', 'contact_sub_type', 'preferred_language') as $fieldName) {
4275 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4276 if (($value = $row['civicrm_contact_' . $fieldName]) != FALSE) {
4277 $rowValues = explode(CRM_Core_DAO::VALUE_SEPARATOR, $value);
4278 $rowLabels = array();
4279 foreach ($rowValues as $rowValue) {
4280 if ($rowValue) {
4281 $rowLabels[] = CRM_Core_Pseudoconstant::getLabel('CRM_Contact_BAO_Contact', $fieldName, $rowValue);
4282 }
4283 }
4284 $rows[$rowNum]['civicrm_contact_' . $fieldName] = implode(', ', $rowLabels);
4285 if ($baseUrl && ($title = CRM_Utils_Array::value($fieldName, $addLinks)) != FALSE) {
4286 $this->addLinkToRow($rows[$rowNum], $baseUrl, $linkText, $value, $fieldName, 'civicrm_contact', $title);
4287 }
4288 }
4289 $entryFound = TRUE;
4290 }
4291 }
4292 $yesNoFields = array(
4293 'do_not_email', 'is_deceased', 'do_not_phone', 'do_not_sms', 'do_not_mail', 'is_opt_out',
4294 );
4295 foreach ($yesNoFields as $fieldName) {
4296 if (array_key_exists('civicrm_contact_' . $fieldName, $row)) {
4297 // Since these are essentially 'negative fields' it feels like it
4298 // makes sense to only highlight the exceptions hence no 'No'.
4299 $rows[$rowNum]['civicrm_contact_' . $fieldName] = !empty($rows[$rowNum]['civicrm_contact_' . $fieldName]) ? ts('Yes') : '';
4300 $entryFound = TRUE;
4301 }
4302 }
4303 return $entryFound;
4304 }
4305
4306 /**
4307 * Adjusts dates passed in to YEAR() for fiscal year.
4308 *
4309 * @param string $fieldName
4310 *
4311 * @return string
4312 */
4313 public function fiscalYearOffset($fieldName) {
4314 $config = CRM_Core_Config::singleton();
4315 $fy = $config->fiscalYearStart;
4316 if (CRM_Utils_Array::value('yid_op', $this->_params) == 'calendar' ||
4317 ($fy['d'] == 1 && $fy['M'] == 1)
4318 ) {
4319 return "YEAR( $fieldName )";
4320 }
4321 return "YEAR( $fieldName - INTERVAL " . ($fy['M'] - 1) . " MONTH" .
4322 ($fy['d'] > 1 ? (" - INTERVAL " . ($fy['d'] - 1) . " DAY") : '') . " )";
4323 }
4324
4325 /**
4326 * Add Address into From Table if required.
4327 */
4328 public function addAddressFromClause() {
4329 // include address field if address column is to be included
4330 if ((isset($this->_addressField) &&
4331 $this->_addressField
4332 ) ||
4333 $this->isTableSelected('civicrm_address')
4334 ) {
4335 $this->_from .= "
4336 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4337 ON ({$this->_aliases['civicrm_contact']}.id =
4338 {$this->_aliases['civicrm_address']}.contact_id) AND
4339 {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4340 }
4341 }
4342
4343 /**
4344 * Add Phone into From Table if required.
4345 */
4346 public function addPhoneFromClause() {
4347 // include address field if address column is to be included
4348 if ($this->isTableSelected('civicrm_phone')
4349 ) {
4350 $this->_from .= "
4351 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4352 ON ({$this->_aliases['civicrm_contact']}.id =
4353 {$this->_aliases['civicrm_phone']}.contact_id) AND
4354 {$this->_aliases['civicrm_phone']}.is_primary = 1\n";
4355 }
4356 }
4357
4358 /**
4359 * Get phone columns to add to array.
4360 *
4361 * @param array $options
4362 * - prefix Prefix to add to table (in case of more than one instance of the table)
4363 * - prefix_label Label to give columns from this phone table instance
4364 *
4365 * @return array
4366 * phone columns definition
4367 */
4368 public function getPhoneColumns($options = array()) {
4369 $defaultOptions = array(
4370 'prefix' => '',
4371 'prefix_label' => '',
4372 );
4373
4374 $options = array_merge($defaultOptions, $options);
4375
4376 $fields = array(
4377 $options['prefix'] . 'civicrm_phone' => array(
4378 'dao' => 'CRM_Core_DAO_Phone',
4379 'fields' => array(
4380 $options['prefix'] . 'phone' => array(
4381 'title' => ts($options['prefix_label'] . 'Phone'),
4382 'name' => 'phone',
4383 ),
4384 ),
4385 ),
4386 );
4387 return $fields;
4388 }
4389
4390 /**
4391 * Get address columns to add to array.
4392 *
4393 * @param array $options
4394 * - prefix Prefix to add to table (in case of more than one instance of the table)
4395 * - prefix_label Label to give columns from this address table instance
4396 *
4397 * @return array
4398 * address columns definition
4399 */
4400 public function getAddressColumns($options = array()) {
4401 $options += array(
4402 'prefix' => '',
4403 'prefix_label' => '',
4404 'group_by' => TRUE,
4405 'order_by' => TRUE,
4406 'filters' => TRUE,
4407 'defaults' => array(),
4408 );
4409 return $this->addAddressFields(
4410 $options['group_by'],
4411 $options['order_by'],
4412 $options['filters'],
4413 $options['defaults']
4414 );
4415 }
4416
4417 /**
4418 * Get a standard set of contact fields.
4419 *
4420 * @return array
4421 */
4422 public function getBasicContactFields() {
4423 return array(
4424 'sort_name' => array(
4425 'title' => ts('Contact Name'),
4426 'required' => TRUE,
4427 'default' => TRUE,
4428 ),
4429 'id' => array(
4430 'no_display' => TRUE,
4431 'required' => TRUE,
4432 ),
4433 'prefix_id' => array(
4434 'title' => ts('Contact Prefix'),
4435 ),
4436 'first_name' => array(
4437 'title' => ts('First Name'),
4438 ),
4439 'nick_name' => array(
4440 'title' => ts('Nick Name'),
4441 ),
4442 'middle_name' => array(
4443 'title' => ts('Middle Name'),
4444 ),
4445 'last_name' => array(
4446 'title' => ts('Last Name'),
4447 ),
4448 'suffix_id' => array(
4449 'title' => ts('Contact Suffix'),
4450 ),
4451 'postal_greeting_display' => array('title' => ts('Postal Greeting')),
4452 'email_greeting_display' => array('title' => ts('Email Greeting')),
4453 'addressee_display' => array('title' => ts('Addressee')),
4454 'contact_type' => array(
4455 'title' => ts('Contact Type'),
4456 ),
4457 'contact_sub_type' => array(
4458 'title' => ts('Contact Subtype'),
4459 ),
4460 'gender_id' => array(
4461 'title' => ts('Gender'),
4462 ),
4463 'birth_date' => array(
4464 'title' => ts('Birth Date'),
4465 ),
4466 'age' => array(
4467 'title' => ts('Age'),
4468 'dbAlias' => 'TIMESTAMPDIFF(YEAR, contact_civireport.birth_date, CURDATE())',
4469 ),
4470 'job_title' => array(
4471 'title' => ts('Contact Job title'),
4472 ),
4473 'organization_name' => array(
4474 'title' => ts('Organization Name'),
4475 ),
4476 'external_identifier' => array(
4477 'title' => ts('Contact identifier from external system'),
4478 ),
4479 'do_not_email' => array(),
4480 'do_not_phone' => array(),
4481 'do_not_mail' => array(),
4482 'do_not_sms' => array(),
4483 'is_opt_out' => array(),
4484 'is_deceased' => array(),
4485 'preferred_language' => array(),
4486 );
4487 }
4488
4489 /**
4490 * Get a standard set of contact filters.
4491 *
4492 * @return array
4493 */
4494 public function getBasicContactFilters() {
4495 return array(
4496 'sort_name' => array(
4497 'title' => ts('Contact Name'),
4498 ),
4499 'source' => array(
4500 'title' => ts('Contact Source'),
4501 'type' => CRM_Utils_Type::T_STRING,
4502 ),
4503 'id' => array(
4504 'title' => ts('Contact ID'),
4505 'no_display' => TRUE,
4506 ),
4507 'gender_id' => array(
4508 'title' => ts('Gender'),
4509 'operatorType' => CRM_Report_Form::OP_MULTISELECT,
4510 'options' => CRM_Core_PseudoConstant::get('CRM_Contact_DAO_Contact', 'gender_id'),
4511 ),
4512 'birth_date' => array(
4513 'title' => ts('Birth Date'),
4514 'operatorType' => CRM_Report_Form::OP_DATE,
4515 ),
4516 'contact_type' => array(
4517 'title' => ts('Contact Type'),
4518 ),
4519 'contact_sub_type' => array(
4520 'title' => ts('Contact Subtype'),
4521 ),
4522 'modified_date' => array(
4523 'title' => ts('Contact Modified'),
4524 'operatorType' => CRM_Report_Form::OP_DATE,
4525 'type' => CRM_Utils_Type::T_DATE,
4526 ),
4527 'is_deceased' => array(
4528 'title' => ts('Deceased'),
4529 'type' => CRM_Utils_Type::T_BOOLEAN,
4530 'default' => 0,
4531 ),
4532 'do_not_email' => array(
4533 'title' => ts('Do not email'),
4534 'type' => CRM_Utils_Type::T_BOOLEAN,
4535 ),
4536 'do_not_phone' => array(
4537 'title' => ts('Do not phone'),
4538 'type' => CRM_Utils_Type::T_BOOLEAN,
4539 ),
4540 'do_not_mail' => array(
4541 'title' => ts('Do not mail'),
4542 'type' => CRM_Utils_Type::T_BOOLEAN,
4543 ),
4544 'do_not_sms' => array(
4545 'title' => ts('Do not SMS'),
4546 'type' => CRM_Utils_Type::T_BOOLEAN,
4547 ),
4548 'is_opt_out' => array(
4549 'title' => ts('Do not bulk email'),
4550 'type' => CRM_Utils_Type::T_BOOLEAN,
4551 ),
4552 'preferred_language' => array(
4553 'title' => ts('Preferred Language'),
4554 ),
4555 );
4556 }
4557
4558 /**
4559 * Add contact to group.
4560 *
4561 * @param int $groupID
4562 */
4563 public function add2group($groupID) {
4564 if (is_numeric($groupID) && isset($this->_aliases['civicrm_contact'])) {
4565 $select = "SELECT DISTINCT {$this->_aliases['civicrm_contact']}.id AS addtogroup_contact_id, ";
4566
4567 // here are we are prepending / adding contact id field that could be used for adding group
4568 // so first check for "SELECT SQL_CALC_FOUND_ROWS" and if does not exist replace "SELECT"
4569 if (preg_match('/^SELECT SQL_CALC_FOUND_ROWS/', $this->_select)) {
4570 $select = str_ireplace('SELECT SQL_CALC_FOUND_ROWS ', $select, $this->_select);
4571 }
4572 else {
4573 $select = str_ireplace('SELECT ', $select, $this->_select);
4574 }
4575
4576 $sql = "{$select} {$this->_from} {$this->_where} {$this->_groupBy} {$this->_having} {$this->_orderBy}";
4577 $sql = str_replace('WITH ROLLUP', '', $sql);
4578 $dao = CRM_Core_DAO::executeQuery($sql);
4579
4580 $contact_ids = array();
4581 // Add resulting contacts to group
4582 while ($dao->fetch()) {
4583 if ($dao->addtogroup_contact_id) {
4584 $contact_ids[$dao->addtogroup_contact_id] = $dao->addtogroup_contact_id;
4585 }
4586 }
4587
4588 if (!empty($contact_ids)) {
4589 CRM_Contact_BAO_GroupContact::addContactsToGroup($contact_ids, $groupID);
4590 CRM_Core_Session::setStatus(ts("Listed contact(s) have been added to the selected group."), ts('Contacts Added'), 'success');
4591 }
4592 else {
4593 CRM_Core_Session::setStatus(ts("The listed records(s) cannot be added to the group."));
4594 }
4595 }
4596 }
4597
4598 /**
4599 * Show charts on print screen.
4600 */
4601 public static function uploadChartImage() {
4602 // upload strictly for '.png' images
4603 $name = trim(basename(CRM_Utils_Request::retrieve('name', 'String', CRM_Core_DAO::$_nullObject, FALSE, NULL, 'GET')));
4604 if (preg_match('/\.png$/', $name)) {
4605
4606 // Get the RAW .png from the input.
4607 $httpRawPostData = file_get_contents("php://input");
4608
4609 // prepare the directory
4610 $config = CRM_Core_Config::singleton();
4611 $defaultPath
4612 = str_replace('/persist/contribute/', '/persist/', $config->imageUploadDir) .
4613 '/openFlashChart/';
4614 if (!file_exists($defaultPath)) {
4615 mkdir($defaultPath, 0777, TRUE);
4616 }
4617
4618 // full path to the saved image including filename
4619 $destination = $defaultPath . $name;
4620
4621 //write and save
4622 $jfh = fopen($destination, 'w') or die("can't open file");
4623 fwrite($jfh, $httpRawPostData);
4624 fclose($jfh);
4625 CRM_Utils_System::civiExit();
4626 }
4627 }
4628
4629 /**
4630 * Apply common settings to entityRef fields.
4631 *
4632 * @param array $field
4633 * @param string $table
4634 */
4635 private function setEntityRefDefaults(&$field, $table) {
4636 $field['attributes'] = $field['attributes'] ? $field['attributes'] : array();
4637 $field['attributes'] += array(
4638 'entity' => CRM_Core_DAO_AllCoreTables::getBriefName(CRM_Core_DAO_AllCoreTables::getClassForTable($table)),
4639 'multiple' => TRUE,
4640 'placeholder' => ts('- select -'),
4641 );
4642 }
4643
4644 /**
4645 * Add link fields to the row.
4646 *
4647 * Function adds the _link & _hover fields to the row.
4648 *
4649 * @param array $row
4650 * @param string $baseUrl
4651 * @param string $linkText
4652 * @param string $value
4653 * @param string $fieldName
4654 * @param string $tablePrefix
4655 * @param string $fieldLabel
4656 *
4657 * @return mixed
4658 */
4659 protected function addLinkToRow(&$row, $baseUrl, $linkText, $value, $fieldName, $tablePrefix, $fieldLabel) {
4660 $criteriaQueryParams = CRM_Report_Utils_Report::getPreviewCriteriaQueryParams($this->_defaults, $this->_params);
4661 $url = CRM_Report_Utils_Report::getNextUrl($baseUrl,
4662 "reset=1&force=1&{$criteriaQueryParams}&" .
4663 $fieldName . "_op=in&{$fieldName}_value={$value}",
4664 $this->_absoluteUrl, $this->_id
4665 );
4666 $row["{$tablePrefix}_{$fieldName}_link"] = $url;
4667 $row["{$tablePrefix}_{$fieldName}_hover"] = ts("%1 for this %2.",
4668 array(1 => $linkText, 2 => $fieldLabel)
4669 );
4670 }
4671
4672 /**
4673 * Generate temporary table to hold all contributions with permissioned FTs.
4674 *
4675 * @param object $query
4676 * @param string $alias
4677 * @param bool $return
4678 */
4679 public function getPermissionedFTQuery(&$query, $alias = NULL, $return = FALSE) {
4680 if (!CRM_Financial_BAO_FinancialType::isACLFinancialTypeStatus()) {
4681 return FALSE;
4682 }
4683 $financialTypes = NULL;
4684 CRM_Financial_BAO_FinancialType::getAvailableFinancialTypes($financialTypes);
4685 if (empty($financialTypes)) {
4686 $contFTs = "0";
4687 $liFTs = implode(',', array_keys(CRM_Contribute_Pseudoconstant::financialType()));
4688 }
4689 else {
4690 $contFTs = $liFTs = implode(',', array_keys($financialTypes));
4691 }
4692 $temp = CRM_Utils_Array::value('civicrm_line_item', $query->_aliases);
4693 if ($alias) {
4694 $query->_aliases['civicrm_line_item'] = $alias;
4695 }
4696 elseif (!$temp) {
4697 $query->_aliases['civicrm_line_item'] = 'civicrm_line_item_civireport';
4698 }
4699 if (empty($query->_where)) {
4700 $query->_where = "WHERE {$query->_aliases['civicrm_contribution']}.id IS NOT NULL ";
4701 }
4702 CRM_Core_DAO::executeQuery("DROP TEMPORARY TABLE IF EXISTS civicrm_contribution_temp");
4703 $sql = "CREATE TEMPORARY TABLE civicrm_contribution_temp AS SELECT {$query->_aliases['civicrm_contribution']}.id {$query->_from}
4704 LEFT JOIN civicrm_line_item {$query->_aliases['civicrm_line_item']}
4705 ON {$query->_aliases['civicrm_contribution']}.id = {$query->_aliases['civicrm_line_item']}.contribution_id AND
4706 {$query->_aliases['civicrm_line_item']}.entity_table = 'civicrm_contribution'
4707 AND {$query->_aliases['civicrm_line_item']}.financial_type_id NOT IN (" . $liFTs . ")
4708 {$query->_where}
4709 AND {$query->_aliases['civicrm_contribution']}.financial_type_id IN (" . $contFTs . ")
4710 AND {$query->_aliases['civicrm_line_item']}.id IS NULL
4711 GROUP BY {$query->_aliases['civicrm_contribution']}.id";
4712 CRM_Core_DAO::executeQuery($sql);
4713 if (isset($temp)) {
4714 $query->_aliases['civicrm_line_item'] = $temp;
4715 }
4716 $from = " INNER JOIN civicrm_contribution_temp temp ON {$query->_aliases['civicrm_contribution']}.id = temp.id ";
4717 if ($return) {
4718 return $from;
4719 }
4720 $query->_from .= $from;
4721 }
4722
4723 /**
4724 * Get label for show results buttons.
4725 *
4726 * @return string
4727 */
4728 public function getResultsLabel() {
4729 $showResultsLabel = $this->resultsDisplayed() ? ts('Refresh results') : ts('View results');
4730 return $showResultsLabel;
4731 }
4732
4733 /**
4734 * Determine the output mode from the url or input.
4735 *
4736 * Output could be
4737 * - pdf : Render as pdf
4738 * - csv : Render as csv
4739 * - print : Render in print format
4740 * - save : save the report and display the new report
4741 * - copy : save the report as a new instance and display that.
4742 * - group : go to the add to group screen.
4743 *
4744 * Potentially chart variations could also be included but the complexity
4745 * is that we might print a bar chart as a pdf.
4746 */
4747 protected function setOutputMode() {
4748 $this->_outputMode = str_replace('report_instance.', '', CRM_Utils_Request::retrieve(
4749 'output',
4750 'String',
4751 CRM_Core_DAO::$_nullObject,
4752 FALSE,
4753 CRM_Utils_Array::value('task', $this->_params)
4754 ));
4755 // if contacts are added to group
4756 if (!empty($this->_params['groups']) && empty($this->_outputMode)) {
4757 $this->_outputMode = 'group';
4758 }
4759 if (isset($this->_params['task'])) {
4760 unset($this->_params['task']);
4761 }
4762 }
4763
4764 /**
4765 * CRM-17793 - Alter DateTime section header to group by date from the datetime field.
4766 *
4767 * @param $tempTable
4768 * @param $columnName
4769 */
4770 public function alterSectionHeaderForDateTime($tempTable, $columnName) {
4771 // add new column with date value for the datetime field
4772 $tempQuery = "ALTER TABLE {$tempTable} ADD COLUMN {$columnName}_date VARCHAR(128)";
4773 CRM_Core_DAO::executeQuery($tempQuery);
4774 $updateQuery = "UPDATE {$tempTable} SET {$columnName}_date = date({$columnName})";
4775 CRM_Core_DAO::executeQuery($updateQuery);
4776 $this->_selectClauses[] = "{$columnName}_date";
4777 $this->_select .= ", {$columnName}_date";
4778 $this->_sections["{$columnName}_date"] = $this->_sections["{$columnName}"];
4779 unset($this->_sections["{$columnName}"]);
4780 $this->assign('sections', $this->_sections);
4781 }
4782
4783 /**
4784 * Get an array of the columns that have been selected for display.
4785 *
4786 * @return array
4787 */
4788 public function getSelectColumns() {
4789 $selectColumns = array();
4790 foreach ($this->_columns as $tableName => $table) {
4791 if (array_key_exists('fields', $table)) {
4792 foreach ($table['fields'] as $fieldName => $field) {
4793 if (!empty($field['required']) ||
4794 !empty($this->_params['fields'][$fieldName])
4795 ) {
4796
4797 $selectColumns["{$tableName}_{$fieldName}"] = 1;
4798 }
4799 }
4800 }
4801 }
4802 return $selectColumns;
4803 }
4804
4805 /**
4806 * Add location tables to the query if they are used for filtering.
4807 *
4808 * This is for when we are running the query separately for filtering and retrieving display fields.
4809 */
4810 public function selectivelyAddLocationTablesJoinsToFilterQuery() {
4811 if ($this->isTableFiltered('civicrm_email')) {
4812 $this->_from .= "
4813 LEFT JOIN civicrm_email {$this->_aliases['civicrm_email']}
4814 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_email']}.contact_id
4815 AND {$this->_aliases['civicrm_email']}.is_primary = 1";
4816 }
4817 if ($this->isTableFiltered('civicrm_phone')) {
4818 $this->_from .= "
4819 LEFT JOIN civicrm_phone {$this->_aliases['civicrm_phone']}
4820 ON {$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_phone']}.contact_id
4821 AND {$this->_aliases['civicrm_phone']}.is_primary = 1";
4822 }
4823 if ($this->isTableFiltered('civicrm_address')) {
4824 $this->_from .= "
4825 LEFT JOIN civicrm_address {$this->_aliases['civicrm_address']}
4826 ON ({$this->_aliases['civicrm_contact']}.id = {$this->_aliases['civicrm_address']}.contact_id)
4827 AND {$this->_aliases['civicrm_address']}.is_primary = 1\n";
4828 }
4829 }
4830
4831 /**
4832 * Set the base table for the FROM clause.
4833 *
4834 * Sets up the from clause, allowing for the possibility it might be a
4835 * temp table pre-filtered by groups if a group filter is in use.
4836 *
4837 * @param string $baseTable
4838 * @param string $field
4839 * @param null $tableAlias
4840 */
4841 public function setFromBase($baseTable, $field = 'id', $tableAlias = NULL) {
4842 if (!$tableAlias) {
4843 $tableAlias = $this->_aliases[$baseTable];
4844 }
4845 $this->_from = $this->_from = " FROM $baseTable $tableAlias ";
4846 $this->joinGroupTempTable($baseTable, $field, $tableAlias);
4847 $this->_from .= " {$this->_aclFrom} ";
4848 }
4849
4850 /**
4851 * Join the temp table contacting contacts who are members of the filtered groups.
4852 *
4853 * If we are using an IN filter we use an inner join, otherwise a left join.
4854 *
4855 * @param string $baseTable
4856 * @param string $field
4857 * @param string $tableAlias
4858 */
4859 public function joinGroupTempTable($baseTable, $field, $tableAlias) {
4860 if ($this->groupTempTable) {
4861 if ($this->_params['gid_op'] == 'in') {
4862 $this->_from = " FROM $this->groupTempTable group_temp_table INNER JOIN $baseTable $tableAlias
4863 ON group_temp_table.id = $tableAlias.{$field} ";
4864 }
4865 else {
4866 $this->_from .= "
4867 LEFT JOIN $this->groupTempTable group_temp_table
4868 ON $tableAlias.{$field} = group_temp_table.id ";
4869 }
4870 }
4871 }
4872
4873 }