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