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