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