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