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