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