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