* Add exception hooks to output pretty messages
[lhc/web/wiklou.git] / includes / SpecialUndelete.php
1 <?php
2
3 /**
4 * Special page allowing users with the appropriate permissions to view
5 * and restore deleted content
6 *
7 * @addtogroup SpecialPage
8 */
9
10 /**
11 * Constructor
12 */
13 function wfSpecialUndelete( $par ) {
14 global $wgRequest;
15
16 $form = new UndeleteForm( $wgRequest, $par );
17 $form->execute();
18 }
19
20 /**
21 * Used to show archived pages and eventually restore them.
22 * @addtogroup SpecialPage
23 */
24 class PageArchive {
25 protected $title;
26 var $fileStatus;
27
28 function __construct( $title ) {
29 if( is_null( $title ) ) {
30 throw new MWException( 'Archiver() given a null title.');
31 }
32 $this->title = $title;
33 }
34
35 /**
36 * List all deleted pages recorded in the archive table. Returns result
37 * wrapper with (ar_namespace, ar_title, count) fields, ordered by page
38 * namespace/title.
39 *
40 * @return ResultWrapper
41 */
42 public static function listAllPages() {
43 $dbr = wfGetDB( DB_SLAVE );
44 return self::listPages( $dbr, '' );
45 }
46
47 /**
48 * List deleted pages recorded in the archive table matching the
49 * given title prefix.
50 * Returns result wrapper with (ar_namespace, ar_title, count) fields.
51 *
52 * @return ResultWrapper
53 */
54 public static function listPagesByPrefix( $prefix ) {
55 $dbr = wfGetDB( DB_SLAVE );
56
57 $title = Title::newFromText( $prefix );
58 if( $title ) {
59 $ns = $title->getNamespace();
60 $encPrefix = $dbr->escapeLike( $title->getDbKey() );
61 } else {
62 // Prolly won't work too good
63 // @todo handle bare namespace names cleanly?
64 $ns = 0;
65 $encPrefix = $dbr->escapeLike( $prefix );
66 }
67 $conds = array(
68 'ar_namespace' => $ns,
69 "ar_title LIKE '$encPrefix%'",
70 );
71 return self::listPages( $dbr, $conds );
72 }
73
74 protected static function listPages( $dbr, $condition ) {
75 return $dbr->resultObject(
76 $dbr->select(
77 array( 'archive' ),
78 array(
79 'ar_namespace',
80 'ar_title',
81 'COUNT(*) AS count',
82 ),
83 $condition,
84 __METHOD__,
85 array(
86 'GROUP BY' => 'ar_namespace,ar_title',
87 'ORDER BY' => 'ar_namespace,ar_title',
88 'LIMIT' => 100,
89 )
90 )
91 );
92 }
93
94 /**
95 * List the revisions of the given page. Returns result wrapper with
96 * (ar_minor_edit, ar_timestamp, ar_user, ar_user_text, ar_comment) fields.
97 *
98 * @return ResultWrapper
99 */
100 function listRevisions() {
101 $dbr = wfGetDB( DB_SLAVE );
102 $res = $dbr->select( 'archive',
103 array( 'ar_minor_edit', 'ar_timestamp', 'ar_user', 'ar_user_text', 'ar_comment', 'ar_len' ),
104 array( 'ar_namespace' => $this->title->getNamespace(),
105 'ar_title' => $this->title->getDBkey() ),
106 'PageArchive::listRevisions',
107 array( 'ORDER BY' => 'ar_timestamp DESC' ) );
108 $ret = $dbr->resultObject( $res );
109 return $ret;
110 }
111
112 /**
113 * List the deleted file revisions for this page, if it's a file page.
114 * Returns a result wrapper with various filearchive fields, or null
115 * if not a file page.
116 *
117 * @return ResultWrapper
118 * @todo Does this belong in Image for fuller encapsulation?
119 */
120 function listFiles() {
121 if( $this->title->getNamespace() == NS_IMAGE ) {
122 $dbr = wfGetDB( DB_SLAVE );
123 $res = $dbr->select( 'filearchive',
124 array(
125 'fa_id',
126 'fa_name',
127 'fa_storage_key',
128 'fa_size',
129 'fa_width',
130 'fa_height',
131 'fa_description',
132 'fa_user',
133 'fa_user_text',
134 'fa_timestamp' ),
135 array( 'fa_name' => $this->title->getDbKey() ),
136 __METHOD__,
137 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
138 $ret = $dbr->resultObject( $res );
139 return $ret;
140 }
141 return null;
142 }
143
144 /**
145 * Fetch (and decompress if necessary) the stored text for the deleted
146 * revision of the page with the given timestamp.
147 *
148 * @return string
149 * @deprecated Use getRevision() for more flexible information
150 */
151 function getRevisionText( $timestamp ) {
152 $rev = $this->getRevision( $timestamp );
153 return $rev ? $rev->getText() : null;
154 }
155
156 /**
157 * Return a Revision object containing data for the deleted revision.
158 * Note that the result *may* or *may not* have a null page ID.
159 * @param string $timestamp
160 * @return Revision
161 */
162 function getRevision( $timestamp ) {
163 $dbr = wfGetDB( DB_SLAVE );
164 $row = $dbr->selectRow( 'archive',
165 array(
166 'ar_rev_id',
167 'ar_text',
168 'ar_comment',
169 'ar_user',
170 'ar_user_text',
171 'ar_timestamp',
172 'ar_minor_edit',
173 'ar_flags',
174 'ar_text_id',
175 'ar_len' ),
176 array( 'ar_namespace' => $this->title->getNamespace(),
177 'ar_title' => $this->title->getDbkey(),
178 'ar_timestamp' => $dbr->timestamp( $timestamp ) ),
179 __METHOD__ );
180 if( $row ) {
181 return new Revision( array(
182 'page' => $this->title->getArticleId(),
183 'id' => $row->ar_rev_id,
184 'text' => ($row->ar_text_id
185 ? null
186 : Revision::getRevisionText( $row, 'ar_' ) ),
187 'comment' => $row->ar_comment,
188 'user' => $row->ar_user,
189 'user_text' => $row->ar_user_text,
190 'timestamp' => $row->ar_timestamp,
191 'minor_edit' => $row->ar_minor_edit,
192 'text_id' => $row->ar_text_id ) );
193 } else {
194 return null;
195 }
196 }
197
198 /**
199 * Return the most-previous revision, either live or deleted, against
200 * the deleted revision given by timestamp.
201 *
202 * May produce unexpected results in case of history merges or other
203 * unusual time issues.
204 *
205 * @param string $timestamp
206 * @return Revision or null
207 */
208 function getPreviousRevision( $timestamp ) {
209 $dbr = wfGetDB( DB_SLAVE );
210
211 // Check the previous deleted revision...
212 $row = $dbr->selectRow( 'archive',
213 'ar_timestamp',
214 array( 'ar_namespace' => $this->title->getNamespace(),
215 'ar_title' => $this->title->getDbkey(),
216 'ar_timestamp < ' .
217 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ),
218 __METHOD__,
219 array(
220 'ORDER BY' => 'ar_timestamp DESC',
221 'LIMIT' => 1 ) );
222 $prevDeleted = $row ? wfTimestamp( TS_MW, $row->ar_timestamp ) : false;
223
224 $row = $dbr->selectRow( array( 'page', 'revision' ),
225 array( 'rev_id', 'rev_timestamp' ),
226 array(
227 'page_namespace' => $this->title->getNamespace(),
228 'page_title' => $this->title->getDbkey(),
229 'page_id = rev_page',
230 'rev_timestamp < ' .
231 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ),
232 __METHOD__,
233 array(
234 'ORDER BY' => 'rev_timestamp DESC',
235 'LIMIT' => 1 ) );
236 $prevLive = $row ? wfTimestamp( TS_MW, $row->rev_timestamp ) : false;
237 $prevLiveId = $row ? intval( $row->rev_id ) : null;
238
239 if( $prevLive && $prevLive > $prevDeleted ) {
240 // Most prior revision was live
241 return Revision::newFromId( $prevLiveId );
242 } elseif( $prevDeleted ) {
243 // Most prior revision was deleted
244 return $this->getRevision( $prevDeleted );
245 } else {
246 // No prior revision on this page.
247 return null;
248 }
249 }
250
251 /**
252 * Get the text from an archive row containing ar_text, ar_flags and ar_text_id
253 */
254 function getTextFromRow( $row ) {
255 if( is_null( $row->ar_text_id ) ) {
256 // An old row from MediaWiki 1.4 or previous.
257 // Text is embedded in this row in classic compression format.
258 return Revision::getRevisionText( $row, "ar_" );
259 } else {
260 // New-style: keyed to the text storage backend.
261 $dbr = wfGetDB( DB_SLAVE );
262 $text = $dbr->selectRow( 'text',
263 array( 'old_text', 'old_flags' ),
264 array( 'old_id' => $row->ar_text_id ),
265 __METHOD__ );
266 return Revision::getRevisionText( $text );
267 }
268 }
269
270
271 /**
272 * Fetch (and decompress if necessary) the stored text of the most
273 * recently edited deleted revision of the page.
274 *
275 * If there are no archived revisions for the page, returns NULL.
276 *
277 * @return string
278 */
279 function getLastRevisionText() {
280 $dbr = wfGetDB( DB_SLAVE );
281 $row = $dbr->selectRow( 'archive',
282 array( 'ar_text', 'ar_flags', 'ar_text_id' ),
283 array( 'ar_namespace' => $this->title->getNamespace(),
284 'ar_title' => $this->title->getDBkey() ),
285 'PageArchive::getLastRevisionText',
286 array( 'ORDER BY' => 'ar_timestamp DESC' ) );
287 if( $row ) {
288 return $this->getTextFromRow( $row );
289 } else {
290 return NULL;
291 }
292 }
293
294 /**
295 * Quick check if any archived revisions are present for the page.
296 * @return bool
297 */
298 function isDeleted() {
299 $dbr = wfGetDB( DB_SLAVE );
300 $n = $dbr->selectField( 'archive', 'COUNT(ar_title)',
301 array( 'ar_namespace' => $this->title->getNamespace(),
302 'ar_title' => $this->title->getDBkey() ) );
303 return ($n > 0);
304 }
305
306 const UNDELETE_NOTHINGRESTORED = 0; // No revisions could be restored
307 const UNDELETE_NOTAVAIL = -1; // Not all requested revisions are available
308 const UNDELETE_UNKNOWNERR = -2; // Unknown error
309 /**
310 * Restore the given (or all) text and file revisions for the page.
311 * Once restored, the items will be removed from the archive tables.
312 * The deletion log will be updated with an undeletion notice.
313 *
314 * @param array $timestamps Pass an empty array to restore all revisions, otherwise list the ones to undelete.
315 * @param string $comment
316 * @param array $fileVersions
317 *
318 * @return array(number of revisions restored, number of file versions restored, log reason) on success or UNDELETE_* on failure
319 */
320 function undelete( $timestamps, $comment = '', $fileVersions = array() ) {
321 // If both the set of text revisions and file revisions are empty,
322 // restore everything. Otherwise, just restore the requested items.
323 $restoreAll = empty( $timestamps ) && empty( $fileVersions );
324
325 $restoreText = $restoreAll || !empty( $timestamps );
326 $restoreFiles = $restoreAll || !empty( $fileVersions );
327
328 if( $restoreFiles && $this->title->getNamespace() == NS_IMAGE ) {
329 $img = wfLocalFile( $this->title );
330 $this->fileStatus = $img->restore( $fileVersions );
331 $filesRestored = $this->fileStatus->successCount;
332 } else {
333 $filesRestored = 0;
334 }
335
336 if( $restoreText ) {
337 $textRestored = $this->undeleteRevisions( $timestamps );
338 if($textRestored < 0) // It must be one of UNDELETE_*
339 return $textRestored;
340 } else {
341 $textRestored = 0;
342 }
343
344 // Touch the log!
345 global $wgContLang;
346 $log = new LogPage( 'delete' );
347
348 if( $textRestored && $filesRestored ) {
349 $reason = wfMsgExt( 'undeletedrevisions-files', array( 'content', 'parsemag' ),
350 $wgContLang->formatNum( $textRestored ),
351 $wgContLang->formatNum( $filesRestored ) );
352 } elseif( $textRestored ) {
353 $reason = wfMsgExt( 'undeletedrevisions', array( 'content', 'parsemag' ),
354 $wgContLang->formatNum( $textRestored ) );
355 } elseif( $filesRestored ) {
356 $reason = wfMsgExt( 'undeletedfiles', array( 'content', 'parsemag' ),
357 $wgContLang->formatNum( $filesRestored ) );
358 } else {
359 wfDebug( "Undelete: nothing undeleted...\n" );
360 return self::UNDELETE_NOTHINGRESTORED;
361 }
362
363 if( trim( $comment ) != '' )
364 $reason .= ": {$comment}";
365 $log->addEntry( 'restore', $this->title, $reason );
366
367 return array($textRestored, $filesRestored, $reason);
368 }
369
370 /**
371 * This is the meaty bit -- restores archived revisions of the given page
372 * to the cur/old tables. If the page currently exists, all revisions will
373 * be stuffed into old, otherwise the most recent will go into cur.
374 *
375 * @param array $timestamps Pass an empty array to restore all revisions, otherwise list the ones to undelete.
376 * @param string $comment
377 * @param array $fileVersions
378 *
379 * @return int number of revisions restored on success or UNDELETE_* on failure
380 */
381 private function undeleteRevisions( $timestamps ) {
382 if ( wfReadOnly() ) return 0;
383
384 $restoreAll = empty( $timestamps );
385
386 $dbw = wfGetDB( DB_MASTER );
387
388 # Does this page already exist? We'll have to update it...
389 $article = new Article( $this->title );
390 $options = 'FOR UPDATE';
391 $page = $dbw->selectRow( 'page',
392 array( 'page_id', 'page_latest' ),
393 array( 'page_namespace' => $this->title->getNamespace(),
394 'page_title' => $this->title->getDBkey() ),
395 __METHOD__,
396 $options );
397 if( $page ) {
398 # Page already exists. Import the history, and if necessary
399 # we'll update the latest revision field in the record.
400 $newid = 0;
401 $pageId = $page->page_id;
402 $previousRevId = $page->page_latest;
403 } else {
404 # Have to create a new article...
405 $newid = $article->insertOn( $dbw );
406 $pageId = $newid;
407 $previousRevId = 0;
408 }
409
410 if( $restoreAll ) {
411 $oldones = '1 = 1'; # All revisions...
412 } else {
413 $oldts = implode( ',',
414 array_map( array( &$dbw, 'addQuotes' ),
415 array_map( array( &$dbw, 'timestamp' ),
416 $timestamps ) ) );
417
418 $oldones = "ar_timestamp IN ( {$oldts} )";
419 }
420
421 /**
422 * Restore each revision...
423 */
424 $result = $dbw->select( 'archive',
425 /* fields */ array(
426 'ar_rev_id',
427 'ar_text',
428 'ar_comment',
429 'ar_user',
430 'ar_user_text',
431 'ar_timestamp',
432 'ar_minor_edit',
433 'ar_flags',
434 'ar_text_id',
435 'ar_page_id',
436 'ar_len' ),
437 /* WHERE */ array(
438 'ar_namespace' => $this->title->getNamespace(),
439 'ar_title' => $this->title->getDBkey(),
440 $oldones ),
441 __METHOD__,
442 /* options */ array(
443 'ORDER BY' => 'ar_timestamp' )
444 );
445 if( $dbw->numRows( $result ) < count( $timestamps ) ) {
446 wfDebug( __METHOD__.": couldn't find all requested rows\n" );
447 return self::UNDELETE_NOTAVAIL;
448 }
449
450 $revision = null;
451 $restored = 0;
452
453 while( $row = $dbw->fetchObject( $result ) ) {
454 if( $row->ar_text_id ) {
455 // Revision was deleted in 1.5+; text is in
456 // the regular text table, use the reference.
457 // Specify null here so the so the text is
458 // dereferenced for page length info if needed.
459 $revText = null;
460 } else {
461 // Revision was deleted in 1.4 or earlier.
462 // Text is squashed into the archive row, and
463 // a new text table entry will be created for it.
464 $revText = Revision::getRevisionText( $row, 'ar_' );
465 }
466 $revision = new Revision( array(
467 'page' => $pageId,
468 'id' => $row->ar_rev_id,
469 'text' => $revText,
470 'comment' => $row->ar_comment,
471 'user' => $row->ar_user,
472 'user_text' => $row->ar_user_text,
473 'timestamp' => $row->ar_timestamp,
474 'minor_edit' => $row->ar_minor_edit,
475 'text_id' => $row->ar_text_id,
476 'len' => $row->ar_len
477 ) );
478 $revision->insertOn( $dbw );
479 $restored++;
480
481 wfRunHooks( 'ArticleRevisionUndeleted', array( &$this->title, $revision, $row->ar_page_id ) );
482 }
483 // Was anything restored at all?
484 if($restored == 0)
485 return 0;
486
487 if( $revision ) {
488 // Attach the latest revision to the page...
489 $wasnew = $article->updateIfNewerOn( $dbw, $revision, $previousRevId );
490
491 if( $newid || $wasnew ) {
492 // Update site stats, link tables, etc
493 $article->createUpdates( $revision );
494 }
495
496 if( $newid ) {
497 wfRunHooks( 'ArticleUndelete', array( &$this->title, true ) );
498 Article::onArticleCreate( $this->title );
499 } else {
500 wfRunHooks( 'ArticleUndelete', array( &$this->title, false ) );
501 Article::onArticleEdit( $this->title );
502 }
503 } else {
504 // Revision couldn't be created. This is very weird
505 return self::UNDELETE_UNKNOWNERR;
506 }
507
508 # Now that it's safely stored, take it out of the archive
509 $dbw->delete( 'archive',
510 /* WHERE */ array(
511 'ar_namespace' => $this->title->getNamespace(),
512 'ar_title' => $this->title->getDBkey(),
513 $oldones ),
514 __METHOD__ );
515
516 return $restored;
517 }
518
519 function getFileStatus() { return $this->fileStatus; }
520 }
521
522 /**
523 * The HTML form for Special:Undelete, which allows users with the appropriate
524 * permissions to view and restore deleted content.
525 * @addtogroup SpecialPage
526 */
527 class UndeleteForm {
528 var $mAction, $mTarget, $mTimestamp, $mRestore, $mTargetObj;
529 var $mTargetTimestamp, $mAllowed, $mComment;
530
531 function UndeleteForm( $request, $par = "" ) {
532 global $wgUser;
533 $this->mAction = $request->getVal( 'action' );
534 $this->mTarget = $request->getVal( 'target' );
535 $this->mSearchPrefix = $request->getText( 'prefix' );
536 $time = $request->getVal( 'timestamp' );
537 $this->mTimestamp = $time ? wfTimestamp( TS_MW, $time ) : '';
538 $this->mFile = $request->getVal( 'file' );
539
540 $posted = $request->wasPosted() &&
541 $wgUser->matchEditToken( $request->getVal( 'wpEditToken' ) );
542 $this->mRestore = $request->getCheck( 'restore' ) && $posted;
543 $this->mPreview = $request->getCheck( 'preview' ) && $posted;
544 $this->mDiff = $request->getCheck( 'diff' );
545 $this->mComment = $request->getText( 'wpComment' );
546
547 if( $par != "" ) {
548 $this->mTarget = $par;
549 }
550 if ( $wgUser->isAllowed( 'undelete' ) && !$wgUser->isBlocked() ) {
551 $this->mAllowed = true;
552 } else {
553 $this->mAllowed = false;
554 $this->mTimestamp = '';
555 $this->mRestore = false;
556 }
557 if ( $this->mTarget !== "" ) {
558 $this->mTargetObj = Title::newFromURL( $this->mTarget );
559 } else {
560 $this->mTargetObj = NULL;
561 }
562 if( $this->mRestore ) {
563 $timestamps = array();
564 $this->mFileVersions = array();
565 foreach( $_REQUEST as $key => $val ) {
566 $matches = array();
567 if( preg_match( '/^ts(\d{14})$/', $key, $matches ) ) {
568 array_push( $timestamps, $matches[1] );
569 }
570
571 if( preg_match( '/^fileid(\d+)$/', $key, $matches ) ) {
572 $this->mFileVersions[] = intval( $matches[1] );
573 }
574 }
575 rsort( $timestamps );
576 $this->mTargetTimestamp = $timestamps;
577 }
578 }
579
580 function execute() {
581 global $wgOut;
582 if ( $this->mAllowed ) {
583 $wgOut->setPagetitle( wfMsg( "undeletepage" ) );
584 } else {
585 $wgOut->setPagetitle( wfMsg( "viewdeletedpage" ) );
586 }
587
588 if( is_null( $this->mTargetObj ) ) {
589 $this->showSearchForm();
590
591 # List undeletable articles
592 if( $this->mSearchPrefix ) {
593 $result = PageArchive::listPagesByPrefix(
594 $this->mSearchPrefix );
595 $this->showList( $result );
596 }
597 return;
598 }
599 if( $this->mTimestamp !== '' ) {
600 return $this->showRevision( $this->mTimestamp );
601 }
602 if( $this->mFile !== null ) {
603 return $this->showFile( $this->mFile );
604 }
605 if( $this->mRestore && $this->mAction == "submit" ) {
606 return $this->undelete();
607 }
608 return $this->showHistory();
609 }
610
611 function showSearchForm() {
612 global $wgOut, $wgScript;
613 $wgOut->addWikiText( wfMsg( 'undelete-header' ) );
614
615 $wgOut->addHtml(
616 Xml::openElement( 'form', array(
617 'method' => 'get',
618 'action' => $wgScript ) ) .
619 '<fieldset>' .
620 Xml::element( 'legend', array(),
621 wfMsg( 'undelete-search-box' ) ) .
622 Xml::hidden( 'title',
623 SpecialPage::getTitleFor( 'Undelete' )->getPrefixedDbKey() ) .
624 Xml::inputLabel( wfMsg( 'undelete-search-prefix' ),
625 'prefix', 'prefix', 20,
626 $this->mSearchPrefix ) .
627 Xml::submitButton( wfMsg( 'undelete-search-submit' ) ) .
628 '</fieldset>' .
629 '</form>' );
630 }
631
632 /* private */ function showList( $result ) {
633 global $wgLang, $wgContLang, $wgUser, $wgOut;
634
635 if( $result->numRows() == 0 ) {
636 $wgOut->addWikiText( wfMsg( 'undelete-no-results' ) );
637 return;
638 }
639
640 $wgOut->addWikiText( wfMsg( "undeletepagetext" ) );
641
642 $sk = $wgUser->getSkin();
643 $undelete = SpecialPage::getTitleFor( 'Undelete' );
644 $wgOut->addHTML( "<ul>\n" );
645 while( $row = $result->fetchObject() ) {
646 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
647 $link = $sk->makeKnownLinkObj( $undelete, htmlspecialchars( $title->getPrefixedText() ), 'target=' . $title->getPrefixedUrl() );
648 #$revs = wfMsgHtml( 'undeleterevisions', $wgLang->formatNum( $row->count ) );
649 $revs = wfMsgExt( 'undeleterevisions',
650 array( 'parseinline' ),
651 $wgLang->formatNum( $row->count ) );
652 $wgOut->addHtml( "<li>{$link} ({$revs})</li>\n" );
653 }
654 $result->free();
655 $wgOut->addHTML( "</ul>\n" );
656
657 return true;
658 }
659
660 /* private */ function showRevision( $timestamp ) {
661 global $wgLang, $wgUser, $wgOut;
662 $self = SpecialPage::getTitleFor( 'Undelete' );
663 $skin = $wgUser->getSkin();
664
665 if(!preg_match("/[0-9]{14}/",$timestamp)) return 0;
666
667 $archive = new PageArchive( $this->mTargetObj );
668 $rev = $archive->getRevision( $timestamp );
669
670 if( !$rev ) {
671 $wgOut->addWikiTexT( wfMsg( 'undeleterevision-missing' ) );
672 return;
673 }
674
675 $wgOut->setPageTitle( wfMsg( 'undeletepage' ) );
676
677 $link = $skin->makeKnownLinkObj(
678 SpecialPage::getTitleFor( 'Undelete', $this->mTargetObj->getPrefixedDBkey() ),
679 htmlspecialchars( $this->mTargetObj->getPrefixedText() )
680 );
681 $time = htmlspecialchars( $wgLang->timeAndDate( $timestamp, true ) );
682 $user = $skin->userLink( $rev->getUser(), $rev->getUserText() )
683 . $skin->userToolLinks( $rev->getUser(), $rev->getUserText() );
684
685 if( $this->mDiff ) {
686 $previousRev = $archive->getPreviousRevision( $timestamp );
687 if( $previousRev ) {
688 $this->showDiff( $previousRev, $rev );
689 if( $wgUser->getOption( 'diffonly' ) ) {
690 return;
691 } else {
692 $wgOut->addHtml( '<hr />' );
693 }
694 } else {
695 $wgOut->addHtml( wfMsgHtml( 'undelete-nodiff' ) );
696 }
697 }
698
699 $wgOut->addHtml( '<p>' . wfMsgHtml( 'undelete-revision', $link, $time, $user ) . '</p>' );
700
701 wfRunHooks( 'UndeleteShowRevision', array( $this->mTargetObj, $rev ) );
702
703 if( $this->mPreview ) {
704 $wgOut->addHtml( "<hr />\n" );
705 $wgOut->addWikiTextTitleTidy( $rev->getText(), $this->mTargetObj, false );
706 }
707
708 $wgOut->addHtml(
709 wfElement( 'textarea', array(
710 'readonly' => 'readonly',
711 'cols' => intval( $wgUser->getOption( 'cols' ) ),
712 'rows' => intval( $wgUser->getOption( 'rows' ) ) ),
713 $rev->getText() . "\n" ) .
714 wfOpenElement( 'div' ) .
715 wfOpenElement( 'form', array(
716 'method' => 'post',
717 'action' => $self->getLocalURL( "action=submit" ) ) ) .
718 wfElement( 'input', array(
719 'type' => 'hidden',
720 'name' => 'target',
721 'value' => $this->mTargetObj->getPrefixedDbKey() ) ) .
722 wfElement( 'input', array(
723 'type' => 'hidden',
724 'name' => 'timestamp',
725 'value' => $timestamp ) ) .
726 wfElement( 'input', array(
727 'type' => 'hidden',
728 'name' => 'wpEditToken',
729 'value' => $wgUser->editToken() ) ) .
730 wfElement( 'input', array(
731 'type' => 'submit',
732 'name' => 'preview',
733 'value' => wfMsg( 'showpreview' ) ) ) .
734 wfElement( 'input', array(
735 'name' => 'diff',
736 'type' => 'submit',
737 'value' => wfMsg( 'showdiff' ) ) ) .
738 wfCloseElement( 'form' ) .
739 wfCloseElement( 'div' ) );
740 }
741
742 /**
743 * Build a diff display between this and the previous either deleted
744 * or non-deleted edit.
745 * @param Revision $previousRev
746 * @param Revision $currentRev
747 * @return string HTML
748 */
749 function showDiff( $previousRev, $currentRev ) {
750 global $wgOut, $wgUser;
751
752 $diffEngine = new DifferenceEngine();
753 $diffEngine->showDiffStyle();
754 $wgOut->addHtml(
755 "<div>" .
756 "<table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>" .
757 "<col class='diff-marker' />" .
758 "<col class='diff-content' />" .
759 "<col class='diff-marker' />" .
760 "<col class='diff-content' />" .
761 "<tr>" .
762 "<td colspan='2' width='50%' align='center' class='diff-otitle'>" .
763 $this->diffHeader( $previousRev ) .
764 "</td>" .
765 "<td colspan='2' width='50%' align='center' class='diff-ntitle'>" .
766 $this->diffHeader( $currentRev ) .
767 "</td>" .
768 "</tr>" .
769 $diffEngine->generateDiffBody(
770 $previousRev->getText(), $currentRev->getText() ) .
771 "</table>" .
772 "</div>\n" );
773
774 }
775
776 private function diffHeader( $rev ) {
777 global $wgUser, $wgLang, $wgLang;
778 $sk = $wgUser->getSkin();
779 $isDeleted = !( $rev->getId() && $rev->getTitle() );
780 if( $isDeleted ) {
781 /// @fixme $rev->getTitle() is null for deleted revs...?
782 $targetPage = SpecialPage::getTitleFor( 'Undelete' );
783 $targetQuery = 'target=' .
784 $this->mTargetObj->getPrefixedUrl() .
785 '&timestamp=' .
786 wfTimestamp( TS_MW, $rev->getTimestamp() );
787 } else {
788 /// @fixme getId() may return non-zero for deleted revs...
789 $targetPage = $rev->getTitle();
790 $targetQuery = 'oldid=' . $rev->getId();
791 }
792 return
793 '<div id="mw-diff-otitle1"><strong>' .
794 $sk->makeLinkObj( $targetPage,
795 wfMsgHtml( 'revisionasof',
796 $wgLang->timeanddate( $rev->getTimestamp(), true ) ),
797 $targetQuery ) .
798 ( $isDeleted ? ' ' . wfMsgHtml( 'deletedrev' ) : '' ) .
799 '</strong></div>' .
800 '<div id="mw-diff-otitle2">' .
801 $sk->revUserTools( $rev ) . '<br/>' .
802 '</div>' .
803 '<div id="mw-diff-otitle3">' .
804 $sk->revComment( $rev ) . '<br/>' .
805 '</div>';
806 }
807
808 /**
809 * Show a deleted file version requested by the visitor.
810 */
811 function showFile( $key ) {
812 global $wgOut, $wgRequest;
813 $wgOut->disable();
814
815 # We mustn't allow the output to be Squid cached, otherwise
816 # if an admin previews a deleted image, and it's cached, then
817 # a user without appropriate permissions can toddle off and
818 # nab the image, and Squid will serve it
819 $wgRequest->response()->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
820 $wgRequest->response()->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
821 $wgRequest->response()->header( 'Pragma: no-cache' );
822
823 $store = FileStore::get( 'deleted' );
824 $store->stream( $key );
825 }
826
827 /* private */ function showHistory() {
828 global $wgLang, $wgContLang, $wgUser, $wgOut;
829
830 $sk = $wgUser->getSkin();
831 if ( $this->mAllowed ) {
832 $wgOut->setPagetitle( wfMsg( "undeletepage" ) );
833 } else {
834 $wgOut->setPagetitle( wfMsg( 'viewdeletedpage' ) );
835 }
836
837 $archive = new PageArchive( $this->mTargetObj );
838 /*
839 $text = $archive->getLastRevisionText();
840 if( is_null( $text ) ) {
841 $wgOut->addWikiText( wfMsg( "nohistory" ) );
842 return;
843 }
844 */
845 if ( $this->mAllowed ) {
846 $wgOut->addWikiText( wfMsg( "undeletehistory" ) );
847 } else {
848 $wgOut->addWikiText( wfMsg( "undeletehistorynoadmin" ) );
849 }
850
851 # List all stored revisions
852 $revisions = $archive->listRevisions();
853 $files = $archive->listFiles();
854
855 $haveRevisions = $revisions && $revisions->numRows() > 0;
856 $haveFiles = $files && $files->numRows() > 0;
857
858 # Batch existence check on user and talk pages
859 if( $haveRevisions ) {
860 $batch = new LinkBatch();
861 while( $row = $revisions->fetchObject() ) {
862 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->ar_user_text ) );
863 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->ar_user_text ) );
864 }
865 $batch->execute();
866 $revisions->seek( 0 );
867 }
868 if( $haveFiles ) {
869 $batch = new LinkBatch();
870 while( $row = $files->fetchObject() ) {
871 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->fa_user_text ) );
872 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->fa_user_text ) );
873 }
874 $batch->execute();
875 $files->seek( 0 );
876 }
877
878 if ( $this->mAllowed ) {
879 $titleObj = SpecialPage::getTitleFor( "Undelete" );
880 $action = $titleObj->getLocalURL( "action=submit" );
881 # Start the form here
882 $top = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $action, 'id' => 'undelete' ) );
883 $wgOut->addHtml( $top );
884 }
885
886 # Show relevant lines from the deletion log:
887 $wgOut->addHTML( "<h2>" . htmlspecialchars( LogPage::logName( 'delete' ) ) . "</h2>\n" );
888 $logViewer = new LogViewer(
889 new LogReader(
890 new FauxRequest(
891 array(
892 'page' => $this->mTargetObj->getPrefixedText(),
893 'type' => 'delete'
894 )
895 )
896 ), LogViewer::NO_ACTION_LINK
897 );
898 $logViewer->showList( $wgOut );
899
900 if( $this->mAllowed && ( $haveRevisions || $haveFiles ) ) {
901 # Format the user-visible controls (comment field, submission button)
902 # in a nice little table
903 $align = $wgContLang->isRtl() ? 'left' : 'right';
904 $table =
905 Xml::openElement( 'fieldset' ) .
906 Xml::openElement( 'table' ) .
907 "<tr>
908 <td colspan='2'>" .
909 wfMsgWikiHtml( 'undeleteextrahelp' ) .
910 "</td>
911 </tr>
912 <tr>
913 <td align='$align'>" .
914 Xml::label( wfMsg( 'undeletecomment' ), 'wpComment' ) .
915 "</td>
916 <td>" .
917 Xml::input( 'wpComment', 50, $this->mComment ) .
918 "</td>
919 </tr>
920 <tr>
921 <td>&nbsp;</td>
922 <td>" .
923 Xml::submitButton( wfMsg( 'undeletebtn' ), array( 'name' => 'restore', 'id' => 'mw-undelete-submit' ) ) .
924 Xml::element( 'input', array( 'type' => 'reset', 'value' => wfMsg( 'undeletereset' ), 'id' => 'mw-undelete-reset' ) ) .
925 "</td>
926 </tr>" .
927 Xml::closeElement( 'table' ) .
928 Xml::closeElement( 'fieldset' );
929
930 $wgOut->addHtml( $table );
931 }
932
933 $wgOut->addHTML( "<h2>" . htmlspecialchars( wfMsg( "history" ) ) . "</h2>\n" );
934
935 if( $haveRevisions ) {
936 # The page's stored (deleted) history:
937 $wgOut->addHTML("<ul>");
938 $target = urlencode( $this->mTarget );
939 $remaining = $revisions->numRows();
940 $earliestLiveTime = $this->getEarliestTime( $this->mTargetObj );
941
942 while( $row = $revisions->fetchObject() ) {
943 $remaining--;
944 $ts = wfTimestamp( TS_MW, $row->ar_timestamp );
945 if ( $this->mAllowed ) {
946 $checkBox = Xml::check( "ts$ts" );
947 $pageLink = $sk->makeKnownLinkObj( $titleObj,
948 $wgLang->timeanddate( $ts, true ),
949 "target=$target&timestamp=$ts" );
950 if( ($remaining > 0) ||
951 ($earliestLiveTime && $ts > $earliestLiveTime ) ) {
952 $diffLink = '(' .
953 $sk->makeKnownLinkObj( $titleObj,
954 wfMsgHtml( 'diff' ),
955 "target=$target&timestamp=$ts&diff=prev" ) .
956 ')';
957 } else {
958 // No older revision to diff against
959 $diffLink = '';
960 }
961 } else {
962 $checkBox = '';
963 $pageLink = $wgLang->timeanddate( $ts, true );
964 $diffLink = '';
965 }
966 $userLink = $sk->userLink( $row->ar_user, $row->ar_user_text ) . $sk->userToolLinks( $row->ar_user, $row->ar_user_text );
967 $stxt = '';
968 if (!is_null($size = $row->ar_len)) {
969 if ($size == 0) {
970 $stxt = wfMsgHtml('historyempty');
971 } else {
972 $stxt = wfMsgHtml('historysize', $wgLang->formatNum( $size ) );
973 }
974 }
975 $comment = $sk->commentBlock( $row->ar_comment );
976 $wgOut->addHTML( "<li>$checkBox $pageLink $diffLink . . $userLink $stxt $comment</li>\n" );
977
978 }
979 $revisions->free();
980 $wgOut->addHTML("</ul>");
981 } else {
982 $wgOut->addWikiText( wfMsg( "nohistory" ) );
983 }
984
985 if( $haveFiles ) {
986 $wgOut->addHtml( "<h2>" . wfMsgHtml( 'filehist' ) . "</h2>\n" );
987 $wgOut->addHtml( "<ul>" );
988 while( $row = $files->fetchObject() ) {
989 $ts = wfTimestamp( TS_MW, $row->fa_timestamp );
990 if ( $this->mAllowed && $row->fa_storage_key ) {
991 $checkBox = Xml::check( "fileid" . $row->fa_id );
992 $key = urlencode( $row->fa_storage_key );
993 $target = urlencode( $this->mTarget );
994 $pageLink = $sk->makeKnownLinkObj( $titleObj,
995 $wgLang->timeanddate( $ts, true ),
996 "target=$target&file=$key" );
997 } else {
998 $checkBox = '';
999 $pageLink = $wgLang->timeanddate( $ts, true );
1000 }
1001 $userLink = $sk->userLink( $row->fa_user, $row->fa_user_text ) . $sk->userToolLinks( $row->fa_user, $row->fa_user_text );
1002 $data =
1003 wfMsgHtml( 'widthheight',
1004 $wgLang->formatNum( $row->fa_width ),
1005 $wgLang->formatNum( $row->fa_height ) ) .
1006 ' (' .
1007 wfMsgHtml( 'nbytes', $wgLang->formatNum( $row->fa_size ) ) .
1008 ')';
1009 $comment = $sk->commentBlock( $row->fa_description );
1010 $wgOut->addHTML( "<li>$checkBox $pageLink . . $userLink $data $comment</li>\n" );
1011 }
1012 $files->free();
1013 $wgOut->addHTML( "</ul>" );
1014 }
1015
1016 if ( $this->mAllowed ) {
1017 # Slip in the hidden controls here
1018 $misc = Xml::hidden( 'target', $this->mTarget );
1019 $misc .= Xml::hidden( 'wpEditToken', $wgUser->editToken() );
1020 $misc .= Xml::closeElement( 'form' );
1021 $wgOut->addHtml( $misc );
1022 }
1023
1024 return true;
1025 }
1026
1027 private function getEarliestTime( $title ) {
1028 $dbr = wfGetDB( DB_SLAVE );
1029 if( $title->exists() ) {
1030 $min = $dbr->selectField( 'revision',
1031 'MIN(rev_timestamp)',
1032 array( 'rev_page' => $title->getArticleId() ),
1033 __METHOD__ );
1034 return wfTimestampOrNull( TS_MW, $min );
1035 }
1036 return null;
1037 }
1038
1039 function undelete() {
1040 global $wgOut, $wgUser;
1041 if( !is_null( $this->mTargetObj ) ) {
1042 $archive = new PageArchive( $this->mTargetObj );
1043
1044 $ok = $archive->undelete(
1045 $this->mTargetTimestamp,
1046 $this->mComment,
1047 $this->mFileVersions );
1048
1049 if( is_array($ok) ) {
1050 $skin = $wgUser->getSkin();
1051 $link = $skin->makeKnownLinkObj( $this->mTargetObj );
1052 $wgOut->addHtml( wfMsgWikiHtml( 'undeletedpage', $link ) );
1053 } else {
1054 $wgOut->showFatalError( wfMsg( "cannotundelete" ) );
1055 }
1056
1057 // Show file deletion warnings and errors
1058 $status = $archive->getFileStatus();
1059 if ( $status && !$status->isGood() ) {
1060 $wgOut->addWikiText( $status->getWikiText( 'undelete-error-short', 'undelete-error-long' ) );
1061 }
1062 } else {
1063 $wgOut->showFatalError( wfMsg( "cannotundelete" ) );
1064 }
1065 return false;
1066 }
1067 }