Extract buildQuery on ReportSummary.
[civicrm-core.git] / CRM / Logging / ReportSummary.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
fee14197 4 | CiviCRM version 5 |
6a488035 5 +--------------------------------------------------------------------+
8c9251b3 6 | Copyright CiviCRM LLC (c) 2004-2018 |
6a488035
TO
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
d25dd0ee 26 */
6a488035
TO
27
28/**
29 *
30 * @package CRM
8c9251b3 31 * @copyright CiviCRM LLC (c) 2004-2018
6a488035 32 * $Id$
6a488035
TO
33 */
34class CRM_Logging_ReportSummary extends CRM_Report_Form {
35 protected $cid;
36
37 protected $_logTables = array();
38
39 protected $loggingDB;
40
41c9c9e9 41 /**
42 * The log table currently being processed.
43 *
44 * @var string
45 */
46 protected $currentLogTable;
47
65ec4c8c 48 /**
49 * Clause used in the final run of buildQuery but not when doing preliminary work.
50 *
51 * (We do this to all the api to run this report since it doesn't call postProcess).
52 *
53 * @var string
54 */
55 protected $logTypeTableClause;
56
e0ef6999 57 /**
2fb1dd66 58 * Class constructor.
e0ef6999 59 */
00be9182 60 public function __construct() {
694e78fd
DS
61 // don’t display the ‘Add these Contacts to Group’ button
62 $this->_add2groupSupported = FALSE;
63
64 $dsn = defined('CIVICRM_LOGGING_DSN') ? DB::parseDSN(CIVICRM_LOGGING_DSN) : DB::parseDSN(CIVICRM_DSN);
65 $this->loggingDB = $dsn['database'];
66
67 // used for redirect back to contact summary
41c9c9e9 68 $this->cid = CRM_Utils_Request::retrieve('cid', 'Integer');
cbb9666e 69
ae5ffbb7
TO
70 $this->_logTables = array(
71 'log_civicrm_contact' => array(
72 'fk' => 'id',
73 ),
74 'log_civicrm_email' => array(
75 'fk' => 'contact_id',
76 'log_type' => 'Contact',
77 ),
78 'log_civicrm_phone' => array(
79 'fk' => 'contact_id',
80 'log_type' => 'Contact',
81 ),
82 'log_civicrm_address' => array(
83 'fk' => 'contact_id',
84 'log_type' => 'Contact',
85 ),
86 'log_civicrm_note' => array(
87 'fk' => 'entity_id',
88 'entity_table' => TRUE,
89 'bracket_info' => array(
90 'table' => 'log_civicrm_note',
91 'column' => 'subject',
cbb9666e 92 ),
ae5ffbb7
TO
93 ),
94 'log_civicrm_note_comment' => array(
95 'fk' => 'entity_id',
96 'table_name' => 'log_civicrm_note',
97 'joins' => array(
98 'table' => 'log_civicrm_note',
99 'join' => "entity_log_civireport.entity_id = fk_table.id AND entity_log_civireport.entity_table = 'civicrm_note'",
cbb9666e 100 ),
ae5ffbb7
TO
101 'entity_table' => TRUE,
102 'bracket_info' => array(
103 'table' => 'log_civicrm_note',
104 'column' => 'subject',
cbb9666e 105 ),
ae5ffbb7
TO
106 ),
107 'log_civicrm_group_contact' => array(
108 'fk' => 'contact_id',
109 'bracket_info' => array(
110 'entity_column' => 'group_id',
111 'table' => 'log_civicrm_group',
112 'column' => 'title',
cbb9666e 113 ),
ae5ffbb7
TO
114 'action_column' => 'status',
115 'log_type' => 'Group',
116 ),
117 'log_civicrm_entity_tag' => array(
118 'fk' => 'entity_id',
119 'bracket_info' => array(
120 'entity_column' => 'tag_id',
121 'table' => 'log_civicrm_tag',
122 'column' => 'name',
cbb9666e 123 ),
ae5ffbb7
TO
124 'entity_table' => TRUE,
125 ),
126 'log_civicrm_relationship' => array(
127 'fk' => 'contact_id_a',
128 'bracket_info' => array(
129 'entity_column' => 'relationship_type_id',
130 'table' => 'log_civicrm_relationship_type',
131 'column' => 'label_a_b',
cbb9666e 132 ),
ae5ffbb7 133 ),
41c9c9e9 134 'log_civicrm_activity_contact' => array(
ae5ffbb7 135 'fk' => 'contact_id',
41c9c9e9 136 'table_name' => 'log_civicrm_activity_contact',
ae5ffbb7 137 'log_type' => 'Activity',
41c9c9e9 138 'field' => 'activity_id',
b94abe71 139 'extra_joins' => array(
140 'table' => 'log_civicrm_activity',
141 'join' => 'extra_table.id = entity_log_civireport.activity_id',
142 ),
41c9c9e9 143
ae5ffbb7
TO
144 'bracket_info' => array(
145 'entity_column' => 'activity_type_id',
146 'options' => CRM_Core_PseudoConstant::activityType(TRUE, TRUE, FALSE, 'label', TRUE),
41c9c9e9 147 'lookup_table' => 'log_civicrm_activity',
cbb9666e 148 ),
ae5ffbb7
TO
149 ),
150 'log_civicrm_case' => array(
151 'fk' => 'contact_id',
152 'joins' => array(
153 'table' => 'log_civicrm_case_contact',
154 'join' => 'entity_log_civireport.id = fk_table.case_id',
cbb9666e 155 ),
ae5ffbb7
TO
156 'bracket_info' => array(
157 'entity_column' => 'case_type_id',
7a5c0c6c 158 'options' => CRM_Case_BAO_Case::buildOptions('case_type_id', 'search'),
ae5ffbb7
TO
159 ),
160 ),
161 );
6a488035 162
ae5ffbb7 163 $logging = new CRM_Logging_Schema();
694e78fd
DS
164
165 // build _logTables for contact custom tables
166 $customTables = $logging->entityCustomDataLogTables('Contact');
6a488035 167 foreach ($customTables as $table) {
9d72cede
EM
168 $this->_logTables[$table] = array(
169 'fk' => 'entity_id',
21dfd5f5 170 'log_type' => 'Contact',
9d72cede 171 );
6a488035
TO
172 }
173
694e78fd
DS
174 // build _logTables for address custom tables
175 $customTables = $logging->entityCustomDataLogTables('Address');
176 foreach ($customTables as $table) {
ae5ffbb7 177 $this->_logTables[$table] = array(
2fb1dd66
EM
178 // For join of fk_table with contact table.
179 'fk' => 'contact_id',
ae5ffbb7 180 'joins' => array(
2fb1dd66
EM
181 // fk_table
182 'table' => 'log_civicrm_address',
ae5ffbb7
TO
183 'join' => 'entity_log_civireport.entity_id = fk_table.id',
184 ),
185 'log_type' => 'Contact',
186 );
694e78fd
DS
187 }
188
2fb1dd66 189 // Allow log tables to be extended via report hooks.
6b4b11c4 190 CRM_Report_BAO_Hook::singleton()->alterLogTables($this, $this->_logTables);
c3e3dd65 191
6a488035
TO
192 parent::__construct();
193 }
194
00be9182 195 public function groupBy() {
6a488035
TO
196 $this->_groupBy = 'GROUP BY entity_log_civireport.log_conn_id, entity_log_civireport.log_user_id, EXTRACT(DAY_MICROSECOND FROM entity_log_civireport.log_date), entity_log_civireport.id';
197 }
198
41c9c9e9 199 /**
200 * Adjust query for the activity_contact table.
201 *
202 * As this is just a join table the ID we REALLY care about is the activity id.
203 *
204 * @param string $tableName
205 * @param string $tableKey
206 * @param string $fieldName
207 * @param string $field
208 *
209 * @return string
210 */
211 public function selectClause(&$tableName, $tableKey, &$fieldName, &$field) {
212 if ($this->currentLogTable == 'log_civicrm_activity_contact' && $fieldName == 'id') {
213 $alias = "{$tableName}_{$fieldName}";
214 $select[] = "{$tableName}.activity_id as $alias";
215 $this->_selectAliases[] = $alias;
216 return "activity_id";
6a488035 217 }
b94abe71 218 if ($fieldName == 'log_grouping') {
219 if ($this->currentLogTable != 'log_civicrm_activity_contact') {
220 return 1;
221 }
222 $mergeActivityID = CRM_Core_PseudoConstant::getKey('CRM_Activity_BAO_Activity', 'activity_type_id', 'Contact Merged');
223 return " IF (entity_log_civireport.log_action = 'Insert' AND extra_table.activity_type_id = $mergeActivityID , GROUP_CONCAT(entity_log_civireport.contact_id), 1) ";
224 }
6a488035
TO
225 }
226
00be9182 227 public function where() {
8c544cd2
DS
228 // reset where clause as its called multiple times, every time insert sql is built.
229 $this->_whereClauses = array();
42047ce4 230
6a488035
TO
231 parent::where();
232 $this->_where .= " AND (entity_log_civireport.log_action != 'Initialization')";
233 }
234
00be9182 235 public function postProcess() {
6a488035
TO
236 $this->beginPostProcess();
237 $rows = array();
eea16664 238
b94abe71 239 $tempColumns = "id int(10), log_civicrm_entity_log_grouping varchar(32)";
a7488080 240 if (!empty($this->_params['fields']['log_action'])) {
9c097caf
DS
241 $tempColumns .= ", log_action varchar(64)";
242 }
243 $tempColumns .= ", log_type varchar(64), log_user_id int(10), log_date timestamp";
a7488080 244 if (!empty($this->_params['fields']['altered_contact'])) {
9c097caf
DS
245 $tempColumns .= ", altered_contact varchar(128)";
246 }
3b45d110 247 $tempColumns .= ", altered_contact_id int(10), log_conn_id varchar(17), is_deleted tinyint(4)";
a7488080 248 if (!empty($this->_params['fields']['display_name'])) {
9c097caf
DS
249 $tempColumns .= ", display_name varchar(128)";
250 }
251
6a488035 252 // temp table to hold all altered contact-ids
9c097caf 253 $sql = "CREATE TEMPORARY TABLE civicrm_temp_civireport_logsummary ( {$tempColumns} ) ENGINE=HEAP";
6a488035 254 CRM_Core_DAO::executeQuery($sql);
03bfa14f 255 $this->addToDeveloperTab($sql);
6a488035 256
6a488035
TO
257 $logTypes = CRM_Utils_Array::value('log_type_value', $this->_params);
258 unset($this->_params['log_type_value']);
cbb9666e 259 if (empty($logTypes)) {
260 foreach (array_keys($this->_logTables) as $table) {
6a488035
TO
261 $type = $this->getLogType($table);
262 $logTypes[$type] = $type;
263 }
264 }
265
65ec4c8c 266 $this->logTypeTableClause = '(1)';
798878cc 267 if ($logTypeTableValue = CRM_Utils_Array::value("log_type_table_value", $this->_params)) {
65ec4c8c 268 $this->logTypeTableClause = $this->whereClause($this->_columns['log_civicrm_entity']['filters']['log_type_table'],
cbb9666e 269 $this->_params['log_type_table_op'], $logTypeTableValue, NULL, NULL);
798878cc
DS
270 unset($this->_params['log_type_table_value']);
271 }
cbb9666e 272
273 foreach ($this->_logTables as $entity => $detail) {
6a488035 274 if ((in_array($this->getLogType($entity), $logTypes) &&
cbb9666e 275 CRM_Utils_Array::value('log_type_op', $this->_params) == 'in') ||
6a488035 276 (!in_array($this->getLogType($entity), $logTypes) &&
cbb9666e 277 CRM_Utils_Array::value('log_type_op', $this->_params) == 'notin')
278 ) {
41c9c9e9 279 $this->currentLogTable = $entity;
cbb9666e 280 $sql = $this->buildQuery(FALSE);
6a488035
TO
281 $sql = str_replace("entity_log_civireport.log_type as", "'{$entity}' as", $sql);
282 $sql = "INSERT IGNORE INTO civicrm_temp_civireport_logsummary {$sql}";
283 CRM_Core_DAO::executeQuery($sql);
03bfa14f 284 $this->addToDeveloperTab($sql);
6a488035
TO
285 }
286 }
287
41c9c9e9 288 $this->currentLogTable = '';
289
9a2a98cd
DS
290 // add computed log_type column so that we can do a group by after that, which will help
291 // alterDisplay() counts sync with pager counts
292 $sql = "SELECT DISTINCT log_type FROM civicrm_temp_civireport_logsummary";
293 $dao = CRM_Core_DAO::executeQuery($sql);
03bfa14f 294 $this->addToDeveloperTab($sql);
9a2a98cd 295 $replaceWith = array();
cbb9666e 296 while ($dao->fetch()) {
9a2a98cd 297 $type = $this->getLogType($dao->log_type);
cbb9666e 298 if (!array_key_exists($type, $replaceWith)) {
9a2a98cd 299 $replaceWith[$type] = array();
cbb9666e 300 }
9a2a98cd
DS
301 $replaceWith[$type][] = $dao->log_type;
302 }
303 foreach ($replaceWith as $type => $tables) {
304 if (!empty($tables)) {
305 $replaceWith[$type] = implode("','", $tables);
306 }
307 }
2efcf0c2 308
9a2a98cd
DS
309 $sql = "ALTER TABLE civicrm_temp_civireport_logsummary ADD COLUMN log_civicrm_entity_log_type_label varchar(64)";
310 CRM_Core_DAO::executeQuery($sql);
03bfa14f 311 $this->addToDeveloperTab($sql);
9a2a98cd
DS
312 foreach ($replaceWith as $type => $in) {
313 $sql = "UPDATE civicrm_temp_civireport_logsummary SET log_civicrm_entity_log_type_label='{$type}', log_date=log_date WHERE log_type IN('$in')";
314 CRM_Core_DAO::executeQuery($sql);
03bfa14f 315 $this->addToDeveloperTab($sql);
9a2a98cd 316 }
65ec4c8c 317 $sql = $this->buildQuery();
9a2a98cd 318
6a488035 319 $this->buildRows($sql, $rows);
03bfa14f 320 $this->addToDeveloperTab($sql);
6a488035
TO
321
322 // format result set.
323 $this->formatDisplay($rows);
324
325 // assign variables to templates
326 $this->doTemplateAssignment($rows);
327
328 // do print / pdf / instance stuff if needed
329 $this->endPostProcess($rows);
330 }
331
e0ef6999 332 /**
2fb1dd66
EM
333 * Get log type.
334 *
335 * @param string $entity
e0ef6999
EM
336 *
337 * @return string
338 */
00be9182 339 public function getLogType($entity) {
a7488080 340 if (!empty($this->_logTables[$entity]['log_type'])) {
6a488035
TO
341 return $this->_logTables[$entity]['log_type'];
342 }
343 $logType = ucfirst(substr($entity, strrpos($entity, '_') + 1));
344 return $logType;
345 }
346
e0ef6999 347 /**
2fb1dd66
EM
348 * Get entity value.
349 *
100fef9d 350 * @param int $id
e0ef6999
EM
351 * @param $entity
352 * @param $logDate
353 *
354 * @return mixed|null|string
355 */
00be9182 356 public function getEntityValue($id, $entity, $logDate) {
a7488080
CW
357 if (!empty($this->_logTables[$entity]['bracket_info'])) {
358 if (!empty($this->_logTables[$entity]['bracket_info']['entity_column'])) {
0d8afee2 359 $logTable = !empty($this->_logTables[$entity]['table_name']) ? $this->_logTables[$entity]['table_name'] : $entity;
41c9c9e9 360 if (!empty($this->_logTables[$entity]['bracket_info']['lookup_table'])) {
361 $logTable = $this->_logTables[$entity]['bracket_info']['lookup_table'];
362 }
6a488035 363 $sql = "
eea16664 364SELECT {$this->_logTables[$entity]['bracket_info']['entity_column']}
365 FROM `{$this->loggingDB}`.{$logTable}
6a488035 366 WHERE log_date <= %1 AND id = %2 ORDER BY log_date DESC LIMIT 1";
41c9c9e9 367
cbb9666e 368 $entityID = CRM_Core_DAO::singleValueQuery($sql, array(
369 1 => array(
370 CRM_Utils_Date::isoToMysql($logDate),
21dfd5f5 371 'Timestamp',
cbb9666e 372 ),
21dfd5f5 373 2 => array($id, 'Integer'),
cbb9666e 374 ));
375 }
376 else {
6a488035
TO
377 $entityID = $id;
378 }
379
9d72cede
EM
380 if ($entityID && $logDate &&
381 array_key_exists('table', $this->_logTables[$entity]['bracket_info'])
382 ) {
6a488035 383 $sql = "
eea16664 384SELECT {$this->_logTables[$entity]['bracket_info']['column']}
385FROM `{$this->loggingDB}`.{$this->_logTables[$entity]['bracket_info']['table']}
6a488035 386WHERE log_date <= %1 AND id = %2 ORDER BY log_date DESC LIMIT 1";
cbb9666e 387 return CRM_Core_DAO::singleValueQuery($sql, array(
388 1 => array(CRM_Utils_Date::isoToMysql($logDate), 'Timestamp'),
21dfd5f5 389 2 => array($entityID, 'Integer'),
cbb9666e 390 ));
391 }
392 else {
9d72cede
EM
393 if (array_key_exists('options', $this->_logTables[$entity]['bracket_info']) &&
394 $entityID
395 ) {
cbb9666e 396 return CRM_Utils_Array::value($entityID, $this->_logTables[$entity]['bracket_info']['options']);
397 }
6a488035
TO
398 }
399 }
cbb9666e 400 return NULL;
6a488035
TO
401 }
402
e0ef6999 403 /**
2fb1dd66
EM
404 * Get entity action.
405 *
100fef9d
CW
406 * @param int $id
407 * @param int $connId
e0ef6999
EM
408 * @param $entity
409 * @param $oldAction
410 *
411 * @return null|string
412 */
00be9182 413 public function getEntityAction($id, $connId, $entity, $oldAction) {
a7488080 414 if (!empty($this->_logTables[$entity]['action_column'])) {
6a488035 415 $sql = "select {$this->_logTables[$entity]['action_column']} from `{$this->loggingDB}`.{$entity} where id = %1 AND log_conn_id = %2";
cbb9666e 416 $newAction = CRM_Core_DAO::singleValueQuery($sql, array(
417 1 => array($id, 'Integer'),
3b45d110 418 2 => array($connId, 'String'),
cbb9666e 419 ));
6a488035
TO
420
421 switch ($entity) {
cbb9666e 422 case 'log_civicrm_group_contact':
423 if ($oldAction !== 'Update') {
424 $newAction = $oldAction;
425 }
426 if ($oldAction == 'Insert') {
427 $newAction = 'Added';
428 }
429 break;
6a488035
TO
430 }
431 return $newAction;
432 }
cbb9666e 433 return NULL;
6a488035 434 }
96025800 435
65ec4c8c 436 /**
437 * Build the report query.
438 *
439 * We override this in order to be able to run from the api.
440 *
441 * @param bool $applyLimit
442 *
443 * @return string
444 */
445 public function buildQuery($applyLimit = TRUE) {
446 if (!$this->logTypeTableClause) {
447 return parent::buildQuery($applyLimit);
448 }
449 // note the group by columns are same as that used in alterDisplay as $newRows - $key
450 $this->limit();
451 $this->orderBy();
452 $sql = "{$this->_select}
453FROM civicrm_temp_civireport_logsummary entity_log_civireport
454WHERE {$this->logTypeTableClause}
455GROUP BY log_civicrm_entity_log_date, log_civicrm_entity_log_type_label, log_civicrm_entity_log_conn_id, log_civicrm_entity_log_user_id, log_civicrm_entity_altered_contact_id, log_civicrm_entity_log_grouping
456{$this->_orderBy}
457{$this->_limit} ";
458 $sql = str_replace('modified_contact_civireport.display_name', 'entity_log_civireport.altered_contact', $sql);
459 $sql = str_replace('modified_contact_civireport.id', 'entity_log_civireport.altered_contact_id', $sql);
460 $sql = str_replace(array(
461 'modified_contact_civireport.',
462 'altered_by_contact_civireport.',
463 ), 'entity_log_civireport.', $sql);
464 return $sql;
465 }
466
6a488035 467}