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