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