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