convert foreign key ids to something readable from the foreign record
[civicrm-core.git] / CRM / Logging / ReportDetail.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Logging_ReportDetail extends CRM_Report_Form {
18
19 const ROW_COUNT_LIMIT = 50;
20 protected $cid;
21
22 /**
23 * Other contact ID.
24 *
25 * This would be set if we are viewing a merge of 2 contacts.
26 *
27 * @var int
28 */
29 protected $oid;
30 protected $db;
31 protected $log_conn_id;
32 protected $log_date;
33 protected $raw;
34 protected $tables = [];
35 protected $interval = '10 SECOND';
36
37 protected $altered_name;
38 protected $altered_by;
39 protected $altered_by_id;
40
41 /**
42 * detail/summary report ids
43 * @var int
44 */
45 protected $detail;
46 protected $summary;
47
48 /**
49 * Instance of Differ.
50 *
51 * @var CRM_Logging_Differ
52 */
53 protected $differ;
54
55 /**
56 * Array of changes made.
57 *
58 * @var array
59 */
60 protected $diffs = [];
61
62 /**
63 * Don't display the Add these contacts to Group button.
64 *
65 * @var bool
66 */
67 protected $_add2groupSupported = FALSE;
68
69 /**
70 * Class constructor.
71 */
72 public function __construct() {
73
74 $this->storeDB();
75
76 $this->parsePropertiesFromUrl();
77
78 parent::__construct();
79
80 CRM_Utils_System::resetBreadCrumb();
81 $breadcrumb = [
82 [
83 'title' => ts('Home'),
84 'url' => CRM_Utils_System::url(),
85 ],
86 [
87 'title' => ts('CiviCRM'),
88 'url' => CRM_Utils_System::url('civicrm', 'reset=1'),
89 ],
90 [
91 'title' => ts('View Contact'),
92 'url' => CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->cid}"),
93 ],
94 [
95 'title' => ts('Search Results'),
96 'url' => CRM_Utils_System::url('civicrm/contact/search', "force=1"),
97 ],
98 ];
99 CRM_Utils_System::appendBreadCrumb($breadcrumb);
100
101 if (CRM_Utils_Request::retrieve('revert', 'Boolean')) {
102 $this->revert();
103 }
104
105 $this->_columnHeaders = [
106 'field' => ['title' => ts('Field'), 'type' => CRM_Utils_Type::T_STRING],
107 'from' => ['title' => ts('Changed From'), 'type' => CRM_Utils_Type::T_STRING],
108 'to' => ['title' => ts('Changed To'), 'type' => CRM_Utils_Type::T_STRING],
109 ];
110 }
111
112 /**
113 * Build query for report.
114 *
115 * We override this to be empty & calculate the rows in the buildRows function.
116 *
117 * @param bool $applyLimit
118 */
119 public function buildQuery($applyLimit = TRUE) {
120 }
121
122 /**
123 * Build rows from query.
124 *
125 * @param string $sql
126 * @param array $rows
127 */
128 public function buildRows($sql, &$rows) {
129 // safeguard for when there aren’t any log entries yet
130 if (!$this->log_conn_id && !$this->log_date) {
131 return;
132 }
133 $this->getDiffs();
134 $rows = $this->convertDiffsToRows();
135 }
136
137 /**
138 * Get the diffs for the report, calculating them if not already done.
139 *
140 * Note that contact details report now uses a more comprehensive method but
141 * the contribution logging details report still uses this.
142 *
143 * @return array
144 */
145 protected function getDiffs() {
146 if (empty($this->diffs)) {
147 foreach ($this->tables as $table) {
148 $this->diffs = array_merge($this->diffs, $this->diffsInTable($table));
149 }
150 }
151 return $this->diffs;
152 }
153
154 /**
155 * @param $table
156 *
157 * @return array
158 */
159 protected function diffsInTable($table) {
160 $this->setDiffer();
161 return $this->differ->diffsInTable($table, $this->cid);
162 }
163
164 /**
165 * Convert the diffs to row format.
166 *
167 * @return array
168 */
169 protected function convertDiffsToRows() {
170 // return early if nothing found
171 if (empty($this->diffs)) {
172 return [];
173 }
174
175 // populate $rows with only the differences between $changed and $original (skipping certain columns and NULL ↔ empty changes unless raw requested)
176 $skipped = ['id'];
177 $nRows = $rows = [];
178 foreach ($this->diffs as $diff) {
179 $table = $diff['table'];
180 if (empty($metadata[$table])) {
181 list($metadata[$table]['titles'], $metadata[$table]['values']) = $this->differ->titlesAndValuesForTable($table, $diff['log_date']);
182 }
183 $values = CRM_Utils_Array::value('values', $metadata[$diff['table']], []);
184 $titles = $metadata[$diff['table']]['titles'];
185 $field = $diff['field'];
186 $from = $diff['from'];
187 $to = $diff['to'];
188
189 if ($this->raw) {
190 $field = "$table.$field";
191 }
192 else {
193 if (in_array($field, $skipped)) {
194 continue;
195 }
196 // $differ filters out === values; for presentation hide changes like 42 → '42'
197 if ($from == $to) {
198 continue;
199 }
200
201 // special-case for multiple values. Also works for CRM-7251: preferred_communication_method
202 if ((substr($from, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR &&
203 substr($from, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR) ||
204 (substr($to, 0, 1) == CRM_Core_DAO::VALUE_SEPARATOR &&
205 substr($to, -1, 1) == CRM_Core_DAO::VALUE_SEPARATOR)
206 ) {
207 $froms = $tos = [];
208 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($from, CRM_Core_DAO::VALUE_SEPARATOR)) as $val) {
209 $froms[] = $values[$field][$val] ?? NULL;
210 }
211 foreach (explode(CRM_Core_DAO::VALUE_SEPARATOR, trim($to, CRM_Core_DAO::VALUE_SEPARATOR)) as $val) {
212 $tos[] = $values[$field][$val] ?? NULL;
213 }
214 $from = implode(', ', array_filter($froms));
215 $to = implode(', ', array_filter($tos));
216 }
217
218 $tableDAOClass = CRM_Core_DAO_AllCoreTables::getClassForTable($table);
219 if (!empty($tableDAOClass)) {
220 $tableDAOFields = (new $tableDAOClass())->fields();
221 // If this field is a foreign key, then we can later use the foreign
222 // class to translate the id into something more useful for display.
223 $fkClassName = $tableDAOFields[$field]['FKClassName'] ?? NULL;
224 }
225 if (isset($values[$field][$from])) {
226 $from = $values[$field][$from];
227 }
228 elseif (!empty($from) && !empty($fkClassName)) {
229 $from = $this->convertForeignKeyValuesToLabels($fkClassName, $field, $from);
230 }
231 if (isset($values[$field][$to])) {
232 $to = $values[$field][$to];
233 }
234 elseif (!empty($to) && !empty($fkClassName)) {
235 $to = $this->convertForeignKeyValuesToLabels($fkClassName, $field, $to);
236 }
237 if (isset($titles[$field])) {
238 $field = $titles[$field];
239 }
240 if ($diff['action'] == 'Insert') {
241 $from = '';
242 }
243 if ($diff['action'] == 'Delete') {
244 $to = '';
245 }
246 }
247 // Rework the results to provide grouping based on the ID
248 // We don't need that field displayed so we will output empty
249 if ($field == 'Modified Date') {
250 $nRows[$diff['id']][] = ['field' => '', 'from' => $from, 'to' => $to];
251 }
252 else {
253 $nRows[$diff['id']][] = ['field' => $field . " (id: {$diff['id']})", 'from' => $from, 'to' => $to];
254 }
255 }
256 // Transform the output so that we can compact the changes into the proper amount of rows IF trData is holding more than 1 array
257 foreach ($nRows as $trData) {
258 if (count($trData) > 1) {
259 $keys = array_intersect(...array_map('array_keys', $trData));
260 $mergedRes = array_combine($keys, array_map(function ($key) use ($trData) {
261 // If more than 1 entry is found, we are assigning them as subarrays, then the tpls will be responsible for concatenating the results
262 return array_column($trData, $key);
263 }, $keys));
264 $rows[] = $mergedRes;
265 }
266 else {
267 // We always need the first row of that array
268 $rows[] = $trData[0];
269 }
270
271 }
272 return $rows;
273 }
274
275 public function buildQuickForm() {
276 parent::buildQuickForm();
277
278 $this->assign('whom_url', CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->cid}"));
279 $this->assign('who_url', CRM_Utils_System::url('civicrm/contact/view', "reset=1&cid={$this->altered_by_id}"));
280 $this->assign('whom_name', $this->altered_name);
281 $this->assign('who_name', $this->altered_by);
282
283 $this->assign('log_date', CRM_Utils_Date::mysqlToIso($this->log_date));
284
285 $q = "reset=1&log_conn_id={$this->log_conn_id}&log_date={$this->log_date}";
286 if ($this->oid) {
287 $q .= '&oid=' . $this->oid;
288 }
289 $this->assign('revertURL', CRM_Report_Utils_Report::getNextUrl($this->detail, "$q&revert=1", FALSE, TRUE));
290 $this->assign('revertConfirm', ts('Are you sure you want to revert all changes?'));
291 }
292
293 /**
294 * Store the dsn for the logging database in $this->db.
295 */
296 protected function storeDB() {
297 $dsn = defined('CIVICRM_LOGGING_DSN') ? CRM_Utils_SQL::autoSwitchDSN(CIVICRM_LOGGING_DSN) : CRM_Utils_SQL::autoSwitchDSN(CIVICRM_DSN);
298 $dsn = DB::parseDSN($dsn);
299 $this->db = $dsn['database'];
300 }
301
302 /**
303 * Calculate all the contact related diffs for the change.
304 */
305 protected function calculateContactDiffs() {
306 $this->_rowsFound = $this->getCountOfAllContactChangesForConnection();
307 // Apply some limits before asking for all contact changes
308 $this->getLimit();
309 $this->diffs = $this->getAllContactChangesForConnection();
310 }
311
312 /**
313 * Get an array of changes made in the mysql connection.
314 *
315 * @return mixed
316 */
317 public function getAllContactChangesForConnection() {
318 if (empty($this->log_conn_id)) {
319 return [];
320 }
321 $this->setDiffer();
322 try {
323 return $this->differ->getAllChangesForConnection($this->tables, $this->dblimit, $this->dboffset);
324 }
325 catch (CRM_Core_Exception $e) {
326 CRM_Core_Error::statusBounce($e->getMessage());
327 }
328 }
329
330 /**
331 * Get an count of contacts with changes.
332 *
333 * @return mixed
334 */
335 public function getCountOfAllContactChangesForConnection() {
336 if (empty($this->log_conn_id)) {
337 return [];
338 }
339 $this->setDiffer();
340 try {
341 return $this->differ->getCountOfAllContactChangesForConnection($this->tables);
342 }
343 catch (CRM_Core_Exception $e) {
344 CRM_Core_Error::statusBounce($e->getMessage());
345 }
346 }
347
348 /**
349 * Make sure the differ is defined.
350 */
351 protected function setDiffer() {
352 if (empty($this->differ)) {
353 $this->differ = new CRM_Logging_Differ($this->log_conn_id, $this->log_date, $this->interval);
354 }
355 }
356
357 /**
358 * Set this tables to reflect tables changed in a merge.
359 */
360 protected function setTablesToContactRelatedTables() {
361 $schema = new CRM_Logging_Schema();
362 $this->tables = $schema->getLogTablesForContact();
363 // allow tables to be extended by report hook query objects.
364 // This is a report specific hook. It's unclear how it interacts to / overlaps the main one.
365 // It probably precedes the main one and was never reconciled with it....
366 CRM_Report_BAO_Hook::singleton()->alterLogTables($this, $this->tables);
367 }
368
369 /**
370 * Revert the changes defined by the parameters.
371 */
372 protected function revert() {
373 $reverter = new CRM_Logging_Reverter($this->log_conn_id, $this->log_date);
374 $reverter->calculateDiffsFromLogConnAndDate($this->tables);
375 $reverter->revert();
376 CRM_Core_Session::setStatus(ts('The changes have been reverted.'), ts('Reverted'), 'success');
377 if ($this->cid) {
378 if ($this->oid) {
379 CRM_Utils_System::redirect(CRM_Utils_System::url(
380 'civicrm/contact/merge',
381 "reset=1&cid={$this->cid}&oid={$this->oid}",
382 FALSE,
383 NULL,
384 FALSE)
385 );
386 }
387 else {
388 CRM_Utils_System::redirect(CRM_Utils_System::url('civicrm/contact/view', "reset=1&selectedChild=log&cid={$this->cid}", FALSE, NULL, FALSE));
389 }
390 }
391 else {
392 CRM_Utils_System::redirect(CRM_Report_Utils_Report::getNextUrl($this->summary, 'reset=1', FALSE, TRUE));
393 }
394 }
395
396 /**
397 * Get the properties that might be in the URL.
398 */
399 protected function parsePropertiesFromUrl() {
400 $this->log_conn_id = CRM_Utils_Request::retrieve('log_conn_id', 'String');
401 $this->log_date = CRM_Utils_Request::retrieve('log_date', 'String');
402 $this->cid = CRM_Utils_Request::retrieve('cid', 'Integer');
403 $this->raw = CRM_Utils_Request::retrieve('raw', 'Boolean');
404
405 $this->altered_name = CRM_Utils_Request::retrieve('alteredName', 'String');
406 $this->altered_by = CRM_Utils_Request::retrieve('alteredBy', 'String');
407 $this->altered_by_id = CRM_Utils_Request::retrieve('alteredById', 'Integer');
408 $this->layout = CRM_Utils_Request::retrieve('layout', 'String');
409 }
410
411 /**
412 * Override to set limit
413 * @param int $rowCount
414 */
415 public function limit($rowCount = self::ROW_COUNT_LIMIT) {
416 parent::limit($rowCount);
417 }
418
419 /**
420 * Override to set pager with limit
421 * @param int $rowCount
422 */
423 public function setPager($rowCount = self::ROW_COUNT_LIMIT) {
424 // We should not be rendering the pager in overlay mode
425 if (!isset($this->layout)) {
426 $this->_dashBoardRowCount = $rowCount;
427 $this->_limit = TRUE;
428 parent::setPager($rowCount);
429 }
430 }
431
432 /**
433 * This is a function similar to limit, in fact we copied it as-is and removed
434 * some `set` statements
435 *
436 */
437 public function getLimit($rowCount = self::ROW_COUNT_LIMIT) {
438 if ($this->addPaging) {
439
440 $pageId = CRM_Utils_Request::retrieve('crmPID', 'Integer');
441
442 // @todo all http vars should be extracted in the preProcess
443 // - not randomly in the class
444 if (!$pageId && !empty($_POST)) {
445 if (isset($_POST['PagerBottomButton']) && isset($_POST['crmPID_B'])) {
446 $pageId = max((int) $_POST['crmPID_B'], 1);
447 }
448 elseif (isset($_POST['PagerTopButton']) && isset($_POST['crmPID'])) {
449 $pageId = max((int) $_POST['crmPID'], 1);
450 }
451 unset($_POST['crmPID_B'], $_POST['crmPID']);
452 }
453
454 $pageId = $pageId ? $pageId : 1;
455 $offset = ($pageId - 1) * $rowCount;
456
457 $offset = CRM_Utils_Type::escape($offset, 'Int');
458 $rowCount = CRM_Utils_Type::escape($rowCount, 'Int');
459 $this->_limit = " LIMIT $offset, $rowCount";
460 $this->dblimit = $rowCount;
461 $this->dboffset = $offset;
462 }
463 }
464
465 /**
466 * Given a key value that we know is a foreign key to another table, return
467 * what the DAO thinks is the "label" for the foreign entity. For example
468 * if it's referencing a contact then return the contact name, or if it's an
469 * activity then return the activity subject.
470 * If it's the type of DAO that doesn't have such a thing, just echo back
471 * what we were given.
472 *
473 * @param string $fkClassName
474 * @param string $field
475 * @param int $keyval
476 * @return string
477 */
478 private function convertForeignKeyValuesToLabels(string $fkClassName, string $field, int $keyval): string {
479 if (property_exists($fkClassName, '_labelField')) {
480 $labelValue = CRM_Core_DAO::getFieldValue($fkClassName, $keyval, $fkClassName::$_labelField);
481 // Not sure if this should use ts - there's not a lot of context (`%1 (id: %2)`) - and also the similar field labels above don't use ts.
482 return "{$labelValue} (id: {$keyval})";
483 }
484 return (string) $keyval;
485 }
486
487 }