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