c88c2f1154f0d927df2d11ebeb329a77851ff45f
[lhc/web/wiklou.git] / includes / specials / SpecialUndelete.php
1 <?php
2 /**
3 * Implements Special:Undelete
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 */
23
24 /**
25 * Used to show archived pages and eventually restore them.
26 *
27 * @ingroup SpecialPage
28 */
29 class PageArchive {
30 /** @var Title */
31 protected $title;
32
33 /** @var Status */
34 protected $fileStatus;
35
36 /** @var Status */
37 protected $revisionStatus;
38
39 /** @var Config */
40 protected $config;
41
42 function __construct( $title, Config $config = null ) {
43 if ( is_null( $title ) ) {
44 throw new MWException( __METHOD__ . ' given a null title.' );
45 }
46 $this->title = $title;
47 if ( $config === null ) {
48 wfDebug( __METHOD__ . ' did not have a Config object passed to it' );
49 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
50 }
51 $this->config = $config;
52 }
53
54 /**
55 * List all deleted pages recorded in the archive table. Returns result
56 * wrapper with (ar_namespace, ar_title, count) fields, ordered by page
57 * namespace/title.
58 *
59 * @return ResultWrapper
60 */
61 public static function listAllPages() {
62 $dbr = wfGetDB( DB_SLAVE );
63
64 return self::listPages( $dbr, '' );
65 }
66
67 /**
68 * List deleted pages recorded in the archive table matching the
69 * given title prefix.
70 * Returns result wrapper with (ar_namespace, ar_title, count) fields.
71 *
72 * @param string $prefix Title prefix
73 * @return ResultWrapper
74 */
75 public static function listPagesByPrefix( $prefix ) {
76 $dbr = wfGetDB( DB_SLAVE );
77
78 $title = Title::newFromText( $prefix );
79 if ( $title ) {
80 $ns = $title->getNamespace();
81 $prefix = $title->getDBkey();
82 } else {
83 // Prolly won't work too good
84 // @todo handle bare namespace names cleanly?
85 $ns = 0;
86 }
87
88 $conds = array(
89 'ar_namespace' => $ns,
90 'ar_title' . $dbr->buildLike( $prefix, $dbr->anyString() ),
91 );
92
93 return self::listPages( $dbr, $conds );
94 }
95
96 /**
97 * @param IDatabase $dbr
98 * @param string|array $condition
99 * @return bool|ResultWrapper
100 */
101 protected static function listPages( $dbr, $condition ) {
102 return $dbr->select(
103 array( 'archive' ),
104 array(
105 'ar_namespace',
106 'ar_title',
107 'count' => 'COUNT(*)'
108 ),
109 $condition,
110 __METHOD__,
111 array(
112 'GROUP BY' => array( 'ar_namespace', 'ar_title' ),
113 'ORDER BY' => array( 'ar_namespace', 'ar_title' ),
114 'LIMIT' => 100,
115 )
116 );
117 }
118
119 /**
120 * List the revisions of the given page. Returns result wrapper with
121 * (ar_minor_edit, ar_timestamp, ar_user, ar_user_text, ar_comment) fields.
122 *
123 * @return ResultWrapper
124 */
125 function listRevisions() {
126 $dbr = wfGetDB( DB_SLAVE );
127
128 $tables = array( 'archive' );
129
130 $fields = array(
131 'ar_minor_edit', 'ar_timestamp', 'ar_user', 'ar_user_text',
132 'ar_comment', 'ar_len', 'ar_deleted', 'ar_rev_id', 'ar_sha1',
133 );
134
135 if ( $this->config->get( 'ContentHandlerUseDB' ) ) {
136 $fields[] = 'ar_content_format';
137 $fields[] = 'ar_content_model';
138 }
139
140 $conds = array( 'ar_namespace' => $this->title->getNamespace(),
141 'ar_title' => $this->title->getDBkey() );
142
143 $options = array( 'ORDER BY' => 'ar_timestamp DESC' );
144
145 $join_conds = array();
146
147 ChangeTags::modifyDisplayQuery(
148 $tables,
149 $fields,
150 $conds,
151 $join_conds,
152 $options
153 );
154
155 return $dbr->select( $tables,
156 $fields,
157 $conds,
158 __METHOD__,
159 $options,
160 $join_conds
161 );
162 }
163
164 /**
165 * List the deleted file revisions for this page, if it's a file page.
166 * Returns a result wrapper with various filearchive fields, or null
167 * if not a file page.
168 *
169 * @return ResultWrapper
170 * @todo Does this belong in Image for fuller encapsulation?
171 */
172 function listFiles() {
173 if ( $this->title->getNamespace() != NS_FILE ) {
174 return null;
175 }
176
177 $dbr = wfGetDB( DB_SLAVE );
178 return $dbr->select(
179 'filearchive',
180 ArchivedFile::selectFields(),
181 array( 'fa_name' => $this->title->getDBkey() ),
182 __METHOD__,
183 array( 'ORDER BY' => 'fa_timestamp DESC' )
184 );
185 }
186
187 /**
188 * Return a Revision object containing data for the deleted revision.
189 * Note that the result *may* or *may not* have a null page ID.
190 *
191 * @param string $timestamp
192 * @return Revision|null
193 */
194 function getRevision( $timestamp ) {
195 $dbr = wfGetDB( DB_SLAVE );
196
197 $fields = array(
198 'ar_rev_id',
199 'ar_text',
200 'ar_comment',
201 'ar_user',
202 'ar_user_text',
203 'ar_timestamp',
204 'ar_minor_edit',
205 'ar_flags',
206 'ar_text_id',
207 'ar_deleted',
208 'ar_len',
209 'ar_sha1',
210 );
211
212 if ( $this->config->get( 'ContentHandlerUseDB' ) ) {
213 $fields[] = 'ar_content_format';
214 $fields[] = 'ar_content_model';
215 }
216
217 $row = $dbr->selectRow( 'archive',
218 $fields,
219 array( 'ar_namespace' => $this->title->getNamespace(),
220 'ar_title' => $this->title->getDBkey(),
221 'ar_timestamp' => $dbr->timestamp( $timestamp ) ),
222 __METHOD__ );
223
224 if ( $row ) {
225 return Revision::newFromArchiveRow( $row, array( 'title' => $this->title ) );
226 }
227
228 return null;
229 }
230
231 /**
232 * Return the most-previous revision, either live or deleted, against
233 * the deleted revision given by timestamp.
234 *
235 * May produce unexpected results in case of history merges or other
236 * unusual time issues.
237 *
238 * @param string $timestamp
239 * @return Revision|null Null when there is no previous revision
240 */
241 function getPreviousRevision( $timestamp ) {
242 $dbr = wfGetDB( DB_SLAVE );
243
244 // Check the previous deleted revision...
245 $row = $dbr->selectRow( 'archive',
246 'ar_timestamp',
247 array( 'ar_namespace' => $this->title->getNamespace(),
248 'ar_title' => $this->title->getDBkey(),
249 'ar_timestamp < ' .
250 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ),
251 __METHOD__,
252 array(
253 'ORDER BY' => 'ar_timestamp DESC',
254 'LIMIT' => 1 ) );
255 $prevDeleted = $row ? wfTimestamp( TS_MW, $row->ar_timestamp ) : false;
256
257 $row = $dbr->selectRow( array( 'page', 'revision' ),
258 array( 'rev_id', 'rev_timestamp' ),
259 array(
260 'page_namespace' => $this->title->getNamespace(),
261 'page_title' => $this->title->getDBkey(),
262 'page_id = rev_page',
263 'rev_timestamp < ' .
264 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ),
265 __METHOD__,
266 array(
267 'ORDER BY' => 'rev_timestamp DESC',
268 'LIMIT' => 1 ) );
269 $prevLive = $row ? wfTimestamp( TS_MW, $row->rev_timestamp ) : false;
270 $prevLiveId = $row ? intval( $row->rev_id ) : null;
271
272 if ( $prevLive && $prevLive > $prevDeleted ) {
273 // Most prior revision was live
274 return Revision::newFromId( $prevLiveId );
275 } elseif ( $prevDeleted ) {
276 // Most prior revision was deleted
277 return $this->getRevision( $prevDeleted );
278 }
279
280 // No prior revision on this page.
281 return null;
282 }
283
284 /**
285 * Get the text from an archive row containing ar_text, ar_flags and ar_text_id
286 *
287 * @param object $row Database row
288 * @return string
289 */
290 function getTextFromRow( $row ) {
291 if ( is_null( $row->ar_text_id ) ) {
292 // An old row from MediaWiki 1.4 or previous.
293 // Text is embedded in this row in classic compression format.
294 return Revision::getRevisionText( $row, 'ar_' );
295 }
296
297 // New-style: keyed to the text storage backend.
298 $dbr = wfGetDB( DB_SLAVE );
299 $text = $dbr->selectRow( 'text',
300 array( 'old_text', 'old_flags' ),
301 array( 'old_id' => $row->ar_text_id ),
302 __METHOD__ );
303
304 return Revision::getRevisionText( $text );
305 }
306
307 /**
308 * Fetch (and decompress if necessary) the stored text of the most
309 * recently edited deleted revision of the page.
310 *
311 * If there are no archived revisions for the page, returns NULL.
312 *
313 * @return string|null
314 */
315 function getLastRevisionText() {
316 $dbr = wfGetDB( DB_SLAVE );
317 $row = $dbr->selectRow( 'archive',
318 array( 'ar_text', 'ar_flags', 'ar_text_id' ),
319 array( 'ar_namespace' => $this->title->getNamespace(),
320 'ar_title' => $this->title->getDBkey() ),
321 __METHOD__,
322 array( 'ORDER BY' => 'ar_timestamp DESC' ) );
323
324 if ( $row ) {
325 return $this->getTextFromRow( $row );
326 }
327
328 return null;
329 }
330
331 /**
332 * Quick check if any archived revisions are present for the page.
333 *
334 * @return bool
335 */
336 function isDeleted() {
337 $dbr = wfGetDB( DB_SLAVE );
338 $n = $dbr->selectField( 'archive', 'COUNT(ar_title)',
339 array( 'ar_namespace' => $this->title->getNamespace(),
340 'ar_title' => $this->title->getDBkey() ),
341 __METHOD__
342 );
343
344 return ( $n > 0 );
345 }
346
347 /**
348 * Restore the given (or all) text and file revisions for the page.
349 * Once restored, the items will be removed from the archive tables.
350 * The deletion log will be updated with an undeletion notice.
351 *
352 * @param array $timestamps Pass an empty array to restore all revisions,
353 * otherwise list the ones to undelete.
354 * @param string $comment
355 * @param array $fileVersions
356 * @param bool $unsuppress
357 * @param User $user User performing the action, or null to use $wgUser
358 * @return array(number of file revisions restored, number of image revisions
359 * restored, log message) on success, false on failure.
360 */
361 function undelete( $timestamps, $comment = '', $fileVersions = array(),
362 $unsuppress = false, User $user = null
363 ) {
364 // If both the set of text revisions and file revisions are empty,
365 // restore everything. Otherwise, just restore the requested items.
366 $restoreAll = empty( $timestamps ) && empty( $fileVersions );
367
368 $restoreText = $restoreAll || !empty( $timestamps );
369 $restoreFiles = $restoreAll || !empty( $fileVersions );
370
371 if ( $restoreFiles && $this->title->getNamespace() == NS_FILE ) {
372 $img = wfLocalFile( $this->title );
373 $this->fileStatus = $img->restore( $fileVersions, $unsuppress );
374 if ( !$this->fileStatus->isOK() ) {
375 return false;
376 }
377 $filesRestored = $this->fileStatus->successCount;
378 } else {
379 $filesRestored = 0;
380 }
381
382 if ( $restoreText ) {
383 $this->revisionStatus = $this->undeleteRevisions( $timestamps, $unsuppress, $comment );
384 if ( !$this->revisionStatus->isOK() ) {
385 return false;
386 }
387
388 $textRestored = $this->revisionStatus->getValue();
389 } else {
390 $textRestored = 0;
391 }
392
393 // Touch the log!
394
395 if ( $textRestored && $filesRestored ) {
396 $reason = wfMessage( 'undeletedrevisions-files' )
397 ->numParams( $textRestored, $filesRestored )->inContentLanguage()->text();
398 } elseif ( $textRestored ) {
399 $reason = wfMessage( 'undeletedrevisions' )->numParams( $textRestored )
400 ->inContentLanguage()->text();
401 } elseif ( $filesRestored ) {
402 $reason = wfMessage( 'undeletedfiles' )->numParams( $filesRestored )
403 ->inContentLanguage()->text();
404 } else {
405 wfDebug( "Undelete: nothing undeleted...\n" );
406
407 return false;
408 }
409
410 if ( trim( $comment ) != '' ) {
411 $reason .= wfMessage( 'colon-separator' )->inContentLanguage()->text() . $comment;
412 }
413
414 if ( $user === null ) {
415 global $wgUser;
416 $user = $wgUser;
417 }
418
419 $logEntry = new ManualLogEntry( 'delete', 'restore' );
420 $logEntry->setPerformer( $user );
421 $logEntry->setTarget( $this->title );
422 $logEntry->setComment( $reason );
423
424 Hooks::run( 'ArticleUndeleteLogEntry', array( $this, &$logEntry, $user ) );
425
426 $logid = $logEntry->insert();
427 $logEntry->publish( $logid );
428
429 return array( $textRestored, $filesRestored, $reason );
430 }
431
432 /**
433 * This is the meaty bit -- restores archived revisions of the given page
434 * to the cur/old tables. If the page currently exists, all revisions will
435 * be stuffed into old, otherwise the most recent will go into cur.
436 *
437 * @param array $timestamps Pass an empty array to restore all revisions,
438 * otherwise list the ones to undelete.
439 * @param bool $unsuppress Remove all ar_deleted/fa_deleted restrictions of seletected revs
440 * @param string $comment
441 * @throws ReadOnlyError
442 * @return Status Status object containing the number of revisions restored on success
443 */
444 private function undeleteRevisions( $timestamps, $unsuppress = false, $comment = '' ) {
445 if ( wfReadOnly() ) {
446 throw new ReadOnlyError();
447 }
448
449 $restoreAll = empty( $timestamps );
450 $dbw = wfGetDB( DB_MASTER );
451
452 # Does this page already exist? We'll have to update it...
453 $article = WikiPage::factory( $this->title );
454 # Load latest data for the current page (bug 31179)
455 $article->loadPageData( 'fromdbmaster' );
456 $oldcountable = $article->isCountable();
457
458 $page = $dbw->selectRow( 'page',
459 array( 'page_id', 'page_latest' ),
460 array( 'page_namespace' => $this->title->getNamespace(),
461 'page_title' => $this->title->getDBkey() ),
462 __METHOD__,
463 array( 'FOR UPDATE' ) // lock page
464 );
465
466 if ( $page ) {
467 $makepage = false;
468 # Page already exists. Import the history, and if necessary
469 # we'll update the latest revision field in the record.
470
471 $previousRevId = $page->page_latest;
472
473 # Get the time span of this page
474 $previousTimestamp = $dbw->selectField( 'revision', 'rev_timestamp',
475 array( 'rev_id' => $previousRevId ),
476 __METHOD__ );
477
478 if ( $previousTimestamp === false ) {
479 wfDebug( __METHOD__ . ": existing page refers to a page_latest that does not exist\n" );
480
481 $status = Status::newGood( 0 );
482 $status->warning( 'undeleterevision-missing' );
483
484 return $status;
485 }
486 } else {
487 # Have to create a new article...
488 $makepage = true;
489 $previousRevId = 0;
490 $previousTimestamp = 0;
491 }
492
493 $oldWhere = array(
494 'ar_namespace' => $this->title->getNamespace(),
495 'ar_title' => $this->title->getDBkey(),
496 );
497 if ( !$restoreAll ) {
498 $oldWhere['ar_timestamp'] = array_map( array( &$dbw, 'timestamp' ), $timestamps );
499 }
500
501 $fields = array(
502 'ar_rev_id',
503 'ar_text',
504 'ar_comment',
505 'ar_user',
506 'ar_user_text',
507 'ar_timestamp',
508 'ar_minor_edit',
509 'ar_flags',
510 'ar_text_id',
511 'ar_deleted',
512 'ar_page_id',
513 'ar_len',
514 'ar_sha1'
515 );
516
517 if ( $this->config->get( 'ContentHandlerUseDB' ) ) {
518 $fields[] = 'ar_content_format';
519 $fields[] = 'ar_content_model';
520 }
521
522 /**
523 * Select each archived revision...
524 */
525 $result = $dbw->select( 'archive',
526 $fields,
527 $oldWhere,
528 __METHOD__,
529 /* options */ array( 'ORDER BY' => 'ar_timestamp' )
530 );
531
532 $rev_count = $result->numRows();
533 if ( !$rev_count ) {
534 wfDebug( __METHOD__ . ": no revisions to restore\n" );
535
536 $status = Status::newGood( 0 );
537 $status->warning( "undelete-no-results" );
538
539 return $status;
540 }
541
542 $result->seek( $rev_count - 1 ); // move to last
543 $row = $result->fetchObject(); // get newest archived rev
544 $oldPageId = (int)$row->ar_page_id; // pass this to ArticleUndelete hook
545 $result->seek( 0 ); // move back
546
547 // grab the content to check consistency with global state before restoring the page.
548 $revision = Revision::newFromArchiveRow( $row,
549 array(
550 'title' => $article->getTitle(), // used to derive default content model
551 )
552 );
553 $user = User::newFromName( $revision->getUserText( Revision::RAW ), false );
554 $content = $revision->getContent( Revision::RAW );
555
556 //NOTE: article ID may not be known yet. prepareSave() should not modify the database.
557 $status = $content->prepareSave( $article, 0, -1, $user );
558
559 if ( !$status->isOK() ) {
560 return $status;
561 }
562
563 if ( $makepage ) {
564 // Check the state of the newest to-be version...
565 if ( !$unsuppress && ( $row->ar_deleted & Revision::DELETED_TEXT ) ) {
566 return Status::newFatal( "undeleterevdel" );
567 }
568 // Safe to insert now...
569 $newid = $article->insertOn( $dbw );
570 $pageId = $newid;
571 } else {
572 // Check if a deleted revision will become the current revision...
573 if ( $row->ar_timestamp > $previousTimestamp ) {
574 // Check the state of the newest to-be version...
575 if ( !$unsuppress && ( $row->ar_deleted & Revision::DELETED_TEXT ) ) {
576 return Status::newFatal( "undeleterevdel" );
577 }
578 }
579
580 $newid = false;
581 $pageId = $article->getId();
582 }
583
584 $revision = null;
585 $restored = 0;
586
587 foreach ( $result as $row ) {
588 // Check for key dupes due to shitty archive integrity.
589 if ( $row->ar_rev_id ) {
590 $exists = $dbw->selectField( 'revision', '1',
591 array( 'rev_id' => $row->ar_rev_id ), __METHOD__ );
592 if ( $exists ) {
593 continue; // don't throw DB errors
594 }
595 }
596 // Insert one revision at a time...maintaining deletion status
597 // unless we are specifically removing all restrictions...
598 $revision = Revision::newFromArchiveRow( $row,
599 array(
600 'page' => $pageId,
601 'title' => $this->title,
602 'deleted' => $unsuppress ? 0 : $row->ar_deleted
603 ) );
604
605 $revision->insertOn( $dbw );
606 $restored++;
607
608 Hooks::run( 'ArticleRevisionUndeleted', array( &$this->title, $revision, $row->ar_page_id ) );
609 }
610 # Now that it's safely stored, take it out of the archive
611 $dbw->delete( 'archive',
612 $oldWhere,
613 __METHOD__ );
614
615 // Was anything restored at all?
616 if ( $restored == 0 ) {
617 return Status::newGood( 0 );
618 }
619
620 $created = (bool)$newid;
621
622 // Attach the latest revision to the page...
623 $wasnew = $article->updateIfNewerOn( $dbw, $revision, $previousRevId );
624 if ( $created || $wasnew ) {
625 // Update site stats, link tables, etc
626 $user = User::newFromName( $revision->getUserText( Revision::RAW ), false );
627 $article->doEditUpdates(
628 $revision,
629 $user,
630 array( 'created' => $created, 'oldcountable' => $oldcountable )
631 );
632 }
633
634 Hooks::run( 'ArticleUndelete', array( &$this->title, $created, $comment, $oldPageId ) );
635
636 if ( $this->title->getNamespace() == NS_FILE ) {
637 $update = new HTMLCacheUpdate( $this->title, 'imagelinks' );
638 $update->doUpdate();
639 }
640
641 return Status::newGood( $restored );
642 }
643
644 /**
645 * @return Status
646 */
647 function getFileStatus() {
648 return $this->fileStatus;
649 }
650
651 /**
652 * @return Status
653 */
654 function getRevisionStatus() {
655 return $this->revisionStatus;
656 }
657 }
658
659 /**
660 * Special page allowing users with the appropriate permissions to view
661 * and restore deleted content.
662 *
663 * @ingroup SpecialPage
664 */
665 class SpecialUndelete extends SpecialPage {
666 private $mAction;
667 private $mTarget;
668 private $mTimestamp;
669 private $mRestore;
670 private $mInvert;
671 private $mFilename;
672 private $mTargetTimestamp;
673 private $mAllowed;
674 private $mCanView;
675 private $mComment;
676 private $mToken;
677
678 /** @var Title */
679 private $mTargetObj;
680
681 function __construct() {
682 parent::__construct( 'Undelete', 'deletedhistory' );
683 }
684
685 function loadRequest( $par ) {
686 $request = $this->getRequest();
687 $user = $this->getUser();
688
689 $this->mAction = $request->getVal( 'action' );
690 if ( $par !== null && $par !== '' ) {
691 $this->mTarget = $par;
692 } else {
693 $this->mTarget = $request->getVal( 'target' );
694 }
695
696 $this->mTargetObj = null;
697
698 if ( $this->mTarget !== null && $this->mTarget !== '' ) {
699 $this->mTargetObj = Title::newFromURL( $this->mTarget );
700 }
701
702 $this->mSearchPrefix = $request->getText( 'prefix' );
703 $time = $request->getVal( 'timestamp' );
704 $this->mTimestamp = $time ? wfTimestamp( TS_MW, $time ) : '';
705 $this->mFilename = $request->getVal( 'file' );
706
707 $posted = $request->wasPosted() &&
708 $user->matchEditToken( $request->getVal( 'wpEditToken' ) );
709 $this->mRestore = $request->getCheck( 'restore' ) && $posted;
710 $this->mInvert = $request->getCheck( 'invert' ) && $posted;
711 $this->mPreview = $request->getCheck( 'preview' ) && $posted;
712 $this->mDiff = $request->getCheck( 'diff' );
713 $this->mDiffOnly = $request->getBool( 'diffonly', $this->getUser()->getOption( 'diffonly' ) );
714 $this->mComment = $request->getText( 'wpComment' );
715 $this->mUnsuppress = $request->getVal( 'wpUnsuppress' ) && $user->isAllowed( 'suppressrevision' );
716 $this->mToken = $request->getVal( 'token' );
717
718 if ( $this->isAllowed( 'undelete' ) && !$user->isBlocked() ) {
719 $this->mAllowed = true; // user can restore
720 $this->mCanView = true; // user can view content
721 } elseif ( $this->isAllowed( 'deletedtext' ) ) {
722 $this->mAllowed = false; // user cannot restore
723 $this->mCanView = true; // user can view content
724 $this->mRestore = false;
725 } else { // user can only view the list of revisions
726 $this->mAllowed = false;
727 $this->mCanView = false;
728 $this->mTimestamp = '';
729 $this->mRestore = false;
730 }
731
732 if ( $this->mRestore || $this->mInvert ) {
733 $timestamps = array();
734 $this->mFileVersions = array();
735 foreach ( $request->getValues() as $key => $val ) {
736 $matches = array();
737 if ( preg_match( '/^ts(\d{14})$/', $key, $matches ) ) {
738 array_push( $timestamps, $matches[1] );
739 }
740
741 if ( preg_match( '/^fileid(\d+)$/', $key, $matches ) ) {
742 $this->mFileVersions[] = intval( $matches[1] );
743 }
744 }
745 rsort( $timestamps );
746 $this->mTargetTimestamp = $timestamps;
747 }
748 }
749
750 /**
751 * Checks whether a user is allowed the permission for the
752 * specific title if one is set.
753 *
754 * @param string $permission
755 * @param User $user
756 * @return bool
757 */
758 private function isAllowed( $permission, User $user = null ) {
759 $user = $user ? : $this->getUser();
760 if ( $this->mTargetObj !== null ) {
761 return $this->mTargetObj->userCan( $permission, $user );
762 } else {
763 return $user->isAllowed( $permission );
764 }
765 }
766
767 function userCanExecute( User $user ) {
768 return $this->isAllowed( $this->mRestriction, $user );
769 }
770
771 function execute( $par ) {
772 $user = $this->getUser();
773
774 $this->setHeaders();
775 $this->outputHeader();
776
777 $this->loadRequest( $par );
778 $this->checkPermissions(); // Needs to be after mTargetObj is set
779
780 $out = $this->getOutput();
781
782 if ( is_null( $this->mTargetObj ) ) {
783 $out->addWikiMsg( 'undelete-header' );
784
785 # Not all users can just browse every deleted page from the list
786 if ( $user->isAllowed( 'browsearchive' ) ) {
787 $this->showSearchForm();
788 }
789
790 return;
791 }
792
793 $out->addHelpLink( 'Help:Undelete' );
794 if ( $this->mAllowed ) {
795 $out->setPageTitle( $this->msg( 'undeletepage' ) );
796 } else {
797 $out->setPageTitle( $this->msg( 'viewdeletedpage' ) );
798 }
799
800 $this->getSkin()->setRelevantTitle( $this->mTargetObj );
801
802 if ( $this->mTimestamp !== '' ) {
803 $this->showRevision( $this->mTimestamp );
804 } elseif ( $this->mFilename !== null && $this->mTargetObj->inNamespace( NS_FILE ) ) {
805 $file = new ArchivedFile( $this->mTargetObj, '', $this->mFilename );
806 // Check if user is allowed to see this file
807 if ( !$file->exists() ) {
808 $out->addWikiMsg( 'filedelete-nofile', $this->mFilename );
809 } elseif ( !$file->userCan( File::DELETED_FILE, $user ) ) {
810 if ( $file->isDeleted( File::DELETED_RESTRICTED ) ) {
811 throw new PermissionsError( 'suppressrevision' );
812 } else {
813 throw new PermissionsError( 'deletedtext' );
814 }
815 } elseif ( !$user->matchEditToken( $this->mToken, $this->mFilename ) ) {
816 $this->showFileConfirmationForm( $this->mFilename );
817 } else {
818 $this->showFile( $this->mFilename );
819 }
820 } elseif ( $this->mRestore && $this->mAction == 'submit' ) {
821 $this->undelete();
822 } else {
823 $this->showHistory();
824 }
825 }
826
827 function showSearchForm() {
828 $out = $this->getOutput();
829 $out->setPageTitle( $this->msg( 'undelete-search-title' ) );
830 $out->addHTML(
831 Xml::openElement( 'form', array( 'method' => 'get', 'action' => wfScript() ) ) .
832 Xml::fieldset( $this->msg( 'undelete-search-box' )->text() ) .
833 Html::hidden( 'title', $this->getPageTitle()->getPrefixedDBkey() ) .
834 Html::rawElement(
835 'label',
836 array( 'for' => 'prefix' ),
837 $this->msg( 'undelete-search-prefix' )->parse()
838 ) .
839 Xml::input(
840 'prefix',
841 20,
842 $this->mSearchPrefix,
843 array( 'id' => 'prefix', 'autofocus' => true )
844 ) . ' ' .
845 Xml::submitButton( $this->msg( 'undelete-search-submit' )->text() ) .
846 Xml::closeElement( 'fieldset' ) .
847 Xml::closeElement( 'form' )
848 );
849
850 # List undeletable articles
851 if ( $this->mSearchPrefix ) {
852 $result = PageArchive::listPagesByPrefix( $this->mSearchPrefix );
853 $this->showList( $result );
854 }
855 }
856
857 /**
858 * Generic list of deleted pages
859 *
860 * @param ResultWrapper $result
861 * @return bool
862 */
863 private function showList( $result ) {
864 $out = $this->getOutput();
865
866 if ( $result->numRows() == 0 ) {
867 $out->addWikiMsg( 'undelete-no-results' );
868
869 return false;
870 }
871
872 $out->addWikiMsg( 'undeletepagetext', $this->getLanguage()->formatNum( $result->numRows() ) );
873
874 $undelete = $this->getPageTitle();
875 $out->addHTML( "<ul>\n" );
876 foreach ( $result as $row ) {
877 $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
878 if ( $title !== null ) {
879 $item = Linker::linkKnown(
880 $undelete,
881 htmlspecialchars( $title->getPrefixedText() ),
882 array(),
883 array( 'target' => $title->getPrefixedText() )
884 );
885 } else {
886 // The title is no longer valid, show as text
887 $item = Html::element(
888 'span',
889 array( 'class' => 'mw-invalidtitle' ),
890 Linker::getInvalidTitleDescription(
891 $this->getContext(),
892 $row->ar_namespace,
893 $row->ar_title
894 )
895 );
896 }
897 $revs = $this->msg( 'undeleterevisions' )->numParams( $row->count )->parse();
898 $out->addHTML( "<li>{$item} ({$revs})</li>\n" );
899 }
900 $result->free();
901 $out->addHTML( "</ul>\n" );
902
903 return true;
904 }
905
906 private function showRevision( $timestamp ) {
907 if ( !preg_match( '/[0-9]{14}/', $timestamp ) ) {
908 return;
909 }
910
911 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
912 if ( !Hooks::run( 'UndeleteForm::showRevision', array( &$archive, $this->mTargetObj ) ) ) {
913 return;
914 }
915 $rev = $archive->getRevision( $timestamp );
916
917 $out = $this->getOutput();
918 $user = $this->getUser();
919
920 if ( !$rev ) {
921 $out->addWikiMsg( 'undeleterevision-missing' );
922
923 return;
924 }
925
926 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
927 if ( !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
928 $out->wrapWikiMsg(
929 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
930 $rev->isDeleted( Revision::DELETED_RESTRICTED ) ?
931 'rev-suppressed-text-permission' : 'rev-deleted-text-permission'
932 );
933
934 return;
935 }
936
937 $out->wrapWikiMsg(
938 "<div class='mw-warning plainlinks'>\n$1\n</div>\n",
939 $rev->isDeleted( Revision::DELETED_RESTRICTED ) ?
940 'rev-suppressed-text-view' : 'rev-deleted-text-view'
941 );
942 $out->addHTML( '<br />' );
943 // and we are allowed to see...
944 }
945
946 if ( $this->mDiff ) {
947 $previousRev = $archive->getPreviousRevision( $timestamp );
948 if ( $previousRev ) {
949 $this->showDiff( $previousRev, $rev );
950 if ( $this->mDiffOnly ) {
951 return;
952 }
953
954 $out->addHTML( '<hr />' );
955 } else {
956 $out->addWikiMsg( 'undelete-nodiff' );
957 }
958 }
959
960 $link = Linker::linkKnown(
961 $this->getPageTitle( $this->mTargetObj->getPrefixedDBkey() ),
962 htmlspecialchars( $this->mTargetObj->getPrefixedText() )
963 );
964
965 $lang = $this->getLanguage();
966
967 // date and time are separate parameters to facilitate localisation.
968 // $time is kept for backward compat reasons.
969 $time = $lang->userTimeAndDate( $timestamp, $user );
970 $d = $lang->userDate( $timestamp, $user );
971 $t = $lang->userTime( $timestamp, $user );
972 $userLink = Linker::revUserTools( $rev );
973
974 $content = $rev->getContent( Revision::FOR_THIS_USER, $user );
975
976 $isText = ( $content instanceof TextContent );
977
978 if ( $this->mPreview || $isText ) {
979 $openDiv = '<div id="mw-undelete-revision" class="mw-warning">';
980 } else {
981 $openDiv = '<div id="mw-undelete-revision">';
982 }
983 $out->addHTML( $openDiv );
984
985 // Revision delete links
986 if ( !$this->mDiff ) {
987 $revdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
988 if ( $revdel ) {
989 $out->addHTML( "$revdel " );
990 }
991 }
992
993 $out->addHTML( $this->msg( 'undelete-revision' )->rawParams( $link )->params(
994 $time )->rawParams( $userLink )->params( $d, $t )->parse() . '</div>' );
995
996 if ( !Hooks::run( 'UndeleteShowRevision', array( $this->mTargetObj, $rev ) ) ) {
997 return;
998 }
999
1000 if ( $this->mPreview || !$isText ) {
1001 // NOTE: non-text content has no source view, so always use rendered preview
1002
1003 // Hide [edit]s
1004 $popts = $out->parserOptions();
1005 $popts->setEditSection( false );
1006
1007 $pout = $content->getParserOutput( $this->mTargetObj, $rev->getId(), $popts, true );
1008 $out->addParserOutput( $pout );
1009 }
1010
1011 if ( $isText ) {
1012 // source view for textual content
1013 $sourceView = Xml::element(
1014 'textarea',
1015 array(
1016 'readonly' => 'readonly',
1017 'cols' => $user->getIntOption( 'cols' ),
1018 'rows' => $user->getIntOption( 'rows' )
1019 ),
1020 $content->getNativeData() . "\n"
1021 );
1022
1023 $previewButton = Xml::element( 'input', array(
1024 'type' => 'submit',
1025 'name' => 'preview',
1026 'value' => $this->msg( 'showpreview' )->text()
1027 ) );
1028 } else {
1029 $sourceView = '';
1030 $previewButton = '';
1031 }
1032
1033 $diffButton = Xml::element( 'input', array(
1034 'name' => 'diff',
1035 'type' => 'submit',
1036 'value' => $this->msg( 'showdiff' )->text() ) );
1037
1038 $out->addHTML(
1039 $sourceView .
1040 Xml::openElement( 'div', array(
1041 'style' => 'clear: both' ) ) .
1042 Xml::openElement( 'form', array(
1043 'method' => 'post',
1044 'action' => $this->getPageTitle()->getLocalURL( array( 'action' => 'submit' ) ) ) ) .
1045 Xml::element( 'input', array(
1046 'type' => 'hidden',
1047 'name' => 'target',
1048 'value' => $this->mTargetObj->getPrefixedDBkey() ) ) .
1049 Xml::element( 'input', array(
1050 'type' => 'hidden',
1051 'name' => 'timestamp',
1052 'value' => $timestamp ) ) .
1053 Xml::element( 'input', array(
1054 'type' => 'hidden',
1055 'name' => 'wpEditToken',
1056 'value' => $user->getEditToken() ) ) .
1057 $previewButton .
1058 $diffButton .
1059 Xml::closeElement( 'form' ) .
1060 Xml::closeElement( 'div' )
1061 );
1062 }
1063
1064 /**
1065 * Build a diff display between this and the previous either deleted
1066 * or non-deleted edit.
1067 *
1068 * @param Revision $previousRev
1069 * @param Revision $currentRev
1070 * @return string HTML
1071 */
1072 function showDiff( $previousRev, $currentRev ) {
1073 $diffContext = clone $this->getContext();
1074 $diffContext->setTitle( $currentRev->getTitle() );
1075 $diffContext->setWikiPage( WikiPage::factory( $currentRev->getTitle() ) );
1076
1077 $diffEngine = $currentRev->getContentHandler()->createDifferenceEngine( $diffContext );
1078 $diffEngine->showDiffStyle();
1079
1080 $formattedDiff = $diffEngine->generateContentDiffBody(
1081 $previousRev->getContent( Revision::FOR_THIS_USER, $this->getUser() ),
1082 $currentRev->getContent( Revision::FOR_THIS_USER, $this->getUser() )
1083 );
1084
1085 $formattedDiff = $diffEngine->addHeader(
1086 $formattedDiff,
1087 $this->diffHeader( $previousRev, 'o' ),
1088 $this->diffHeader( $currentRev, 'n' )
1089 );
1090
1091 $this->getOutput()->addHTML( "<div>$formattedDiff</div>\n" );
1092 }
1093
1094 /**
1095 * @param Revision $rev
1096 * @param string $prefix
1097 * @return string
1098 */
1099 private function diffHeader( $rev, $prefix ) {
1100 $isDeleted = !( $rev->getId() && $rev->getTitle() );
1101 if ( $isDeleted ) {
1102 /// @todo FIXME: $rev->getTitle() is null for deleted revs...?
1103 $targetPage = $this->getPageTitle();
1104 $targetQuery = array(
1105 'target' => $this->mTargetObj->getPrefixedText(),
1106 'timestamp' => wfTimestamp( TS_MW, $rev->getTimestamp() )
1107 );
1108 } else {
1109 /// @todo FIXME: getId() may return non-zero for deleted revs...
1110 $targetPage = $rev->getTitle();
1111 $targetQuery = array( 'oldid' => $rev->getId() );
1112 }
1113
1114 // Add show/hide deletion links if available
1115 $user = $this->getUser();
1116 $lang = $this->getLanguage();
1117 $rdel = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
1118
1119 if ( $rdel ) {
1120 $rdel = " $rdel";
1121 }
1122
1123 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
1124
1125 $tags = wfGetDB( DB_SLAVE )->selectField(
1126 'tag_summary',
1127 'ts_tags',
1128 array( 'ts_rev_id' => $rev->getId() ),
1129 __METHOD__
1130 );
1131 $tagSummary = ChangeTags::formatSummaryRow( $tags, 'deleteddiff' );
1132
1133 // FIXME This is reimplementing DifferenceEngine#getRevisionHeader
1134 // and partially #showDiffPage, but worse
1135 return '<div id="mw-diff-' . $prefix . 'title1"><strong>' .
1136 Linker::link(
1137 $targetPage,
1138 $this->msg(
1139 'revisionasof',
1140 $lang->userTimeAndDate( $rev->getTimestamp(), $user ),
1141 $lang->userDate( $rev->getTimestamp(), $user ),
1142 $lang->userTime( $rev->getTimestamp(), $user )
1143 )->escaped(),
1144 array(),
1145 $targetQuery
1146 ) .
1147 '</strong></div>' .
1148 '<div id="mw-diff-' . $prefix . 'title2">' .
1149 Linker::revUserTools( $rev ) . '<br />' .
1150 '</div>' .
1151 '<div id="mw-diff-' . $prefix . 'title3">' .
1152 $minor . Linker::revComment( $rev ) . $rdel . '<br />' .
1153 '</div>' .
1154 '<div id="mw-diff-' . $prefix . 'title5">' .
1155 $tagSummary[0] . '<br />' .
1156 '</div>';
1157 }
1158
1159 /**
1160 * Show a form confirming whether a tokenless user really wants to see a file
1161 * @param string $key
1162 */
1163 private function showFileConfirmationForm( $key ) {
1164 $out = $this->getOutput();
1165 $lang = $this->getLanguage();
1166 $user = $this->getUser();
1167 $file = new ArchivedFile( $this->mTargetObj, '', $this->mFilename );
1168 $out->addWikiMsg( 'undelete-show-file-confirm',
1169 $this->mTargetObj->getText(),
1170 $lang->userDate( $file->getTimestamp(), $user ),
1171 $lang->userTime( $file->getTimestamp(), $user ) );
1172 $out->addHTML(
1173 Xml::openElement( 'form', array(
1174 'method' => 'POST',
1175 'action' => $this->getPageTitle()->getLocalURL( array(
1176 'target' => $this->mTarget,
1177 'file' => $key,
1178 'token' => $user->getEditToken( $key ),
1179 ) ),
1180 )
1181 ) .
1182 Xml::submitButton( $this->msg( 'undelete-show-file-submit' )->text() ) .
1183 '</form>'
1184 );
1185 }
1186
1187 /**
1188 * Show a deleted file version requested by the visitor.
1189 * @param string $key
1190 */
1191 private function showFile( $key ) {
1192 $this->getOutput()->disable();
1193
1194 # We mustn't allow the output to be Squid cached, otherwise
1195 # if an admin previews a deleted image, and it's cached, then
1196 # a user without appropriate permissions can toddle off and
1197 # nab the image, and Squid will serve it
1198 $response = $this->getRequest()->response();
1199 $response->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1200 $response->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1201 $response->header( 'Pragma: no-cache' );
1202
1203 $repo = RepoGroup::singleton()->getLocalRepo();
1204 $path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
1205 $repo->streamFile( $path );
1206 }
1207
1208 private function showHistory() {
1209 $out = $this->getOutput();
1210 if ( $this->mAllowed ) {
1211 $out->addModules( 'mediawiki.special.undelete' );
1212 }
1213 $out->wrapWikiMsg(
1214 "<div class='mw-undelete-pagetitle'>\n$1\n</div>\n",
1215 array( 'undeletepagetitle', wfEscapeWikiText( $this->mTargetObj->getPrefixedText() ) )
1216 );
1217
1218 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
1219 Hooks::run( 'UndeleteForm::showHistory', array( &$archive, $this->mTargetObj ) );
1220 /*
1221 $text = $archive->getLastRevisionText();
1222 if( is_null( $text ) ) {
1223 $out->addWikiMsg( 'nohistory' );
1224 return;
1225 }
1226 */
1227 $out->addHTML( '<div class="mw-undelete-history">' );
1228 if ( $this->mAllowed ) {
1229 $out->addWikiMsg( 'undeletehistory' );
1230 $out->addWikiMsg( 'undeleterevdel' );
1231 } else {
1232 $out->addWikiMsg( 'undeletehistorynoadmin' );
1233 }
1234 $out->addHTML( '</div>' );
1235
1236 # List all stored revisions
1237 $revisions = $archive->listRevisions();
1238 $files = $archive->listFiles();
1239
1240 $haveRevisions = $revisions && $revisions->numRows() > 0;
1241 $haveFiles = $files && $files->numRows() > 0;
1242
1243 # Batch existence check on user and talk pages
1244 if ( $haveRevisions ) {
1245 $batch = new LinkBatch();
1246 foreach ( $revisions as $row ) {
1247 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->ar_user_text ) );
1248 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->ar_user_text ) );
1249 }
1250 $batch->execute();
1251 $revisions->seek( 0 );
1252 }
1253 if ( $haveFiles ) {
1254 $batch = new LinkBatch();
1255 foreach ( $files as $row ) {
1256 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->fa_user_text ) );
1257 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->fa_user_text ) );
1258 }
1259 $batch->execute();
1260 $files->seek( 0 );
1261 }
1262
1263 if ( $this->mAllowed ) {
1264 $action = $this->getPageTitle()->getLocalURL( array( 'action' => 'submit' ) );
1265 # Start the form here
1266 $top = Xml::openElement(
1267 'form',
1268 array( 'method' => 'post', 'action' => $action, 'id' => 'undelete' )
1269 );
1270 $out->addHTML( $top );
1271 }
1272
1273 # Show relevant lines from the deletion log:
1274 $deleteLogPage = new LogPage( 'delete' );
1275 $out->addHTML( Xml::element( 'h2', null, $deleteLogPage->getName()->text() ) . "\n" );
1276 LogEventsList::showLogExtract( $out, 'delete', $this->mTargetObj );
1277 # Show relevant lines from the suppression log:
1278 $suppressLogPage = new LogPage( 'suppress' );
1279 if ( $this->getUser()->isAllowed( 'suppressionlog' ) ) {
1280 $out->addHTML( Xml::element( 'h2', null, $suppressLogPage->getName()->text() ) . "\n" );
1281 LogEventsList::showLogExtract( $out, 'suppress', $this->mTargetObj );
1282 }
1283
1284 if ( $this->mAllowed && ( $haveRevisions || $haveFiles ) ) {
1285 # Format the user-visible controls (comment field, submission button)
1286 # in a nice little table
1287 if ( $this->getUser()->isAllowed( 'suppressrevision' ) ) {
1288 $unsuppressBox =
1289 "<tr>
1290 <td>&#160;</td>
1291 <td class='mw-input'>" .
1292 Xml::checkLabel( $this->msg( 'revdelete-unsuppress' )->text(),
1293 'wpUnsuppress', 'mw-undelete-unsuppress', $this->mUnsuppress ) .
1294 "</td>
1295 </tr>";
1296 } else {
1297 $unsuppressBox = '';
1298 }
1299
1300 $table = Xml::fieldset( $this->msg( 'undelete-fieldset-title' )->text() ) .
1301 Xml::openElement( 'table', array( 'id' => 'mw-undelete-table' ) ) .
1302 "<tr>
1303 <td colspan='2' class='mw-undelete-extrahelp'>" .
1304 $this->msg( 'undeleteextrahelp' )->parseAsBlock() .
1305 "</td>
1306 </tr>
1307 <tr>
1308 <td class='mw-label'>" .
1309 Xml::label( $this->msg( 'undeletecomment' )->text(), 'wpComment' ) .
1310 "</td>
1311 <td class='mw-input'>" .
1312 Xml::input(
1313 'wpComment',
1314 50,
1315 $this->mComment,
1316 array( 'id' => 'wpComment', 'autofocus' => true )
1317 ) .
1318 "</td>
1319 </tr>
1320 <tr>
1321 <td>&#160;</td>
1322 <td class='mw-submit'>" .
1323 Xml::submitButton(
1324 $this->msg( 'undeletebtn' )->text(),
1325 array( 'name' => 'restore', 'id' => 'mw-undelete-submit' )
1326 ) . ' ' .
1327 Xml::submitButton(
1328 $this->msg( 'undeleteinvert' )->text(),
1329 array( 'name' => 'invert', 'id' => 'mw-undelete-invert' )
1330 ) .
1331 "</td>
1332 </tr>" .
1333 $unsuppressBox .
1334 Xml::closeElement( 'table' ) .
1335 Xml::closeElement( 'fieldset' );
1336
1337 $out->addHTML( $table );
1338 }
1339
1340 $out->addHTML( Xml::element( 'h2', null, $this->msg( 'history' )->text() ) . "\n" );
1341
1342 if ( $haveRevisions ) {
1343 # The page's stored (deleted) history:
1344 $out->addHTML( '<ul>' );
1345 $remaining = $revisions->numRows();
1346 $earliestLiveTime = $this->mTargetObj->getEarliestRevTime();
1347
1348 foreach ( $revisions as $row ) {
1349 $remaining--;
1350 $out->addHTML( $this->formatRevisionRow( $row, $earliestLiveTime, $remaining ) );
1351 }
1352 $revisions->free();
1353 $out->addHTML( '</ul>' );
1354 } else {
1355 $out->addWikiMsg( 'nohistory' );
1356 }
1357
1358 if ( $haveFiles ) {
1359 $out->addHTML( Xml::element( 'h2', null, $this->msg( 'filehist' )->text() ) . "\n" );
1360 $out->addHTML( '<ul>' );
1361 foreach ( $files as $row ) {
1362 $out->addHTML( $this->formatFileRow( $row ) );
1363 }
1364 $files->free();
1365 $out->addHTML( '</ul>' );
1366 }
1367
1368 if ( $this->mAllowed ) {
1369 # Slip in the hidden controls here
1370 $misc = Html::hidden( 'target', $this->mTarget );
1371 $misc .= Html::hidden( 'wpEditToken', $this->getUser()->getEditToken() );
1372 $misc .= Xml::closeElement( 'form' );
1373 $out->addHTML( $misc );
1374 }
1375
1376 return true;
1377 }
1378
1379 private function formatRevisionRow( $row, $earliestLiveTime, $remaining ) {
1380 $rev = Revision::newFromArchiveRow( $row,
1381 array(
1382 'title' => $this->mTargetObj
1383 ) );
1384
1385 $revTextSize = '';
1386 $ts = wfTimestamp( TS_MW, $row->ar_timestamp );
1387 // Build checkboxen...
1388 if ( $this->mAllowed ) {
1389 if ( $this->mInvert ) {
1390 if ( in_array( $ts, $this->mTargetTimestamp ) ) {
1391 $checkBox = Xml::check( "ts$ts" );
1392 } else {
1393 $checkBox = Xml::check( "ts$ts", true );
1394 }
1395 } else {
1396 $checkBox = Xml::check( "ts$ts" );
1397 }
1398 } else {
1399 $checkBox = '';
1400 }
1401
1402 // Build page & diff links...
1403 $user = $this->getUser();
1404 if ( $this->mCanView ) {
1405 $titleObj = $this->getPageTitle();
1406 # Last link
1407 if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
1408 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
1409 $last = $this->msg( 'diff' )->escaped();
1410 } elseif ( $remaining > 0 || ( $earliestLiveTime && $ts > $earliestLiveTime ) ) {
1411 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
1412 $last = Linker::linkKnown(
1413 $titleObj,
1414 $this->msg( 'diff' )->escaped(),
1415 array(),
1416 array(
1417 'target' => $this->mTargetObj->getPrefixedText(),
1418 'timestamp' => $ts,
1419 'diff' => 'prev'
1420 )
1421 );
1422 } else {
1423 $pageLink = $this->getPageLink( $rev, $titleObj, $ts );
1424 $last = $this->msg( 'diff' )->escaped();
1425 }
1426 } else {
1427 $pageLink = htmlspecialchars( $this->getLanguage()->userTimeAndDate( $ts, $user ) );
1428 $last = $this->msg( 'diff' )->escaped();
1429 }
1430
1431 // User links
1432 $userLink = Linker::revUserTools( $rev );
1433
1434 // Minor edit
1435 $minor = $rev->isMinor() ? ChangesList::flag( 'minor' ) : '';
1436
1437 // Revision text size
1438 $size = $row->ar_len;
1439 if ( !is_null( $size ) ) {
1440 $revTextSize = Linker::formatRevisionSize( $size );
1441 }
1442
1443 // Edit summary
1444 $comment = Linker::revComment( $rev );
1445
1446 // Tags
1447 $attribs = array();
1448 list( $tagSummary, $classes ) = ChangeTags::formatSummaryRow( $row->ts_tags, 'deletedhistory' );
1449 if ( $classes ) {
1450 $attribs['class'] = implode( ' ', $classes );
1451 }
1452
1453 // Revision delete links
1454 $revdlink = Linker::getRevDeleteLink( $user, $rev, $this->mTargetObj );
1455
1456 $revisionRow = $this->msg( 'undelete-revision-row' )
1457 ->rawParams(
1458 $checkBox,
1459 $revdlink,
1460 $last,
1461 $pageLink,
1462 $userLink,
1463 $minor,
1464 $revTextSize,
1465 $comment,
1466 $tagSummary
1467 )
1468 ->escaped();
1469
1470 return Xml::tags( 'li', $attribs, $revisionRow ) . "\n";
1471 }
1472
1473 private function formatFileRow( $row ) {
1474 $file = ArchivedFile::newFromRow( $row );
1475 $ts = wfTimestamp( TS_MW, $row->fa_timestamp );
1476 $user = $this->getUser();
1477
1478 $checkBox = '';
1479 if ( $this->mCanView && $row->fa_storage_key ) {
1480 if ( $this->mAllowed ) {
1481 $checkBox = Xml::check( 'fileid' . $row->fa_id );
1482 }
1483 $key = urlencode( $row->fa_storage_key );
1484 $pageLink = $this->getFileLink( $file, $this->getPageTitle(), $ts, $key );
1485 } else {
1486 $pageLink = $this->getLanguage()->userTimeAndDate( $ts, $user );
1487 }
1488 $userLink = $this->getFileUser( $file );
1489 $data = $this->msg( 'widthheight' )->numParams( $row->fa_width, $row->fa_height )->text();
1490 $bytes = $this->msg( 'parentheses' )
1491 ->rawParams( $this->msg( 'nbytes' )->numParams( $row->fa_size )->text() )
1492 ->plain();
1493 $data = htmlspecialchars( $data . ' ' . $bytes );
1494 $comment = $this->getFileComment( $file );
1495
1496 // Add show/hide deletion links if available
1497 $canHide = $this->isAllowed( 'deleterevision' );
1498 if ( $canHide || ( $file->getVisibility() && $this->isAllowed( 'deletedhistory' ) ) ) {
1499 if ( !$file->userCan( File::DELETED_RESTRICTED, $user ) ) {
1500 // Revision was hidden from sysops
1501 $revdlink = Linker::revDeleteLinkDisabled( $canHide );
1502 } else {
1503 $query = array(
1504 'type' => 'filearchive',
1505 'target' => $this->mTargetObj->getPrefixedDBkey(),
1506 'ids' => $row->fa_id
1507 );
1508 $revdlink = Linker::revDeleteLink( $query,
1509 $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1510 }
1511 } else {
1512 $revdlink = '';
1513 }
1514
1515 return "<li>$checkBox $revdlink $pageLink . . $userLink $data $comment</li>\n";
1516 }
1517
1518 /**
1519 * Fetch revision text link if it's available to all users
1520 *
1521 * @param Revision $rev
1522 * @param Title $titleObj
1523 * @param string $ts Timestamp
1524 * @return string
1525 */
1526 function getPageLink( $rev, $titleObj, $ts ) {
1527 $user = $this->getUser();
1528 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1529
1530 if ( !$rev->userCan( Revision::DELETED_TEXT, $user ) ) {
1531 return '<span class="history-deleted">' . $time . '</span>';
1532 }
1533
1534 $link = Linker::linkKnown(
1535 $titleObj,
1536 htmlspecialchars( $time ),
1537 array(),
1538 array(
1539 'target' => $this->mTargetObj->getPrefixedText(),
1540 'timestamp' => $ts
1541 )
1542 );
1543
1544 if ( $rev->isDeleted( Revision::DELETED_TEXT ) ) {
1545 $link = '<span class="history-deleted">' . $link . '</span>';
1546 }
1547
1548 return $link;
1549 }
1550
1551 /**
1552 * Fetch image view link if it's available to all users
1553 *
1554 * @param File|ArchivedFile $file
1555 * @param Title $titleObj
1556 * @param string $ts A timestamp
1557 * @param string $key A storage key
1558 *
1559 * @return string HTML fragment
1560 */
1561 function getFileLink( $file, $titleObj, $ts, $key ) {
1562 $user = $this->getUser();
1563 $time = $this->getLanguage()->userTimeAndDate( $ts, $user );
1564
1565 if ( !$file->userCan( File::DELETED_FILE, $user ) ) {
1566 return '<span class="history-deleted">' . $time . '</span>';
1567 }
1568
1569 $link = Linker::linkKnown(
1570 $titleObj,
1571 htmlspecialchars( $time ),
1572 array(),
1573 array(
1574 'target' => $this->mTargetObj->getPrefixedText(),
1575 'file' => $key,
1576 'token' => $user->getEditToken( $key )
1577 )
1578 );
1579
1580 if ( $file->isDeleted( File::DELETED_FILE ) ) {
1581 $link = '<span class="history-deleted">' . $link . '</span>';
1582 }
1583
1584 return $link;
1585 }
1586
1587 /**
1588 * Fetch file's user id if it's available to this user
1589 *
1590 * @param File|ArchivedFile $file
1591 * @return string HTML fragment
1592 */
1593 function getFileUser( $file ) {
1594 if ( !$file->userCan( File::DELETED_USER, $this->getUser() ) ) {
1595 return '<span class="history-deleted">' .
1596 $this->msg( 'rev-deleted-user' )->escaped() .
1597 '</span>';
1598 }
1599
1600 $link = Linker::userLink( $file->getRawUser(), $file->getRawUserText() ) .
1601 Linker::userToolLinks( $file->getRawUser(), $file->getRawUserText() );
1602
1603 if ( $file->isDeleted( File::DELETED_USER ) ) {
1604 $link = '<span class="history-deleted">' . $link . '</span>';
1605 }
1606
1607 return $link;
1608 }
1609
1610 /**
1611 * Fetch file upload comment if it's available to this user
1612 *
1613 * @param File|ArchivedFile $file
1614 * @return string HTML fragment
1615 */
1616 function getFileComment( $file ) {
1617 if ( !$file->userCan( File::DELETED_COMMENT, $this->getUser() ) ) {
1618 return '<span class="history-deleted"><span class="comment">' .
1619 $this->msg( 'rev-deleted-comment' )->escaped() . '</span></span>';
1620 }
1621
1622 $link = Linker::commentBlock( $file->getRawDescription() );
1623
1624 if ( $file->isDeleted( File::DELETED_COMMENT ) ) {
1625 $link = '<span class="history-deleted">' . $link . '</span>';
1626 }
1627
1628 return $link;
1629 }
1630
1631 function undelete() {
1632 if ( $this->getConfig()->get( 'UploadMaintenance' )
1633 && $this->mTargetObj->getNamespace() == NS_FILE
1634 ) {
1635 throw new ErrorPageError( 'undelete-error', 'filedelete-maintenance' );
1636 }
1637
1638 if ( wfReadOnly() ) {
1639 throw new ReadOnlyError;
1640 }
1641
1642 $out = $this->getOutput();
1643 $archive = new PageArchive( $this->mTargetObj, $this->getConfig() );
1644 Hooks::run( 'UndeleteForm::undelete', array( &$archive, $this->mTargetObj ) );
1645 $ok = $archive->undelete(
1646 $this->mTargetTimestamp,
1647 $this->mComment,
1648 $this->mFileVersions,
1649 $this->mUnsuppress,
1650 $this->getUser()
1651 );
1652
1653 if ( is_array( $ok ) ) {
1654 if ( $ok[1] ) { // Undeleted file count
1655 Hooks::run( 'FileUndeleteComplete', array(
1656 $this->mTargetObj, $this->mFileVersions,
1657 $this->getUser(), $this->mComment ) );
1658 }
1659
1660 $link = Linker::linkKnown( $this->mTargetObj );
1661 $out->addHTML( $this->msg( 'undeletedpage' )->rawParams( $link )->parse() );
1662 } else {
1663 $out->setPageTitle( $this->msg( 'undelete-error' ) );
1664 }
1665
1666 // Show revision undeletion warnings and errors
1667 $status = $archive->getRevisionStatus();
1668 if ( $status && !$status->isGood() ) {
1669 $out->addWikiText( '<div class="error">' .
1670 $status->getWikiText(
1671 'cannotundelete',
1672 'cannotundelete'
1673 ) . '</div>'
1674 );
1675 }
1676
1677 // Show file undeletion warnings and errors
1678 $status = $archive->getFileStatus();
1679 if ( $status && !$status->isGood() ) {
1680 $out->addWikiText( '<div class="error">' .
1681 $status->getWikiText(
1682 'undelete-error-short',
1683 'undelete-error-long'
1684 ) . '</div>'
1685 );
1686 }
1687 }
1688
1689 protected function getGroupName() {
1690 return 'pagetools';
1691 }
1692 }