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