[TASK] Make show_rechis.php mod.php dispatched
[Packages/TYPO3.CMS.git] / typo3 / sysext / backend / Classes / History / RecordHistory.php
1 <?php
2 namespace TYPO3\CMS\Backend\History;
3
4 /***************************************************************
5 * Copyright notice
6 *
7 * (c) 1999-2013 Kasper Skårhøj (kasperYYYY@typo3.com)
8 * (c) 2006-2013 Sebastian Kurfürst (sebastian@garbage-group.de)
9 * All rights reserved
10 *
11 * This script is part of the TYPO3 project. The TYPO3 project is
12 * free software; you can redistribute it and/or modify
13 * it under the terms of the GNU General Public License as published by
14 * the Free Software Foundation; either version 2 of the License, or
15 * (at your option) any later version.
16 *
17 * The GNU General Public License can be found at
18 * http://www.gnu.org/copyleft/gpl.html.
19 * A copy is found in the text file GPL.txt and important notices to the license
20 * from the author is found in LICENSE.txt distributed with these scripts.
21 *
22 *
23 * This script is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 *
28 * This copyright notice MUST APPEAR in all copies of the script!
29 ***************************************************************/
30
31 use TYPO3\CMS\Backend\Utility\BackendUtility;
32 use TYPO3\CMS\Backend\Utility\IconUtility;
33 use TYPO3\CMS\Core\Utility\GeneralUtility;
34
35 /**
36 * Class for the record history display script (show_rechis.php)
37 *
38 * XHTML Compliant
39 *
40 * @author Sebastian Kurfürst <sebastian@garbage-group.de>
41 */
42 /**
43 * Class for the record history display script (show_rechis.php)
44 *
45 * @author Sebastian Kurfürst <sebastian@garbage-group.de>
46 */
47 class RecordHistory {
48
49 // External, static:
50 // Maximum number of sys_history steps to show.
51 /**
52 * @todo Define visibility
53 */
54 public $maxSteps = 20;
55
56 // display diff or not (0-no diff, 1-inline)
57 /**
58 * @todo Define visibility
59 */
60 public $showDiff = 1;
61
62 // on a pages table - show sub elements as well.
63 /**
64 * @todo Define visibility
65 */
66 public $showSubElements = 1;
67
68 // show inserts and deletes as well
69 /**
70 * @todo Define visibility
71 */
72 public $showInsertDelete = 1;
73
74 // Internal, GPvars
75 // Element reference, syntax [tablename]:[uid]
76 /**
77 * @todo Define visibility
78 */
79 public $element;
80
81 // syslog ID which is not shown anymore
82 /**
83 * @todo Define visibility
84 */
85 public $lastSyslogId;
86
87 /**
88 * @todo Define visibility
89 */
90 public $returnUrl;
91
92 // Internal
93 /**
94 * @todo Define visibility
95 */
96 public $changeLog;
97
98 /**
99 * @todo Define visibility
100 */
101 public $showMarked = FALSE;
102
103 /**
104 * @var array
105 */
106 protected $recordCache = array();
107
108 /**
109 * @var array
110 */
111 protected $pageAccessCache = array();
112
113 /**
114 * Constructor for the class
115 *
116 * @todo Define visibility
117 */
118 public function __construct() {
119 // GPvars:
120 $this->element = $this->getArgument('element');
121 $this->returnUrl = $this->getArgument('returnUrl');
122 $this->lastSyslogId = $this->getArgument('diff');
123 $this->rollbackFields = $this->getArgument('rollbackFields');
124 // Resolve sh_uid if set
125 $this->resolveShUid();
126 }
127
128 /**
129 * Main function for the listing of history.
130 * It detects incoming variables like element reference, history element uid etc. and renders the correct screen.
131 *
132 * @return HTML content for the module
133 * @todo Define visibility
134 */
135 public function main() {
136 $content = '';
137 // Single-click rollback
138 if ($this->getArgument('revert') && $this->getArgument('sumUp')) {
139 $this->rollbackFields = $this->getArgument('revert');
140 $this->showInsertDelete = 0;
141 $this->showSubElements = 0;
142 $element = explode(':', $this->element);
143 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_history', 'tablename=' . $GLOBALS['TYPO3_DB']->fullQuoteStr($element[0], 'sys_history') . ' AND recuid=' . (int)$element[1], '', 'uid DESC', '1');
144 $record = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
145 $this->lastSyslogId = $record['sys_log_uid'];
146 $this->createChangeLog();
147 $completeDiff = $this->createMultipleDiff();
148 $this->performRollback($completeDiff);
149 \TYPO3\CMS\Core\Utility\HttpUtility::redirect($this->returnUrl);
150 }
151 // Save snapshot
152 if ($this->getArgument('highlight') && !$this->getArgument('settings')) {
153 $this->toggleHighlight($this->getArgument('highlight'));
154 }
155 $content .= $this->displaySettings();
156 if ($this->createChangeLog()) {
157 if ($this->rollbackFields) {
158 $completeDiff = $this->createMultipleDiff();
159 $content .= $this->performRollback($completeDiff);
160 }
161 if ($this->lastSyslogId) {
162 $completeDiff = $this->createMultipleDiff();
163 $content .= $this->displayMultipleDiff($completeDiff);
164 }
165 if ($this->element) {
166 $content .= $this->displayHistory();
167 }
168 }
169 return $content;
170 }
171
172 /*******************************
173 *
174 * database actions
175 *
176 *******************************/
177 /**
178 * Toggles highlight state of record
179 *
180 * @param integer $uid Uid of sys_history entry
181 * @return void
182 * @todo Define visibility
183 */
184 public function toggleHighlight($uid) {
185 $uid = (int)$uid;
186 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('snapshot', 'sys_history', 'uid=' . $uid);
187 $tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
188 $GLOBALS['TYPO3_DB']->exec_UPDATEquery('sys_history', 'uid=' . $uid, array('snapshot' => !$tmp['snapshot']));
189 }
190
191 /**
192 * perform rollback
193 *
194 * @param array $diff Diff array to rollback
195 * @return void
196 * @access private
197 * @todo Define visibility
198 */
199 public function performRollback($diff) {
200 if (!$this->rollbackFields) {
201 return 0;
202 }
203 $reloadPageFrame = 0;
204 $rollbackData = explode(':', $this->rollbackFields);
205 // PROCESS INSERTS AND DELETES
206 // rewrite inserts and deletes
207 $cmdmapArray = array();
208 if ($diff['insertsDeletes']) {
209 switch (count($rollbackData)) {
210 case 1:
211 // all tables
212 $data = $diff['insertsDeletes'];
213 break;
214 case 2:
215 // one record
216 if ($diff['insertsDeletes'][$this->rollbackFields]) {
217 $data[$this->rollbackFields] = $diff['insertsDeletes'][$this->rollbackFields];
218 }
219 break;
220 case 3:
221 // one field in one record -- ignore!
222 break;
223 }
224 if ($data) {
225 foreach ($data as $key => $action) {
226 $elParts = explode(':', $key);
227 if ($action == 1) {
228 // inserted records should be deleted
229 $cmdmapArray[$elParts[0]][$elParts[1]]['delete'] = 1;
230 // When the record is deleted, the contents of the record do not need to be updated
231 unset($diff['oldData'][$key]);
232 unset($diff['newData'][$key]);
233 } elseif ($action == -1) {
234 // deleted records should be inserted again
235 $cmdmapArray[$elParts[0]][$elParts[1]]['undelete'] = 1;
236 }
237 }
238 }
239 }
240 // Writes the data:
241 if ($cmdmapArray) {
242 $tce = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
243 $tce->stripslashes_values = 0;
244 $tce->debug = 0;
245 $tce->dontProcessTransformations = 1;
246 $tce->start(array(), $cmdmapArray);
247 $tce->process_cmdmap();
248 unset($tce);
249 if (isset($cmdmapArray['pages'])) {
250 $reloadPageFrame = 1;
251 }
252 }
253 // PROCESS CHANGES
254 // create an array for process_datamap
255 $diff_modified = array();
256 foreach ($diff['oldData'] as $key => $value) {
257 $splitKey = explode(':', $key);
258 $diff_modified[$splitKey[0]][$splitKey[1]] = $value;
259 }
260 switch (count($rollbackData)) {
261 case 1:
262 // all tables
263 $data = $diff_modified;
264 break;
265 case 2:
266 // one record
267 $data[$rollbackData[0]][$rollbackData[1]] = $diff_modified[$rollbackData[0]][$rollbackData[1]];
268 break;
269 case 3:
270 // one field in one record
271 $data[$rollbackData[0]][$rollbackData[1]][$rollbackData[2]] = $diff_modified[$rollbackData[0]][$rollbackData[1]][$rollbackData[2]];
272 break;
273 }
274 // Removing fields:
275 $data = $this->removeFilefields($rollbackData[0], $data);
276 // Writes the data:
277 $tce = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\DataHandling\\DataHandler');
278 $tce->stripslashes_values = 0;
279 $tce->debug = 0;
280 $tce->dontProcessTransformations = 1;
281 $tce->start($data, array());
282 $tce->process_datamap();
283 unset($tce);
284 if (isset($data['pages'])) {
285 $reloadPageFrame = 1;
286 }
287 // Return to normal operation
288 $this->lastSyslogId = FALSE;
289 $this->rollbackFields = FALSE;
290 $this->createChangeLog();
291 // Reload page frame if necessary
292 if ($reloadPageFrame) {
293 return '<script type="text/javascript">
294 /*<![CDATA[*/
295 if (top.content && top.content.nav_frame && top.content.nav_frame.refresh_nav) {
296 top.content.nav_frame.refresh_nav();
297 }
298 /*]]>*/
299 </script>';
300 }
301 }
302
303 /*******************************
304 *
305 * Display functions
306 *
307 *******************************/
308 /**
309 * Displays settings
310 *
311 * @return string HTML code to modify settings
312 * @todo Define visibility
313 */
314 public function displaySettings() {
315 // Get current selection from UC, merge data, write it back to UC
316 $currentSelection = is_array($GLOBALS['BE_USER']->uc['moduleData']['history']) ? $GLOBALS['BE_USER']->uc['moduleData']['history'] : array('maxSteps' => '', 'showDiff' => 1, 'showSubElements' => 1, 'showInsertDelete' => 1);
317 $currentSelectionOverride = $this->getArgument('settings');
318 if ($currentSelectionOverride) {
319 $currentSelection = array_merge($currentSelection, $currentSelectionOverride);
320 $GLOBALS['BE_USER']->uc['moduleData']['history'] = $currentSelection;
321 $GLOBALS['BE_USER']->writeUC($GLOBALS['BE_USER']->uc);
322 }
323 // Display selector for number of history entries
324 $selector['maxSteps'] = array(
325 10 => 10,
326 20 => 20,
327 50 => 50,
328 100 => 100,
329 '' => 'maxSteps_all',
330 'marked' => 'maxSteps_marked'
331 );
332 $selector['showDiff'] = array(
333 0 => 'showDiff_no',
334 1 => 'showDiff_inline'
335 );
336 $selector['showSubElements'] = array(
337 0 => 'no',
338 1 => 'yes'
339 );
340 $selector['showInsertDelete'] = array(
341 0 => 'no',
342 1 => 'yes'
343 );
344 // render selectors
345 $displayCode = '';
346 foreach ($selector as $key => $values) {
347 $displayCode .= '<tr><td>' . $GLOBALS['LANG']->getLL($key, 1) . '</td>';
348 $displayCode .= '<td><select name="settings[' . $key . ']" onChange="document.settings.submit()" style="width:100px">';
349 foreach ($values as $singleKey => $singleVal) {
350 $caption = $GLOBALS['LANG']->getLL($singleVal, 1) ?: $singleVal;
351 $displayCode .= '<option value="' . $singleKey . '"' . ($singleKey == $currentSelection[$key] ? ' selected="selected"' : '') . '> ' . $caption . '</option>';
352 }
353 $displayCode .= '</select></td></tr>';
354 }
355 // set values correctly
356 if ($currentSelection['maxSteps'] != 'marked') {
357 $this->maxSteps = $currentSelection['maxSteps'] ? (int)$currentSelection['maxSteps'] : '';
358 } else {
359 $this->showMarked = TRUE;
360 $this->maxSteps = FALSE;
361 }
362 $this->showDiff = (int)$currentSelection['showDiff'];
363 $this->showSubElements = (int)$currentSelection['showSubElements'];
364 $this->showInsertDelete = (int)$currentSelection['showInsertDelete'];
365 $content = '';
366 // Get link to page history if the element history is shown
367 $elParts = explode(':', $this->element);
368 if (!empty($this->element) && $elParts[0] != 'pages') {
369 $content .= '<strong>' . $GLOBALS['LANG']->getLL('elementHistory', 1) . '</strong><br />';
370 $pid = $this->getRecord($elParts[0], $elParts[1]);
371
372 if ($this->hasPageAccess('pages', $pid['pid'])) {
373 $content .= $this->linkPage($GLOBALS['LANG']->getLL('elementHistory_link', 1), array('element' => 'pages:' . $pid['pid']));
374 }
375 }
376 $content .= '<form name="settings" action="' . htmlspecialchars(GeneralUtility::getIndpEnv('TYPO3_REQUEST_URL')) . '" method="post"><table>' . $displayCode . '</table></form>';
377 return $GLOBALS['SOBE']->doc->section($GLOBALS['LANG']->getLL('settings', 1), $content, FALSE, TRUE, FALSE, FALSE);
378 }
379
380 /**
381 * Shows the full change log
382 *
383 * @return string HTML for list, wrapped in a table.
384 * @todo Define visibility
385 */
386 public function displayHistory() {
387 $lines = array();
388 // Initialize:
389 $lines[] = '<thead><tr>
390 <th> </th>
391 <th>' . $GLOBALS['LANG']->getLL('time', 1) . '</th>
392 <th>' . $GLOBALS['LANG']->getLL('age', 1) . '</th>
393 <th>' . $GLOBALS['LANG']->getLL('user', 1) . '</th>
394 <th>' . $GLOBALS['LANG']->getLL('tableUid', 1) . '</th>
395 <th>' . $GLOBALS['LANG']->getLL('differences', 1) . '</th>
396 <th>&nbsp;</th>
397 </tr></thead>';
398 $be_user_array = BackendUtility::getUserNames();
399 // Traverse changelog array:
400 if (!$this->changeLog) {
401 return 0;
402 }
403 $i = 0;
404 foreach ($this->changeLog as $sysLogUid => $entry) {
405 // stop after maxSteps
406 if ($i > $this->maxSteps && $this->maxSteps) {
407 break;
408 }
409 // Show only marked states
410 if (!$entry['snapshot'] && $this->showMarked) {
411 continue;
412 }
413 $i++;
414 // Get user names
415 $userName = $entry['user'] ? $be_user_array[$entry['user']]['username'] : $GLOBALS['LANG']->getLL('externalChange', 1);
416 // Build up single line
417 $singleLine = array();
418 // Diff link
419 $image = IconUtility::getSpriteIcon('actions-view-go-forward', array('title' => $GLOBALS['LANG']->getLL('sumUpChanges', TRUE)));
420 $singleLine[] = '<span>' . $this->linkPage($image, array('diff' => $sysLogUid)) . '</span>';
421 // remove first link
422 $singleLine[] = htmlspecialchars(BackendUtility::datetime($entry['tstamp']));
423 // add time
424 $singleLine[] = htmlspecialchars(BackendUtility::calcAge($GLOBALS['EXEC_TIME'] - $entry['tstamp'], $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.xlf:labels.minutesHoursDaysYears')));
425 // add age
426 $singleLine[] = htmlspecialchars($userName);
427 // add user name
428 $singleLine[] = $this->linkPage($this->generateTitle($entry['tablename'], $entry['recuid']), array('element' => $entry['tablename'] . ':' . $entry['recuid']), '', $GLOBALS['LANG']->getLL('linkRecordHistory', 1));
429 // add record UID
430 // Show insert/delete/diff/changed field names
431 if ($entry['action']) {
432 // insert or delete of element
433 $singleLine[] = '<strong>' . htmlspecialchars($GLOBALS['LANG']->getLL($entry['action'], 1)) . '</strong>';
434 } else {
435 // Display field names instead of full diff
436 if (!$this->showDiff) {
437 // Re-write field names with labels
438 $tmpFieldList = explode(',', $entry['fieldlist']);
439 foreach ($tmpFieldList as $key => $value) {
440 $tmp = str_replace(':', '', $GLOBALS['LANG']->sl(BackendUtility::getItemLabel($entry['tablename'], $value), 1));
441 if ($tmp) {
442 $tmpFieldList[$key] = $tmp;
443 } else {
444 // remove fields if no label available
445 unset($tmpFieldList[$key]);
446 }
447 }
448 $singleLine[] = htmlspecialchars(implode(',', $tmpFieldList));
449 } else {
450 // Display diff
451 $diff = $this->renderDiff($entry, $entry['tablename']);
452 $singleLine[] = $diff;
453 }
454 }
455 // Show link to mark/unmark state
456 if (!$entry['action']) {
457 if ($entry['snapshot']) {
458 $image = IconUtility::getSpriteIcon('actions-unmarkstate', array('title' => $GLOBALS['LANG']->getLL('unmarkState', TRUE)), array());
459 } else {
460 $image = IconUtility::getSpriteIcon('actions-markstate', array('title' => $GLOBALS['LANG']->getLL('markState', TRUE)), array());
461 }
462 $singleLine[] = $this->linkPage($image, array('highlight' => $entry['uid']));
463 } else {
464 $singleLine[] = '';
465 }
466 // put line together
467 $lines[] = '
468 <tr>
469 <td>' . implode('</td><td>', $singleLine) . '</td>
470 </tr>';
471 }
472 // Finally, put it all together:
473 $theCode = '
474 <!--
475 History (list):
476 -->
477 <table class="t3-table" id="typo3-history">
478 ' . implode('', $lines) . '
479 </table>';
480 if ($this->lastSyslogId) {
481 $theCode .= '<br />' . $this->linkPage(IconUtility::getSpriteIcon('actions-move-to-bottom', array('title' => $GLOBALS['LANG']->getLL('fullView', TRUE))), array('diff' => ''));
482 }
483 // Add message about the difference view.
484 $flashMessage = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Messaging\\FlashMessage', $GLOBALS['LANG']->getLL('differenceMsg'), '', \TYPO3\CMS\Core\Messaging\FlashMessage::INFO);
485 $theCode .= '<br /><br />' . $flashMessage->render() . '<br />';
486 // Add the whole content as a module section:
487 return $GLOBALS['SOBE']->doc->section($GLOBALS['LANG']->getLL('changes'), $theCode, FALSE, TRUE);
488 }
489
490 /**
491 * Displays a diff over multiple fields including rollback links
492 *
493 * @param array $diff Difference array
494 * @return string HTML output
495 * @todo Define visibility
496 */
497 public function displayMultipleDiff($diff) {
498 $content = '';
499 // Get all array keys needed
500 $arrayKeys = array_merge(array_keys($diff['newData']), array_keys($diff['insertsDeletes']), array_keys($diff['oldData']));
501 $arrayKeys = array_unique($arrayKeys);
502 if ($arrayKeys) {
503 foreach ($arrayKeys as $key) {
504 $record = '';
505 $elParts = explode(':', $key);
506 // Turn around diff because it should be a "rollback preview"
507 if ($diff['insertsDeletes'][$key] == 1) {
508 // insert
509 $record .= '<strong>' . $GLOBALS['LANG']->getLL('delete', 1) . '</strong>';
510 $record .= '<br />';
511 } elseif ($diff['insertsDeletes'][$key] == -1) {
512 $record .= '<strong>' . $GLOBALS['LANG']->getLL('insert', 1) . '</strong>';
513 $record .= '<br />';
514 }
515 // Build up temporary diff array
516 // turn around diff because it should be a "rollback preview"
517 if ($diff['newData'][$key]) {
518 $tmpArr['newRecord'] = $diff['oldData'][$key];
519 $tmpArr['oldRecord'] = $diff['newData'][$key];
520 $record .= $this->renderDiff($tmpArr, $elParts[0], $elParts[1]);
521 }
522 $elParts = explode(':', $key);
523 $titleLine = $this->createRollbackLink($key, $GLOBALS['LANG']->getLL('revertRecord', 1), 1) . $this->generateTitle($elParts[0], $elParts[1]);
524 $record = '<div style="margin-left:10px;padding-left:5px;border-left:1px solid black;border-bottom:1px dotted black;padding-bottom:2px;">' . $record . '</div>';
525 $content .= $GLOBALS['SOBE']->doc->section($titleLine, $record, FALSE, FALSE, FALSE, TRUE);
526 }
527 $content = $this->createRollbackLink('ALL', $GLOBALS['LANG']->getLL('revertAll', 1), 0) . '<div style="margin-left:10px;padding-left:5px;border-left:1px solid black;border-bottom:1px dotted black;padding-bottom:2px;">' . $content . '</div>';
528 } else {
529 $content = $GLOBALS['LANG']->getLL('noDifferences', 1);
530 }
531 return $GLOBALS['SOBE']->doc->section($GLOBALS['LANG']->getLL('mergedDifferences', 1), $content, FALSE, TRUE, FALSE, TRUE);
532 }
533
534 /**
535 * Renders HTML table-rows with the comparison information of an sys_history entry record
536 *
537 * @param array $entry sys_history entry record.
538 * @param string $table The table name
539 * @param integer $rollbackUid If set to UID of record, display rollback links
540 * @return string HTML table
541 * @access private
542 * @todo Define visibility
543 */
544 public function renderDiff($entry, $table, $rollbackUid = 0) {
545 $lines = array();
546 if (is_array($entry['newRecord'])) {
547 $t3lib_diff_Obj = GeneralUtility::makeInstance('TYPO3\\CMS\\Core\\Utility\\DiffUtility');
548 $fieldsToDisplay = array_keys($entry['newRecord']);
549 foreach ($fieldsToDisplay as $fN) {
550 if (is_array($GLOBALS['TCA'][$table]['columns'][$fN]) && $GLOBALS['TCA'][$table]['columns'][$fN]['config']['type'] != 'passthrough') {
551 // Create diff-result:
552 $diffres = $t3lib_diff_Obj->makeDiffDisplay(BackendUtility::getProcessedValue($table, $fN, $entry['oldRecord'][$fN], 0, 1), BackendUtility::getProcessedValue($table, $fN, $entry['newRecord'][$fN], 0, 1));
553 $lines[] = '
554 <tr class="bgColor4">
555 ' . ($rollbackUid ? '<td style="width:33px">' . $this->createRollbackLink(($table . ':' . $rollbackUid . ':' . $fN), $GLOBALS['LANG']->getLL('revertField', 1), 2) . '</td>' : '') . '
556 <td style="width:90px"><em>' . $GLOBALS['LANG']->sl(BackendUtility::getItemLabel($table, $fN), 1) . '</em></td>
557 <td style="width:300px">' . nl2br($diffres) . '</td>
558 </tr>';
559 }
560 }
561 }
562 if ($lines) {
563 $content = '<table border="0" cellpadding="2" cellspacing="2" id="typo3-history-item">
564 ' . implode('', $lines) . '
565 </table>';
566 return $content;
567 }
568 // error fallback
569 return NULL;
570 }
571
572 /*******************************
573 *
574 * build up history
575 *
576 *******************************/
577 /**
578 * Creates a diff between the current version of the records and the selected version
579 *
580 * @return array Diff for many elements, 0 if no changelog is found
581 * @todo Define visibility
582 */
583 public function createMultipleDiff() {
584 $insertsDeletes = array();
585 $newArr = array();
586 $differences = array();
587 if (!$this->changeLog) {
588 return 0;
589 }
590 // traverse changelog array
591 foreach ($this->changeLog as $key => $value) {
592 $field = $value['tablename'] . ':' . $value['recuid'];
593 // inserts / deletes
594 if ($value['action']) {
595 if (!$insertsDeletes[$field]) {
596 $insertsDeletes[$field] = 0;
597 }
598 if ($value['action'] == 'insert') {
599 $insertsDeletes[$field]++;
600 } else {
601 $insertsDeletes[$field]--;
602 }
603 // unset not needed fields
604 if ($insertsDeletes[$field] == 0) {
605 unset($insertsDeletes[$field]);
606 }
607 } else {
608 // update fields
609 // first row of field
610 if (!isset($newArr[$field])) {
611 $newArr[$field] = $value['newRecord'];
612 $differences[$field] = $value['oldRecord'];
613 } else {
614 // standard
615 $differences[$field] = array_merge($differences[$field], $value['oldRecord']);
616 }
617 }
618 }
619 // remove entries where there were no changes effectively
620 foreach ($newArr as $record => $value) {
621 foreach ($value as $key => $innerVal) {
622 if ($newArr[$record][$key] == $differences[$record][$key]) {
623 unset($newArr[$record][$key]);
624 unset($differences[$record][$key]);
625 }
626 }
627 if (empty($newArr[$record]) && empty($differences[$record])) {
628 unset($newArr[$record]);
629 unset($differences[$record]);
630 }
631 }
632 return array(
633 'newData' => $newArr,
634 'oldData' => $differences,
635 'insertsDeletes' => $insertsDeletes
636 );
637 }
638
639 /**
640 * Creates change log including sub-elements, filling $this->changeLog
641 *
642 * @return integer
643 * @todo Define visibility
644 */
645 public function createChangeLog() {
646 $elParts = explode(':', $this->element);
647
648 if (empty($this->element)) {
649 return 0;
650 }
651
652 $changeLog = $this->getHistoryData($elParts[0], $elParts[1]);
653 // get history of tables of this page and merge it into changelog
654 if ($elParts[0] == 'pages' && $this->showSubElements && $this->hasPageAccess('pages', $elParts[1])) {
655 foreach ($GLOBALS['TCA'] as $tablename => $value) {
656 // check if there are records on the page
657 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $tablename, 'pid=' . (int)$elParts[1]);
658 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
659 // if there is history data available, merge it into changelog
660 if ($newChangeLog = $this->getHistoryData($tablename, $row['uid'])) {
661 foreach ($newChangeLog as $key => $value) {
662 $changeLog[$key] = $value;
663 }
664 }
665 }
666 }
667 }
668 if (!$changeLog) {
669 return 0;
670 }
671 krsort($changeLog);
672 $this->changeLog = $changeLog;
673 return 1;
674 }
675
676 /**
677 * Gets history and delete/insert data from sys_log and sys_history
678 *
679 * @param string $table DB table name
680 * @param integer $uid UID of record
681 * @return array history data of the record
682 * @todo Define visibility
683 */
684 public function getHistoryData($table, $uid) {
685 // If table is found in $GLOBALS['TCA']:
686 if ($GLOBALS['TCA'][$table] && $this->hasTableAccess($table) && $this->hasPageAccess($table, $uid)) {
687 $uid = $this->resolveElement($table, $uid);
688 // Selecting the $this->maxSteps most recent states:
689 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('sys_history.*, sys_log.userid', 'sys_history, sys_log', 'sys_history.sys_log_uid = sys_log.uid
690 AND sys_history.tablename = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_history') . '
691 AND sys_history.recuid = ' . (int)$uid, '', 'sys_log.uid DESC', $this->maxSteps);
692 // Traversing the result, building up changesArray / changeLog:
693 $changeLog = array();
694 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
695 // Only history until a certain syslog ID needed
696 if ($row['sys_log_uid'] < $this->lastSyslogId && $this->lastSyslogId) {
697 continue;
698 }
699 $hisDat = unserialize($row['history_data']);
700 if (is_array($hisDat['newRecord']) && is_array($hisDat['oldRecord'])) {
701 // Add hisDat to the changeLog
702 $hisDat['uid'] = $row['uid'];
703 $hisDat['tstamp'] = $row['tstamp'];
704 $hisDat['user'] = $row['userid'];
705 $hisDat['snapshot'] = $row['snapshot'];
706 $hisDat['fieldlist'] = $row['fieldlist'];
707 $hisDat['tablename'] = $row['tablename'];
708 $hisDat['recuid'] = $row['recuid'];
709 $changeLog[$row['sys_log_uid']] = $hisDat;
710 } else {
711 debug('ERROR: [getHistoryData]');
712 // error fallback
713 return 0;
714 }
715 }
716 // SELECT INSERTS/DELETES
717 if ($this->showInsertDelete) {
718 // Select most recent inserts and deletes // WITHOUT snapshots
719 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid, userid, action, tstamp', 'sys_log', 'type = 1
720 AND (action=1 OR action=3)
721 AND tablename = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_log') . '
722 AND recuid = ' . (int)$uid, '', 'uid DESC', $this->maxSteps);
723 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
724 if ($row['uid'] < $this->lastSyslogId && $this->lastSyslogId) {
725 continue;
726 }
727 $hisDat = array();
728 switch ($row['action']) {
729 case 1:
730 // Insert
731 $hisDat['action'] = 'insert';
732 break;
733 case 3:
734 // Delete
735 $hisDat['action'] = 'delete';
736 break;
737 }
738 $hisDat['tstamp'] = $row['tstamp'];
739 $hisDat['user'] = $row['userid'];
740 $hisDat['tablename'] = $table;
741 $hisDat['recuid'] = $uid;
742 $changeLog[$row['uid']] = $hisDat;
743 }
744 }
745 return $changeLog;
746 }
747 // error fallback
748 return 0;
749 }
750
751 /*******************************
752 *
753 * Various helper functions
754 *
755 *******************************/
756 /**
757 * Generates the title and puts the record title behind
758 *
759 * @param string $table
760 * @param string $uid
761 * @return string
762 * @todo Define visibility
763 */
764 public function generateTitle($table, $uid) {
765 $out = $table . ':' . $uid;
766 if ($labelField = $GLOBALS['TCA'][$table]['ctrl']['label']) {
767 $record = $this->getRecord($table, $uid);
768 $out .= ' (' . BackendUtility::getRecordTitle($table, $record, TRUE) . ')';
769 }
770 return $out;
771 }
772
773 /**
774 * Creates a link for the rollback
775 *
776 * @param string $key Parameter which is set to rollbackFields
777 * @param string $alt Optional, alternative label and title tag of image
778 * @param integer $type Optional, type of rollback: 0 - ALL; 1 - element; 2 - field
779 * @return string HTML output
780 * @todo Define visibility
781 */
782 public function createRollbackLink($key, $alt = '', $type = 0) {
783 return $this->linkPage('<img ' . IconUtility::skinImg('', ('gfx/revert_' . $type . '.gif'), 'width="33" height="33"') . ' alt="' . $alt . '" title="' . $alt . '" align="middle" />', array('rollbackFields' => $key));
784 }
785
786 /**
787 * Creates a link to the same page.
788 *
789 * @param string $str String to wrap in <a> tags (must be htmlspecialchars()'ed prior to calling function)
790 * @param array $inparams Array of key/value pairs to override the default values with.
791 * @param string $anchor Possible anchor value.
792 * @param string $title Possible title.
793 * @return string Link.
794 * @access private
795 * @todo Define visibility
796 */
797 public function linkPage($str, $inparams = array(), $anchor = '', $title = '') {
798 // Setting default values based on GET parameters:
799 $params['element'] = $this->element;
800 $params['returnUrl'] = $this->returnUrl;
801 $params['diff'] = $this->lastSyslogId;
802 // Mergin overriding values:
803 $params = array_merge($params, $inparams);
804 // Make the link:
805 $link = BackendUtility::getModuleUrl('record_history', $params) . ($anchor ? '#' . $anchor : '');
806 return '<a href="' . htmlspecialchars($link) . '"' . ($title ? ' title="' . $title . '"' : '') . '>' . $str . '</a>';
807 }
808
809 /**
810 * Will traverse the field names in $dataArray and look in $GLOBALS['TCA'] if the fields are of types which cannot be handled by the sys_history (that is currently group types with internal_type set to "file")
811 *
812 * @param string $table Table name
813 * @param array $dataArray The data array
814 * @return array The modified data array
815 * @access private
816 * @todo Define visibility
817 */
818 public function removeFilefields($table, $dataArray) {
819 if ($GLOBALS['TCA'][$table]) {
820 foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $config) {
821 if ($config['config']['type'] == 'group' && $config['config']['internal_type'] == 'file') {
822 unset($dataArray[$field]);
823 }
824 }
825 }
826 return $dataArray;
827 }
828
829 /**
830 * Convert input element reference to workspace version if any.
831 *
832 * @param string $table Table of input element
833 * @param integer $uid UID of record
834 * @return integer converted UID of record
835 * @todo Define visibility
836 */
837 public function resolveElement($table, $uid) {
838 if (isset($GLOBALS['TCA'][$table])) {
839 if ($workspaceVersion = BackendUtility::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $uid, 'uid')) {
840 $uid = $workspaceVersion['uid'];
841 }
842 }
843 return $uid;
844 }
845
846 /**
847 * Resolve sh_uid (used from log)
848 *
849 * @return void
850 * @todo Define visibility
851 */
852 public function resolveShUid() {
853 if ($this->getArgument('sh_uid')) {
854 $sh_uid = $this->getArgument('sh_uid');
855 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_history', 'uid=' . (int)$sh_uid);
856 $record = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
857 $this->element = $record['tablename'] . ':' . $record['recuid'];
858 $this->lastSyslogId = $record['sys_log_uid'] - 1;
859 }
860 }
861
862 /**
863 * Determines whether user has access to a page.
864 *
865 * @param string $table
866 * @param integer $uid
867 * @return boolean
868 */
869 protected function hasPageAccess($table, $uid) {
870 $uid = (int)$uid;
871
872 if ($table === 'pages') {
873 $pageId = $uid;
874 } else {
875 $record = $this->getRecord($table, $uid);
876 $pageId = $record['pid'];
877 }
878
879 if (!isset($this->pageAccessCache[$pageId])) {
880 $this->pageAccessCache[$pageId] = BackendUtility::readPageAccess(
881 $pageId, $this->getBackendUser()->getPagePermsClause(1)
882 );
883 }
884
885 return ($this->pageAccessCache[$pageId] !== FALSE);
886 }
887
888 /**
889 * Determines whether user has access to a table.
890 *
891 * @param string $table
892 * @return boolean
893 */
894 protected function hasTableAccess($table) {
895 return $this->getBackendUser()->check('tables_select', $table);
896 }
897
898 /**
899 * Gets a database record.
900 *
901 * @param string $table
902 * @param integer $uid
903 * @return array|NULL
904 */
905 protected function getRecord($table, $uid) {
906 if (!isset($this->recordCache[$table][$uid])) {
907 $this->recordCache[$table][$uid] = BackendUtility::getRecord($table, $uid, '*', '', FALSE);
908 }
909 return $this->recordCache[$table][$uid];
910 }
911
912 /**
913 * Gets the current backend user.
914 *
915 * @return \TYPO3\CMS\Core\Authentication\BackendUserAuthentication
916 */
917 protected function getBackendUser() {
918 return $GLOBALS['BE_USER'];
919 }
920
921 /**
922 * Fetches GET/POST arguments and sanitizes the values for
923 * the expected disposal. Invalid values will be converted
924 * to an empty string.
925 *
926 * @param string $name Name of the argument
927 * @return array|string|integer
928 */
929 protected function getArgument($name) {
930 $value = GeneralUtility::_GP($name);
931
932 switch ($name) {
933 case 'element':
934 if ($value !== '' && !preg_match('#^[a-z0-9_.]+:[0-9]+$#i', $value)) {
935 $value = '';
936 }
937 break;
938 case 'rollbackFields':
939 case 'revert':
940 if ($value !== '' && !preg_match('#^[a-z0-9_.]+(:[0-9]+(:[a-z0-9_.]+)?)?$#i', $value)) {
941 $value = '';
942 }
943 break;
944 case 'returnUrl':
945 $value = GeneralUtility::sanitizeLocalUrl($value);
946 break;
947 case 'diff':
948 case 'highlight':
949 case 'sh_uid':
950 $value = (int)$value;
951 break;
952 case 'settings':
953 if (!is_array($value)) {
954 $value = array();
955 }
956 break;
957 default:
958 $value = '';
959 }
960
961 return $value;
962 }
963
964 }