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