[BUGFIX] Fix PHP warning in EXT:beuser
[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                                         }
419                                         $singleLine[] = htmlspecialchars(implode(',', $tmpFieldList));
420                                 } else {        // Display diff
421                                         $diff = $this->renderDiff($entry, $entry['tablename']);
422                                         $singleLine[] = $diff;
423                                 }
424                         }
425
426                                 // Show link to mark/unmark state
427                         if (!$entry['action']) {
428                                 if ($entry['snapshot']) {
429                                         $image = '<img' . t3lib_iconWorks::skinImg('', 'gfx/unmarkstate.gif') . ' align="top" alt="' . $GLOBALS['LANG']->getLL('unmarkState', 1) . '" title="' . $GLOBALS['LANG']->getLL('unmarkState', 1) . '" />';
430                                 } else {
431                                         $image = '<img' . t3lib_iconWorks::skinImg('', 'gfx/markstate.gif') . ' align="top" alt="' . $GLOBALS['LANG']->getLL('markState', 1) . '" title="' . $GLOBALS['LANG']->getLL('markState', 1) . '" />';
432                                 }
433                                 $singleLine[] = $this->linkPage($image, array('highlight' => $entry['uid']));
434                         } else {
435                                 $singleLine[] = '';
436                         }
437
438                                 // put line together
439                         $lines[] = '
440                                 <tr class="db_list_normal">
441                                         <td>' . implode('</td><td>', $singleLine) . '</td>
442                                 </tr>';
443                 }
444
445                         // Finally, put it all together:
446                 $theCode = '
447                         <!--
448                                 History (list):
449                         -->
450                         <table class="typo3-dblist" border="0" cellpadding="0" cellspacing="0" id="typo3-history">
451                                 ' . implode('', $lines) . '
452                         </table>';
453
454                 if ($this->lastSyslogId) {
455                         $theCode .= '<br />' .  $this->linkPage(t3lib_iconWorks::getSpriteIcon('actions-move-to-bottom', array('title' => $GLOBALS['LANG']->getLL('fullView', TRUE))), array('diff' => ''));
456                 }
457
458                         // Add message about the difference view.
459                 $flashMessage = t3lib_div::makeInstance(
460                         't3lib_FlashMessage',
461                         $GLOBALS['LANG']->getLL('differenceMsg'),
462                         '',
463                         t3lib_FlashMessage::INFO
464                 );
465
466                 $theCode .= '<br /><br />' . $flashMessage->render() . '<br />';
467
468                         // Add the whole content as a module section:
469                 return $GLOBALS['SOBE']->doc->section($GLOBALS['LANG']->getLL('changes'), $theCode, FALSE, TRUE);
470         }
471
472         /**
473          * Displays a diff over multiple fields including rollback links
474          *
475          * @param array $diff Difference array
476          * @return string HTML output
477          */
478         function displayMultipleDiff($diff) {
479                 $content = '';
480
481                         // Get all array keys needed
482                 $arrayKeys = array_merge(array_keys($diff['newData']), array_keys($diff['insertsDeletes']), array_keys($diff['oldData']));
483                 $arrayKeys = array_unique($arrayKeys);
484
485                 if ($arrayKeys) {
486                         foreach ($arrayKeys as $key) {
487                                 $record = '';
488                                 $elParts = explode(':', $key);
489                                         // Turn around diff because it should be a "rollback preview"
490                                 if ($diff['insertsDeletes'][$key] == 1) {       // insert
491                                         $record .= '<strong>' . $GLOBALS['LANG']->getLL('delete', 1) . '</strong>';
492                                         $record .= '<br />';
493                                 } elseif ($diff['insertsDeletes'][$key] == -1) {
494                                         $record .= '<strong>' . $GLOBALS['LANG']->getLL('insert', 1) . '</strong>';
495                                         $record .= '<br />';
496                                 }
497                                         // Build up temporary diff array
498                                         // turn around diff because it should be a "rollback preview"
499                                 if ($diff['newData'][$key]) {
500                                         $tmpArr['newRecord'] = $diff['oldData'][$key];
501                                         $tmpArr['oldRecord'] = $diff['newData'][$key];
502                                         $record .= $this->renderDiff($tmpArr, $elParts[0], $elParts[1]);
503                                 }
504
505                                 $elParts = explode(':', $key);
506                                 $titleLine = $this->createRollbackLink($key, $GLOBALS['LANG']->getLL('revertRecord', 1), 1) . $this->generateTitle($elParts[0], $elParts[1]);
507                                 $record = '<div style="margin-left:10px;padding-left:5px;border-left:1px solid black;border-bottom:1px dotted black;padding-bottom:2px;">' . $record . '</div>';
508
509                                 $content .= $GLOBALS['SOBE']->doc->section($titleLine, $record, FALSE, FALSE, FALSE, TRUE);
510                         }
511                         $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>';
512                 } else {
513                         $content = $GLOBALS['LANG']->getLL('noDifferences', 1);
514                 }
515                 return $GLOBALS['SOBE']->doc->section($GLOBALS['LANG']->getLL('mergedDifferences', 1), $content, FALSE, TRUE, FALSE, TRUE);
516         }
517
518         /**
519          * Renders HTML table-rows with the comparison information of an sys_history entry record
520          *
521          * @param array $entry sys_history entry record.
522          * @param string $table The table name
523          * @param integer $rollbackUid If set to UID of record, display rollback links
524          * @return string HTML table
525          * @access private
526          */
527         function renderDiff($entry, $table, $rollbackUid = 0) {
528                 $lines = array();
529                 if (is_array($entry['newRecord'])) {
530
531                         $t3lib_diff_Obj = t3lib_div::makeInstance('t3lib_diff');
532
533                         $fieldsToDisplay = array_keys($entry['newRecord']);
534                         foreach ($fieldsToDisplay as $fN) {
535                                 t3lib_div::loadTCA($table);
536                                 if (is_array($GLOBALS['TCA'][$table]['columns'][$fN]) && $GLOBALS['TCA'][$table]['columns'][$fN]['config']['type'] != 'passthrough') {
537
538                                                 // Create diff-result:
539                                         $diffres = $t3lib_diff_Obj->makeDiffDisplay(
540                                                 t3lib_BEfunc::getProcessedValue($table, $fN, $entry['oldRecord'][$fN], 0, 1),
541                                                 t3lib_BEfunc::getProcessedValue($table, $fN, $entry['newRecord'][$fN], 0, 1)
542                                         );
543                                         $lines[] = '
544                                                 <tr class="bgColor4">
545                                                 ' . ($rollbackUid ? '<td style="width:33px">' . $this->createRollbackLink($table . ':' . $rollbackUid . ':' . $fN, $GLOBALS['LANG']->getLL('revertField', 1), 2) . '</td>' : '') . '
546                                                         <td style="width:90px"><em>' . $GLOBALS['LANG']->sl(t3lib_BEfunc::getItemLabel($table, $fN), 1) . '</em></td>
547                                                         <td style="width:300px">' . nl2br($diffres) . '</td>
548                                                 </tr>';
549                                 }
550                         }
551                 }
552                 if ($lines) {
553                         $content = '<table border="0" cellpadding="2" cellspacing="2" id="typo3-history-item">
554                                         ' . implode('', $lines) . '
555                                 </table>';
556                         return $content;
557                 }
558                         // error fallback
559                 return NULL;
560         }
561
562         /*******************************
563          *
564          * build up history
565          *
566          *******************************/
567
568         /**
569          * Creates a diff between the current version of the records and the selected version
570          *
571          * @return array Diff for many elements, 0 if no changelog is found
572          */
573         function createMultipleDiff() {
574                 $insertsDeletes = array();
575                 $newArr = array();
576                 $differences = array();
577                 if (!$this->changeLog) {
578                         return 0;
579                 }
580
581                         // traverse changelog array
582                 foreach ($this->changeLog as $key => $value) {
583                         $field = $value['tablename'] . ':' . $value['recuid'];
584
585                                 // inserts / deletes
586                         if ($value['action']) {
587                                 if (!$insertsDeletes[$field]) {
588                                         $insertsDeletes[$field] = 0;
589                                 }
590                                 if ($value['action'] == 'insert') {
591                                         $insertsDeletes[$field]++;
592                                 } else {
593                                         $insertsDeletes[$field]--;
594                                 }
595                                         // unset not needed fields
596                                 if ($insertsDeletes[$field] == 0) {
597                                         unset($insertsDeletes[$field]);
598                                 }
599                         } else {
600                                         // update fields
601                                         // first row of field
602                                 if (!isset($newArr[$field])) {
603                                         $newArr[$field] = $value['newRecord'];
604                                         $differences[$field] = $value['oldRecord'];
605                                 } else { // standard
606                                         $differences[$field] = array_merge($differences[$field], $value['oldRecord']);
607                                 }
608                         }
609                 }
610
611                         // remove entries where there were no changes effectively
612                 foreach ($newArr as $record => $value) {
613                         foreach ($value as $key => $innerVal) {
614                                 if ($newArr[$record][$key] == $differences[$record][$key]) {
615                                         unset($newArr[$record][$key]);
616                                         unset($differences[$record][$key]);
617                                 }
618                         }
619                         if (empty($newArr[$record]) && empty($differences[$record])) {
620                                 unset($newArr[$record]);
621                                 unset($differences[$record]);
622                         }
623                 }
624                 return array(
625                         'newData' => $newArr,
626                         'oldData' => $differences,
627                         'insertsDeletes' => $insertsDeletes
628                 );
629         }
630
631         /**
632          * Creates change log including sub-elements, filling $this->changeLog
633          *
634          * @return integer
635          */
636         function createChangeLog() {
637                 $elParts = explode(':', $this->element);
638                 $changeLog = $this->getHistoryData($elParts[0], $elParts[1]);
639
640                         // get history of tables of this page and merge it into changelog
641                 if ($elParts[0] == 'pages' && $this->showSubElements) {
642                         foreach ($GLOBALS['TCA'] as $tablename => $value) {
643                                         // check if there are records on the page
644                                 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $tablename, 'pid=' . intval($elParts[1]));
645                                 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
646                                                 // if there is history data available, merge it into changelog
647                                         if ($newChangeLog = $this->getHistoryData($tablename, $row['uid']))     {
648                                                 foreach ($newChangeLog as $key => $value) {
649                                                         $changeLog[$key] = $value;
650                                                 }
651                                         }
652                                 }
653                         }
654                 }
655                 if (!$changeLog) {
656                         return 0;
657                 }
658
659                 krsort($changeLog);
660                 $this->changeLog = $changeLog;
661
662                 return 1;
663         }
664
665         /**
666          * Gets history and delete/insert data from sys_log and sys_history
667          *
668          * @param string $table DB table name
669          * @param integer $uid UID of record
670          * @return array history data of the record
671          */
672         function getHistoryData($table, $uid) {
673                 $uid = $this->resolveElement($table, $uid);
674
675                         // If table is found in $GLOBALS['TCA']:
676                 if ($GLOBALS['TCA'][$table]) {
677
678                                 // Selecting the $this->maxSteps most recent states:
679                         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
680                                                 'sys_history.*, sys_log.userid',
681                                                 'sys_history, sys_log',
682                                                 'sys_history.sys_log_uid = sys_log.uid
683                                                         AND sys_history.tablename = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_history') . '
684                                                         AND sys_history.recuid = '.intval($uid),
685                                                 '',
686                                                 'sys_log.uid DESC',
687                                                 $this->maxSteps
688                                         );
689
690                                 // Traversing the result, building up changesArray / changeLog:
691                         $changeLog = array();
692
693                         while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
694                                         // Only history until a certain syslog ID needed
695                                 if ($row['sys_log_uid'] < $this->lastSyslogId && $this->lastSyslogId) {
696                                         continue;
697                                 }
698                                 $hisDat = unserialize($row['history_data']);
699
700                                 if (is_array($hisDat['newRecord']) && is_array($hisDat['oldRecord'])) {
701
702                                                 // Add hisDat to the changeLog
703                                         $hisDat['uid'] = $row['uid'];
704                                         $hisDat['tstamp'] = $row['tstamp'];
705                                         $hisDat['user'] = $row['userid'];
706                                         $hisDat['snapshot'] = $row['snapshot'];
707                                         $hisDat['fieldlist'] = $row['fieldlist'];
708                                         $hisDat['tablename'] = $row['tablename'];
709                                         $hisDat['recuid'] = $row['recuid'];
710
711                                         $changeLog[$row['sys_log_uid']] = $hisDat;
712                                 } else {
713                                         debug('ERROR: [getHistoryData]');
714                                                 // error fallback
715                                         return 0;
716                                 }
717                         }
718                                 // SELECT INSERTS/DELETES
719                         if ($this->showInsertDelete) {
720                                         // Select most recent inserts and deletes // WITHOUT snapshots
721                                 $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
722                                                 'uid, userid, action, tstamp',
723                                                 'sys_log',
724                                                 'type = 1
725                                                         AND (action=1 OR action=3)
726                                                         AND tablename = ' . $GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_log') . '
727                                                         AND recuid = ' . intval($uid),
728                                                 '',
729                                                 'uid DESC',
730                                                 $this->maxSteps
731                                         );
732                                 while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
733
734                                         if ($row['uid'] < $this->lastSyslogId && $this->lastSyslogId) {
735                                                 continue;
736                                         }
737                                         $hisDat = array();
738
739                                         switch ($row['action']) {
740                                                 case 1: // Insert
741                                                         $hisDat['action'] = 'insert';
742                                                         break;
743                                                 case 3: // Delete
744                                                         $hisDat['action'] = 'delete';
745                                                         break;
746                                         }
747                                         $hisDat['tstamp'] = $row['tstamp'];
748                                         $hisDat['user'] = $row['userid'];
749                                         $hisDat['tablename'] = $table;
750                                         $hisDat['recuid'] = $uid;
751                                         $changeLog[$row['uid']] = $hisDat;
752                                 }
753                         }
754                         return $changeLog;
755                 }
756                         // error fallback
757                 return 0;
758         }
759
760
761         /*******************************
762          *
763          * Various helper functions
764          *
765          *******************************/
766
767         /**
768          * Generates the title and puts the record title behind
769          *
770          * @param string $table
771          * @param string $uid
772          * @return string
773          */
774         function generateTitle($table, $uid) {
775                 $out = $table . ':' . $uid;
776                 if ($labelField = $GLOBALS['TCA'][$table]['ctrl']['label']) {
777                         $record = t3lib_BEfunc::getRecordRaw($table, 'uid=' . intval($uid));
778                         $out .= ' (' . t3lib_BEfunc::getRecordTitle($table, $record, TRUE) . ')';
779                 }
780                 return $out;
781         }
782         /**
783          * Creates a link for the rollback
784          *
785          * @param string $key Parameter which is set to rollbackFields
786          * @param string $alt Optional, alternative label and title tag of image
787          * @param integer $type Optional, type of rollback: 0 - ALL; 1 - element; 2 - field
788          * @return string HTML output
789          */
790         function createRollbackLink($key, $alt = '', $type = 0) {
791                 return $this->linkPage('<img ' . t3lib_iconWorks::skinImg('', 'gfx/revert_' . $type . '.gif', 'width="33" height="33"') . ' alt="' . $alt . '" title="' . $alt . '" align="middle" />', array('rollbackFields' => $key));
792         }
793
794         /**
795          * Creates a link to the same page.
796          *
797          * @param string $str String to wrap in <a> tags (must be htmlspecialchars()'ed prior to calling function)
798          * @param array $inparams Array of key/value pairs to override the default values with.
799          * @param string $anchor Possible anchor value.
800          * @param string $title Possible title.
801          * @return string Link.
802          * @access private
803          */
804         function linkPage($str, $inparams = array(), $anchor = '', $title = '') {
805
806                         // Setting default values based on GET parameters:
807                 $params['element'] = $this->element;
808                 $params['returnUrl'] = $this->returnUrl;
809                 $params['diff'] = $this->lastSyslogId;
810                         // Mergin overriding values:
811                 $params = array_merge($params, $inparams);
812
813                         // Make the link:
814                 $link = 'show_rechis.php?' . t3lib_div::implodeArrayForUrl('', $params) . ($anchor ? '#' . $anchor : '');
815                 return '<a href="' . htmlspecialchars($link) . '"' . ($title ? ' title="' . $title . '"' : '') . '>' . $str . '</a>';
816         }
817
818         /**
819          * 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")
820          *
821          * @param string $table Table name
822          * @param array $dataArray The data array
823          * @return array The modified data array
824          * @access private
825          */
826         function removeFilefields($table, $dataArray) {
827                 if ($GLOBALS['TCA'][$table]) {
828                         t3lib_div::loadTCA($table);
829
830                         foreach ($GLOBALS['TCA'][$table]['columns'] as $field => $config) {
831                                 if ($config['config']['type'] == 'group' && $config['config']['internal_type'] == 'file') {
832                                         unset($dataArray[$field]);
833                                 }
834                         }
835                 }
836                 return $dataArray;
837         }
838
839         /**
840          * Convert input element reference to workspace version if any.
841          *
842          * @param string $table Table of input element
843          * @param integer $uid UID of record
844          * @return integer converted UID of record
845          */
846         function resolveElement($table, $uid) {
847                 if (isset($GLOBALS['TCA'][$table])) {
848                         if ($workspaceVersion = t3lib_BEfunc::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace, $table, $uid, 'uid')) {
849                                 $uid = $workspaceVersion['uid'];
850                         }
851                 }
852                 return $uid;
853         }
854
855         /**
856          * Resolve sh_uid (used from log)
857          *
858          * @return void
859          */
860         function resolveShUid() {
861                 if (t3lib_div::_GP('sh_uid')) {
862                         $sh_uid = t3lib_div::_GP('sh_uid');
863                         $res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'sys_history', 'uid=' . intval($sh_uid));
864                         $record = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
865                         $this->element = $record['tablename'] . ':' . $record['recuid'];
866                         $this->lastSyslogId = $record['sys_log_uid'] - 1;
867                 }
868         }
869 }
870 ?>