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