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