]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/specials/SpecialUndelete.php
MediaWiki 1.17.1-scripts
[autoinstallsdev/mediawiki.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         protected $title;
31         var $fileStatus;
32
33         function __construct( $title ) {
34                 if( is_null( $title ) ) {
35                         throw new MWException( __METHOD__ . ' given a null title.' );
36                 }
37                 $this->title = $title;
38         }
39
40         /**
41          * List all deleted pages recorded in the archive table. Returns result
42          * wrapper with (ar_namespace, ar_title, count) fields, ordered by page
43          * namespace/title.
44          *
45          * @return ResultWrapper
46          */
47         public static function listAllPages() {
48                 $dbr = wfGetDB( DB_SLAVE );
49                 return self::listPages( $dbr, '' );
50         }
51
52         /**
53          * List deleted pages recorded in the archive table matching the
54          * given title prefix.
55          * Returns result wrapper with (ar_namespace, ar_title, count) fields.
56          *
57          * @param $prefix String: title prefix
58          * @return ResultWrapper
59          */
60         public static function listPagesByPrefix( $prefix ) {
61                 $dbr = wfGetDB( DB_SLAVE );
62
63                 $title = Title::newFromText( $prefix );
64                 if( $title ) {
65                         $ns = $title->getNamespace();
66                         $prefix = $title->getDBkey();
67                 } else {
68                         // Prolly won't work too good
69                         // @todo handle bare namespace names cleanly?
70                         $ns = 0;
71                 }
72                 $conds = array(
73                         'ar_namespace' => $ns,
74                         'ar_title' . $dbr->buildLike( $prefix, $dbr->anyString() ),
75                 );
76                 return self::listPages( $dbr, $conds );
77         }
78
79         protected static function listPages( $dbr, $condition ) {
80                 return $dbr->resultObject(
81                         $dbr->select(
82                                 array( 'archive' ),
83                                 array(
84                                         'ar_namespace',
85                                         'ar_title',
86                                         'COUNT(*) AS count'
87                                 ),
88                                 $condition,
89                                 __METHOD__,
90                                 array(
91                                         'GROUP BY' => 'ar_namespace,ar_title',
92                                         'ORDER BY' => 'ar_namespace,ar_title',
93                                         'LIMIT' => 100,
94                                 )
95                         )
96                 );
97         }
98
99         /**
100          * List the revisions of the given page. Returns result wrapper with
101          * (ar_minor_edit, ar_timestamp, ar_user, ar_user_text, ar_comment) fields.
102          *
103          * @return ResultWrapper
104          */
105         function listRevisions() {
106                 $dbr = wfGetDB( DB_SLAVE );
107                 $res = $dbr->select( 'archive',
108                         array( 'ar_minor_edit', 'ar_timestamp', 'ar_user', 'ar_user_text', 'ar_comment', 'ar_len', 'ar_deleted' ),
109                         array( 'ar_namespace' => $this->title->getNamespace(),
110                                'ar_title' => $this->title->getDBkey() ),
111                         'PageArchive::listRevisions',
112                         array( 'ORDER BY' => 'ar_timestamp DESC' ) );
113                 $ret = $dbr->resultObject( $res );
114                 return $ret;
115         }
116
117         /**
118          * List the deleted file revisions for this page, if it's a file page.
119          * Returns a result wrapper with various filearchive fields, or null
120          * if not a file page.
121          *
122          * @return ResultWrapper
123          * @todo Does this belong in Image for fuller encapsulation?
124          */
125         function listFiles() {
126                 if( $this->title->getNamespace() == NS_FILE ) {
127                         $dbr = wfGetDB( DB_SLAVE );
128                         $res = $dbr->select( 'filearchive',
129                                 array(
130                                         'fa_id',
131                                         'fa_name',
132                                         'fa_archive_name',
133                                         'fa_storage_key',
134                                         'fa_storage_group',
135                                         'fa_size',
136                                         'fa_width',
137                                         'fa_height',
138                                         'fa_bits',
139                                         'fa_metadata',
140                                         'fa_media_type',
141                                         'fa_major_mime',
142                                         'fa_minor_mime',
143                                         'fa_description',
144                                         'fa_user',
145                                         'fa_user_text',
146                                         'fa_timestamp',
147                                         'fa_deleted' ),
148                                 array( 'fa_name' => $this->title->getDBkey() ),
149                                 __METHOD__,
150                                 array( 'ORDER BY' => 'fa_timestamp DESC' ) );
151                         $ret = $dbr->resultObject( $res );
152                         return $ret;
153                 }
154                 return null;
155         }
156
157         /**
158          * Fetch (and decompress if necessary) the stored text for the deleted
159          * revision of the page with the given timestamp.
160          *
161          * @param $timestamp String
162          * @return String
163          * @deprecated Use getRevision() for more flexible information
164          */
165         function getRevisionText( $timestamp ) {
166                 $rev = $this->getRevision( $timestamp );
167                 return $rev ? $rev->getText() : null;
168         }
169
170         /**
171          * Return a Revision object containing data for the deleted revision.
172          * Note that the result *may* or *may not* have a null page ID.
173          *
174          * @param $timestamp String
175          * @return Revision
176          */
177         function getRevision( $timestamp ) {
178                 $dbr = wfGetDB( DB_SLAVE );
179                 $row = $dbr->selectRow( 'archive',
180                         array(
181                                 'ar_rev_id',
182                                 'ar_text',
183                                 'ar_comment',
184                                 'ar_user',
185                                 'ar_user_text',
186                                 'ar_timestamp',
187                                 'ar_minor_edit',
188                                 'ar_flags',
189                                 'ar_text_id',
190                                 'ar_deleted',
191                                 'ar_len' ),
192                         array( 'ar_namespace' => $this->title->getNamespace(),
193                                'ar_title' => $this->title->getDBkey(),
194                                'ar_timestamp' => $dbr->timestamp( $timestamp ) ),
195                         __METHOD__ );
196                 if( $row ) {
197                         return Revision::newFromArchiveRow( $row, array( 'page' => $this->title->getArticleId() ) );
198                 } else {
199                         return null;
200                 }
201         }
202
203         /**
204          * Return the most-previous revision, either live or deleted, against
205          * the deleted revision given by timestamp.
206          *
207          * May produce unexpected results in case of history merges or other
208          * unusual time issues.
209          *
210          * @param $timestamp String
211          * @return Revision or null
212          */
213         function getPreviousRevision( $timestamp ) {
214                 $dbr = wfGetDB( DB_SLAVE );
215
216                 // Check the previous deleted revision...
217                 $row = $dbr->selectRow( 'archive',
218                         'ar_timestamp',
219                         array( 'ar_namespace' => $this->title->getNamespace(),
220                                'ar_title' => $this->title->getDBkey(),
221                                'ar_timestamp < ' .
222                                                 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ),
223                         __METHOD__,
224                         array(
225                                 'ORDER BY' => 'ar_timestamp DESC',
226                                 'LIMIT' => 1 ) );
227                 $prevDeleted = $row ? wfTimestamp( TS_MW, $row->ar_timestamp ) : false;
228
229                 $row = $dbr->selectRow( array( 'page', 'revision' ),
230                         array( 'rev_id', 'rev_timestamp' ),
231                         array(
232                                 'page_namespace' => $this->title->getNamespace(),
233                                 'page_title' => $this->title->getDBkey(),
234                                 'page_id = rev_page',
235                                 'rev_timestamp < ' .
236                                                 $dbr->addQuotes( $dbr->timestamp( $timestamp ) ) ),
237                         __METHOD__,
238                         array(
239                                 'ORDER BY' => 'rev_timestamp DESC',
240                                 'LIMIT' => 1 ) );
241                 $prevLive = $row ? wfTimestamp( TS_MW, $row->rev_timestamp ) : false;
242                 $prevLiveId = $row ? intval( $row->rev_id ) : null;
243
244                 if( $prevLive && $prevLive > $prevDeleted ) {
245                         // Most prior revision was live
246                         return Revision::newFromId( $prevLiveId );
247                 } elseif( $prevDeleted ) {
248                         // Most prior revision was deleted
249                         return $this->getRevision( $prevDeleted );
250                 } else {
251                         // No prior revision on this page.
252                         return null;
253                 }
254         }
255
256         /**
257          * Get the text from an archive row containing ar_text, ar_flags and ar_text_id
258          *
259          * @param $row Object: database row
260          * @return Revision
261          */
262         function getTextFromRow( $row ) {
263                 if( is_null( $row->ar_text_id ) ) {
264                         // An old row from MediaWiki 1.4 or previous.
265                         // Text is embedded in this row in classic compression format.
266                         return Revision::getRevisionText( $row, "ar_" );
267                 } else {
268                         // New-style: keyed to the text storage backend.
269                         $dbr = wfGetDB( DB_SLAVE );
270                         $text = $dbr->selectRow( 'text',
271                                 array( 'old_text', 'old_flags' ),
272                                 array( 'old_id' => $row->ar_text_id ),
273                                 __METHOD__ );
274                         return Revision::getRevisionText( $text );
275                 }
276         }
277
278
279         /**
280          * Fetch (and decompress if necessary) the stored text of the most
281          * recently edited deleted revision of the page.
282          *
283          * If there are no archived revisions for the page, returns NULL.
284          *
285          * @return String
286          */
287         function getLastRevisionText() {
288                 $dbr = wfGetDB( DB_SLAVE );
289                 $row = $dbr->selectRow( 'archive',
290                         array( 'ar_text', 'ar_flags', 'ar_text_id' ),
291                         array( 'ar_namespace' => $this->title->getNamespace(),
292                                'ar_title' => $this->title->getDBkey() ),
293                         __METHOD__,
294                         array( 'ORDER BY' => 'ar_timestamp DESC' ) );
295                 if( $row ) {
296                         return $this->getTextFromRow( $row );
297                 } else {
298                         return null;
299                 }
300         }
301
302         /**
303          * Quick check if any archived revisions are present for the page.
304          *
305          * @return Boolean
306          */
307         function isDeleted() {
308                 $dbr = wfGetDB( DB_SLAVE );
309                 $n = $dbr->selectField( 'archive', 'COUNT(ar_title)',
310                         array( 'ar_namespace' => $this->title->getNamespace(),
311                                'ar_title' => $this->title->getDBkey() ) );
312                 return ($n > 0);
313         }
314
315         /**
316          * Restore the given (or all) text and file revisions for the page.
317          * Once restored, the items will be removed from the archive tables.
318          * The deletion log will be updated with an undeletion notice.
319          *
320          * @param $timestamps Array: pass an empty array to restore all revisions, otherwise list the ones to undelete.
321          * @param $comment String
322          * @param $fileVersions Array
323          * @param $unsuppress Boolean
324          *
325          * @return array(number of file revisions restored, number of image revisions restored, log message)
326          * on success, false on failure
327          */
328         function undelete( $timestamps, $comment = '', $fileVersions = array(), $unsuppress = false ) {
329                 // If both the set of text revisions and file revisions are empty,
330                 // restore everything. Otherwise, just restore the requested items.
331                 $restoreAll = empty( $timestamps ) && empty( $fileVersions );
332
333                 $restoreText = $restoreAll || !empty( $timestamps );
334                 $restoreFiles = $restoreAll || !empty( $fileVersions );
335
336                 if( $restoreFiles && $this->title->getNamespace() == NS_FILE ) {
337                         $img = wfLocalFile( $this->title );
338                         $this->fileStatus = $img->restore( $fileVersions, $unsuppress );
339                         $filesRestored = $this->fileStatus->successCount;
340                 } else {
341                         $filesRestored = 0;
342                 }
343
344                 if( $restoreText ) {
345                         $textRestored = $this->undeleteRevisions( $timestamps, $unsuppress, $comment );
346                         if($textRestored === false) // It must be one of UNDELETE_*
347                                 return false;
348                 } else {
349                         $textRestored = 0;
350                 }
351
352                 // Touch the log!
353                 global $wgContLang;
354                 $log = new LogPage( 'delete' );
355
356                 if( $textRestored && $filesRestored ) {
357                         $reason = wfMsgExt( 'undeletedrevisions-files', array( 'content', 'parsemag' ),
358                                 $wgContLang->formatNum( $textRestored ),
359                                 $wgContLang->formatNum( $filesRestored ) );
360                 } elseif( $textRestored ) {
361                         $reason = wfMsgExt( 'undeletedrevisions', array( 'content', 'parsemag' ),
362                                 $wgContLang->formatNum( $textRestored ) );
363                 } elseif( $filesRestored ) {
364                         $reason = wfMsgExt( 'undeletedfiles', array( 'content', 'parsemag' ),
365                                 $wgContLang->formatNum( $filesRestored ) );
366                 } else {
367                         wfDebug( "Undelete: nothing undeleted...\n" );
368                         return false;
369                 }
370
371                 if( trim( $comment ) != '' )
372                         $reason .= wfMsgForContent( 'colon-separator' ) . $comment;
373                 $log->addEntry( 'restore', $this->title, $reason );
374
375                 return array($textRestored, $filesRestored, $reason);
376         }
377
378         /**
379          * This is the meaty bit -- restores archived revisions of the given page
380          * to the cur/old tables. If the page currently exists, all revisions will
381          * be stuffed into old, otherwise the most recent will go into cur.
382          *
383          * @param $timestamps Array: pass an empty array to restore all revisions, otherwise list the ones to undelete.
384          * @param $comment String
385          * @param $unsuppress Boolean: remove all ar_deleted/fa_deleted restrictions of seletected revs
386          *
387          * @return Mixed: number of revisions restored or false on failure
388          */
389         private function undeleteRevisions( $timestamps, $unsuppress = false, $comment = '' ) {
390                 if ( wfReadOnly() )
391                         return false;
392                 $restoreAll = empty( $timestamps );
393
394                 $dbw = wfGetDB( DB_MASTER );
395
396                 # Does this page already exist? We'll have to update it...
397                 $article = new Article( $this->title );
398                 $options = 'FOR UPDATE'; // lock page
399                 $page = $dbw->selectRow( 'page',
400                         array( 'page_id', 'page_latest' ),
401                         array( 'page_namespace' => $this->title->getNamespace(),
402                                'page_title'     => $this->title->getDBkey() ),
403                         __METHOD__,
404                         $options
405                 );
406                 if( $page ) {
407                         $makepage = false;
408                         # Page already exists. Import the history, and if necessary
409                         # we'll update the latest revision field in the record.
410                         $newid             = 0;
411                         $pageId            = $page->page_id;
412                         $previousRevId    = $page->page_latest;
413                         # Get the time span of this page
414                         $previousTimestamp = $dbw->selectField( 'revision', 'rev_timestamp',
415                                 array( 'rev_id' => $previousRevId ),
416                                 __METHOD__ );
417                         if( $previousTimestamp === false ) {
418                                 wfDebug( __METHOD__.": existing page refers to a page_latest that does not exist\n" );
419                                 return 0;
420                         }
421                 } else {
422                         # Have to create a new article...
423                         $makepage = true;
424                         $previousRevId = 0;
425                         $previousTimestamp = 0;
426                 }
427
428                 if( $restoreAll ) {
429                         $oldones = '1 = 1'; # All revisions...
430                 } else {
431                         $oldts = implode( ',',
432                                 array_map( array( &$dbw, 'addQuotes' ),
433                                         array_map( array( &$dbw, 'timestamp' ),
434                                                 $timestamps ) ) );
435
436                         $oldones = "ar_timestamp IN ( {$oldts} )";
437                 }
438
439                 /**
440                  * Select each archived revision...
441                  */
442                 $result = $dbw->select( 'archive',
443                         /* fields */ array(
444                                 'ar_rev_id',
445                                 'ar_text',
446                                 'ar_comment',
447                                 'ar_user',
448                                 'ar_user_text',
449                                 'ar_timestamp',
450                                 'ar_minor_edit',
451                                 'ar_flags',
452                                 'ar_text_id',
453                                 'ar_deleted',
454                                 'ar_page_id',
455                                 'ar_len' ),
456                         /* WHERE */ array(
457                                 'ar_namespace' => $this->title->getNamespace(),
458                                 'ar_title'     => $this->title->getDBkey(),
459                                 $oldones ),
460                         __METHOD__,
461                         /* options */ array( 'ORDER BY' => 'ar_timestamp' )
462                 );
463                 $ret = $dbw->resultObject( $result );
464                 $rev_count = $dbw->numRows( $result );
465                 if( !$rev_count ) {
466                         wfDebug( __METHOD__.": no revisions to restore\n" );
467                         return false; // ???
468                 }
469
470                 $ret->seek( $rev_count - 1 ); // move to last
471                 $row = $ret->fetchObject(); // get newest archived rev
472                 $ret->seek( 0 ); // move back
473
474                 if( $makepage ) {
475                         // Check the state of the newest to-be version...
476                         if( !$unsuppress && ($row->ar_deleted & Revision::DELETED_TEXT) ) {
477                                 return false; // we can't leave the current revision like this!
478                         }
479                         // Safe to insert now...
480                         $newid  = $article->insertOn( $dbw );
481                         $pageId = $newid;
482                 } else {
483                         // Check if a deleted revision will become the current revision...
484                         if( $row->ar_timestamp > $previousTimestamp ) {
485                                 // Check the state of the newest to-be version...
486                                 if( !$unsuppress && ($row->ar_deleted & Revision::DELETED_TEXT) ) {
487                                         return false; // we can't leave the current revision like this!
488                                 }
489                         }
490                 }
491
492                 $revision = null;
493                 $restored = 0;
494
495                 foreach ( $ret as $row ) {
496                         // Check for key dupes due to shitty archive integrity.
497                         if( $row->ar_rev_id ) {
498                                 $exists = $dbw->selectField( 'revision', '1', array('rev_id' => $row->ar_rev_id), __METHOD__ );
499                                 if( $exists ) continue; // don't throw DB errors
500                         }
501                         // Insert one revision at a time...maintaining deletion status
502                         // unless we are specifically removing all restrictions...
503                         $revision = Revision::newFromArchiveRow( $row,
504                                 array(
505                                         'page' => $pageId,
506                                         'deleted' => $unsuppress ? 0 : $row->ar_deleted
507                                 ) );
508
509                         $revision->insertOn( $dbw );
510                         $restored++;
511
512                         wfRunHooks( 'ArticleRevisionUndeleted', array( &$this->title, $revision, $row->ar_page_id ) );
513                 }
514                 # Now that it's safely stored, take it out of the archive
515                 $dbw->delete( 'archive',
516                         /* WHERE */ array(
517                                 'ar_namespace' => $this->title->getNamespace(),
518                                 'ar_title' => $this->title->getDBkey(),
519                                 $oldones ),
520                         __METHOD__ );
521
522                 // Was anything restored at all?
523                 if( $restored == 0 )
524                         return 0;
525
526                 if( $revision ) {
527                         // Attach the latest revision to the page...
528                         $wasnew = $article->updateIfNewerOn( $dbw, $revision, $previousRevId );
529                         if( $newid || $wasnew ) {
530                                 // Update site stats, link tables, etc
531                                 $article->createUpdates( $revision );
532                         }
533
534                         if( $newid ) {
535                                 wfRunHooks( 'ArticleUndelete', array( &$this->title, true, $comment ) );
536                                 Article::onArticleCreate( $this->title );
537                         } else {
538                                 wfRunHooks( 'ArticleUndelete', array( &$this->title, false, $comment ) );
539                                 Article::onArticleEdit( $this->title );
540                         }
541
542                         if( $this->title->getNamespace() == NS_FILE ) {
543                                 $update = new HTMLCacheUpdate( $this->title, 'imagelinks' );
544                                 $update->doUpdate();
545                         }
546                 } else {
547                         // Revision couldn't be created. This is very weird
548                         wfDebug( "Undelete: unknown error...\n" );
549                         return false;
550                 }
551
552                 return $restored;
553         }
554
555         function getFileStatus() { return $this->fileStatus; }
556 }
557
558 /**
559  * Special page allowing users with the appropriate permissions to view
560  * and restore deleted content.
561  *
562  * @ingroup SpecialPage
563  */
564 class UndeleteForm extends SpecialPage {
565         var $mAction, $mTarget, $mTimestamp, $mRestore, $mInvert, $mTargetObj;
566         var $mTargetTimestamp, $mAllowed, $mCanView, $mComment, $mToken, $mRequest;
567
568         function __construct( $request = null ) {
569                 parent::__construct( 'Undelete', 'deletedhistory' );
570
571                 if ( $request === null ) {
572                         global $wgRequest;
573                         $this->mRequest = $wgRequest;
574                 } else {
575                         $this->mRequest = $request;
576                 }
577         }
578
579         function loadRequest() {
580                 global $wgUser;
581                 $this->mAction = $this->mRequest->getVal( 'action' );
582                 $this->mTarget = $this->mRequest->getVal( 'target' );
583                 $this->mSearchPrefix = $this->mRequest->getText( 'prefix' );
584                 $time = $this->mRequest->getVal( 'timestamp' );
585                 $this->mTimestamp = $time ? wfTimestamp( TS_MW, $time ) : '';
586                 $this->mFile = $this->mRequest->getVal( 'file' );
587
588                 $posted = $this->mRequest->wasPosted() &&
589                         $wgUser->matchEditToken( $this->mRequest->getVal( 'wpEditToken' ) );
590                 $this->mRestore = $this->mRequest->getCheck( 'restore' ) && $posted;
591                 $this->mInvert = $this->mRequest->getCheck( 'invert' ) && $posted;
592                 $this->mPreview = $this->mRequest->getCheck( 'preview' ) && $posted;
593                 $this->mDiff = $this->mRequest->getCheck( 'diff' );
594                 $this->mComment = $this->mRequest->getText( 'wpComment' );
595                 $this->mUnsuppress = $this->mRequest->getVal( 'wpUnsuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
596                 $this->mToken = $this->mRequest->getVal( 'token' );
597
598                 if ( $wgUser->isAllowed( 'undelete' ) && !$wgUser->isBlocked() ) {
599                         $this->mAllowed = true; // user can restore
600                         $this->mCanView = true; // user can view content
601                 } elseif ( $wgUser->isAllowed( 'deletedtext' ) ) {
602                         $this->mAllowed = false; // user cannot restore
603                         $this->mCanView = true; // user can view content
604                 }  else { // user can only view the list of revisions
605                         $this->mAllowed = false;
606                         $this->mCanView = false;
607                         $this->mTimestamp = '';
608                         $this->mRestore = false;
609                 }
610
611                 if( $this->mRestore || $this->mInvert ) {
612                         $timestamps = array();
613                         $this->mFileVersions = array();
614                         foreach( $_REQUEST as $key => $val ) {
615                                 $matches = array();
616                                 if( preg_match( '/^ts(\d{14})$/', $key, $matches ) ) {
617                                         array_push( $timestamps, $matches[1] );
618                                 }
619
620                                 if( preg_match( '/^fileid(\d+)$/', $key, $matches ) ) {
621                                         $this->mFileVersions[] = intval( $matches[1] );
622                                 }
623                         }
624                         rsort( $timestamps );
625                         $this->mTargetTimestamp = $timestamps;
626                 }
627         }
628
629         function execute( $par ) {
630                 global $wgOut, $wgUser;
631
632                 $this->setHeaders();
633                 if ( !$this->userCanExecute( $wgUser ) ) {
634                         $this->displayRestrictionError();
635                         return;
636                 }
637                 $this->outputHeader();
638
639                 $this->loadRequest();
640
641                 if ( $this->mAllowed ) {
642                         $wgOut->setPagetitle( wfMsg( "undeletepage" ) );
643                 } else {
644                         $wgOut->setPagetitle( wfMsg( "viewdeletedpage" ) );
645                 }
646
647                 if( $par != '' ) {
648                         $this->mTarget = $par;
649                 }
650                 if ( $this->mTarget !== '' ) {
651                         $this->mTargetObj = Title::newFromURL( $this->mTarget );
652                 } else {
653                         $this->mTargetObj = null;
654                 }
655
656                 if( is_null( $this->mTargetObj ) ) {
657                 # Not all users can just browse every deleted page from the list
658                         if( $wgUser->isAllowed( 'browsearchive' ) ) {
659                                 $this->showSearchForm();
660
661                                 # List undeletable articles
662                                 if( $this->mSearchPrefix ) {
663                                         $result = PageArchive::listPagesByPrefix( $this->mSearchPrefix );
664                                         $this->showList( $result );
665                                 }
666                         } else {
667                                 $wgOut->addWikiMsg( 'undelete-header' );
668                         }
669                         return;
670                 }
671                 if( $this->mTimestamp !== '' ) {
672                         return $this->showRevision( $this->mTimestamp );
673                 }
674                 if( $this->mFile !== null ) {
675                         $file = new ArchivedFile( $this->mTargetObj, '', $this->mFile );
676                         // Check if user is allowed to see this file
677                         if ( !$file->exists() ) {
678                                 $wgOut->addWikiMsg( 'filedelete-nofile', $this->mFile );
679                                 return;
680                         } else if( !$file->userCan( File::DELETED_FILE ) ) {
681                                 if( $file->isDeleted( File::DELETED_RESTRICTED ) ) {
682                                         $wgOut->permissionRequired( 'suppressrevision' );
683                                 } else {
684                                         $wgOut->permissionRequired( 'deletedtext' );
685                                 }
686                                 return false;
687                         } elseif ( !$wgUser->matchEditToken( $this->mToken, $this->mFile ) ) {
688                                 $this->showFileConfirmationForm( $this->mFile );
689                                 return false;
690                         } else {
691                                 return $this->showFile( $this->mFile );
692                         }
693                 }
694                 if( $this->mRestore && $this->mAction == "submit" ) {
695                         global $wgUploadMaintenance;
696                         if( $wgUploadMaintenance && $this->mTargetObj && $this->mTargetObj->getNamespace() == NS_FILE ) {
697                                 $wgOut->wrapWikiMsg( "<div class='error'>\n$1\n</div>\n", array( 'filedelete-maintenance' ) );
698                                 return;
699                         }
700                         return $this->undelete();
701                 }
702                 if( $this->mInvert && $this->mAction == "submit" ) {
703                         return $this->showHistory( );
704                 }
705                 return $this->showHistory();
706         }
707
708         function showSearchForm() {
709                 global $wgOut, $wgScript;
710                 $wgOut->addWikiMsg( 'undelete-header' );
711
712                 $wgOut->addHTML(
713                         Xml::openElement( 'form', array(
714                                 'method' => 'get',
715                                 'action' => $wgScript ) ) .
716                         Xml::fieldset( wfMsg( 'undelete-search-box' ) ) .
717                         Html::hidden( 'title',
718                                 $this->getTitle()->getPrefixedDbKey() ) .
719                         Xml::inputLabel( wfMsg( 'undelete-search-prefix' ),
720                                 'prefix', 'prefix', 20,
721                                 $this->mSearchPrefix ) . ' ' .
722                         Xml::submitButton( wfMsg( 'undelete-search-submit' ) ) .
723                         Xml::closeElement( 'fieldset' ) .
724                         Xml::closeElement( 'form' )
725                 );
726         }
727
728         // Generic list of deleted pages
729         private function showList( $result ) {
730                 global $wgLang, $wgUser, $wgOut;
731
732                 if( $result->numRows() == 0 ) {
733                         $wgOut->addWikiMsg( 'undelete-no-results' );
734                         return;
735                 }
736
737                 $wgOut->addWikiMsg( 'undeletepagetext', $wgLang->formatNum( $result->numRows() ) );
738
739                 $sk = $wgUser->getSkin();
740                 $undelete = $this->getTitle();
741                 $wgOut->addHTML( "<ul>\n" );
742                 foreach ( $result as $row ) {
743                         $title = Title::makeTitleSafe( $row->ar_namespace, $row->ar_title );
744                         $link = $sk->linkKnown(
745                                 $undelete,
746                                 htmlspecialchars( $title->getPrefixedText() ),
747                                 array(),
748                                 array( 'target' => $title->getPrefixedText() )
749                         );
750                         $revs = wfMsgExt( 'undeleterevisions',
751                                 array( 'parseinline' ),
752                                 $wgLang->formatNum( $row->count ) );
753                         $wgOut->addHTML( "<li>{$link} ({$revs})</li>\n" );
754                 }
755                 $result->free();
756                 $wgOut->addHTML( "</ul>\n" );
757
758                 return true;
759         }
760
761         private function showRevision( $timestamp ) {
762                 global $wgLang, $wgUser, $wgOut;
763
764                 $skin = $wgUser->getSkin();
765
766                 if(!preg_match("/[0-9]{14}/",$timestamp)) return 0;
767
768                 $archive = new PageArchive( $this->mTargetObj );
769                 $rev = $archive->getRevision( $timestamp );
770
771                 if( !$rev ) {
772                         $wgOut->addWikiMsg( 'undeleterevision-missing' );
773                         return;
774                 }
775
776                 if( $rev->isDeleted(Revision::DELETED_TEXT) ) {
777                         if( !$rev->userCan(Revision::DELETED_TEXT) ) {
778                                 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-permission' );
779                                 return;
780                         } else {
781                                 $wgOut->wrapWikiMsg( "<div class='mw-warning plainlinks'>\n$1\n</div>\n", 'rev-deleted-text-view' );
782                                 $wgOut->addHTML( '<br />' );
783                                 // and we are allowed to see...
784                         }
785                 }
786
787                 $wgOut->setPageTitle( wfMsg( 'undeletepage' ) );
788
789                 $link = $skin->linkKnown(
790                         $this->getTitle( $this->mTargetObj->getPrefixedDBkey() ),
791                         htmlspecialchars( $this->mTargetObj->getPrefixedText() )
792                 );
793
794                 if( $this->mDiff ) {
795                         $previousRev = $archive->getPreviousRevision( $timestamp );
796                         if( $previousRev ) {
797                                 $this->showDiff( $previousRev, $rev );
798                                 if( $wgUser->getOption( 'diffonly' ) ) {
799                                         return;
800                                 } else {
801                                         $wgOut->addHTML( '<hr />' );
802                                 }
803                         } else {
804                                 $wgOut->addWikiMsg( 'undelete-nodiff' );
805                         }
806                 }
807
808                 // date and time are separate parameters to facilitate localisation.
809                 // $time is kept for backward compat reasons.
810                 $time = htmlspecialchars( $wgLang->timeAndDate( $timestamp, true ) );
811                 $d = htmlspecialchars( $wgLang->date( $timestamp, true ) );
812                 $t = htmlspecialchars( $wgLang->time( $timestamp, true ) );
813                 $user = $skin->revUserTools( $rev );
814
815                 if( $this->mPreview ) {
816                         $openDiv = '<div id="mw-undelete-revision" class="mw-warning">';
817                 } else {
818                         $openDiv = '<div id="mw-undelete-revision">';
819                 }
820
821                 // Revision delete links
822                 $canHide = $wgUser->isAllowed( 'deleterevision' );
823                 if( $this->mDiff ) {
824                         $revdlink = ''; // diffs already have revision delete links
825                 } else if( $canHide || ($rev->getVisibility() && $wgUser->isAllowed('deletedhistory')) ) {
826                         if( !$rev->userCan(Revision::DELETED_RESTRICTED ) ) {
827                                 $revdlink = $skin->revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
828                         } else {
829                                 $query = array(
830                                         'type'   => 'archive',
831                                         'target' => $this->mTargetObj->getPrefixedDBkey(),
832                                         'ids'    => $rev->getTimestamp()
833                                 );
834                                 $revdlink = $skin->revDeleteLink( $query,
835                                         $rev->isDeleted( File::DELETED_RESTRICTED ), $canHide );
836                         }
837                 } else {
838                         $revdlink = '';
839                 }
840
841                 $wgOut->addHTML( $openDiv . $revdlink . wfMsgWikiHtml( 'undelete-revision', $link, $time, $user, $d, $t ) . '</div>' );
842                 wfRunHooks( 'UndeleteShowRevision', array( $this->mTargetObj, $rev ) );
843
844                 if( $this->mPreview ) {
845                         //Hide [edit]s
846                         $popts = $wgOut->parserOptions();
847                         $popts->setEditSection( false );
848                         $wgOut->parserOptions( $popts );
849                         $wgOut->addWikiTextTitleTidy( $rev->getText( Revision::FOR_THIS_USER ), $this->mTargetObj, true );
850                 }
851
852                 $wgOut->addHTML(
853                         Xml::element( 'textarea', array(
854                                         'readonly' => 'readonly',
855                                         'cols' => intval( $wgUser->getOption( 'cols' ) ),
856                                         'rows' => intval( $wgUser->getOption( 'rows' ) ) ),
857                                 $rev->getText( Revision::FOR_THIS_USER ) . "\n" ) .
858                         Xml::openElement( 'div' ) .
859                         Xml::openElement( 'form', array(
860                                 'method' => 'post',
861                                 'action' => $this->getTitle()->getLocalURL( array( 'action' => 'submit' ) ) ) ) .
862                         Xml::element( 'input', array(
863                                 'type' => 'hidden',
864                                 'name' => 'target',
865                                 'value' => $this->mTargetObj->getPrefixedDbKey() ) ) .
866                         Xml::element( 'input', array(
867                                 'type' => 'hidden',
868                                 'name' => 'timestamp',
869                                 'value' => $timestamp ) ) .
870                         Xml::element( 'input', array(
871                                 'type' => 'hidden',
872                                 'name' => 'wpEditToken',
873                                 'value' => $wgUser->editToken() ) ) .
874                         Xml::element( 'input', array(
875                                 'type' => 'submit',
876                                 'name' => 'preview',
877                                 'value' => wfMsg( 'showpreview' ) ) ) .
878                         Xml::element( 'input', array(
879                                 'name' => 'diff',
880                                 'type' => 'submit',
881                                 'value' => wfMsg( 'showdiff' ) ) ) .
882                         Xml::closeElement( 'form' ) .
883                         Xml::closeElement( 'div' ) );
884         }
885
886         /**
887          * Build a diff display between this and the previous either deleted
888          * or non-deleted edit.
889          *
890          * @param $previousRev Revision
891          * @param $currentRev Revision
892          * @return String: HTML
893          */
894         function showDiff( $previousRev, $currentRev ) {
895                 global $wgOut;
896
897                 $diffEngine = new DifferenceEngine( $previousRev->getTitle() );
898                 $diffEngine->showDiffStyle();
899                 $wgOut->addHTML(
900                         "<div>" .
901                         "<table border='0' width='98%' cellpadding='0' cellspacing='4' class='diff'>" .
902                         "<col class='diff-marker' />" .
903                         "<col class='diff-content' />" .
904                         "<col class='diff-marker' />" .
905                         "<col class='diff-content' />" .
906                         "<tr>" .
907                                 "<td colspan='2' width='50%' align='center' class='diff-otitle'>" .
908                                 $this->diffHeader( $previousRev, 'o' ) .
909                                 "</td>\n" .
910                                 "<td colspan='2' width='50%' align='center' class='diff-ntitle'>" .
911                                 $this->diffHeader( $currentRev, 'n' ) .
912                                 "</td>\n" .
913                         "</tr>" .
914                         $diffEngine->generateDiffBody(
915                                 $previousRev->getText(), $currentRev->getText() ) .
916                         "</table>" .
917                         "</div>\n"
918                 );
919         }
920
921         private function diffHeader( $rev, $prefix ) {
922                 global $wgUser, $wgLang;
923                 $sk = $wgUser->getSkin();
924                 $isDeleted = !( $rev->getId() && $rev->getTitle() );
925                 if( $isDeleted ) {
926                         /// @todo Fixme: $rev->getTitle() is null for deleted revs...?
927                         $targetPage = $this->getTitle();
928                         $targetQuery = array(
929                                 'target' => $this->mTargetObj->getPrefixedText(),
930                                 'timestamp' => wfTimestamp( TS_MW, $rev->getTimestamp() )
931                         );
932                 } else {
933                         /// @todo Fixme getId() may return non-zero for deleted revs...
934                         $targetPage = $rev->getTitle();
935                         $targetQuery = array( 'oldid' => $rev->getId() );
936                 }
937                 // Add show/hide deletion links if available
938                 $canHide = $wgUser->isAllowed( 'deleterevision' );
939                 if( $canHide || ($rev->getVisibility() && $wgUser->isAllowed('deletedhistory')) ) {
940                         $del = ' ';
941                         if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
942                                 $del .= $sk->revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
943                         } else {
944                                 $query = array(
945                                         'type'   => 'archive',
946                                         'target' => $this->mTargetObj->getPrefixedDbkey(),
947                                         'ids'    => $rev->getTimestamp()
948                                 );
949                                 $del .= $sk->revDeleteLink( $query,
950                                         $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
951                         }
952                 } else {
953                         $del = '';
954                 }
955                 return
956                         '<div id="mw-diff-'.$prefix.'title1"><strong>' .
957                                 $sk->link(
958                                         $targetPage,
959                                         wfMsgHtml(
960                                                 'revisionasof',
961                                                 htmlspecialchars( $wgLang->timeanddate( $rev->getTimestamp(), true ) ),
962                                                 htmlspecialchars( $wgLang->date( $rev->getTimestamp(), true ) ),
963                                                 htmlspecialchars( $wgLang->time( $rev->getTimestamp(), true ) )
964                                         ),
965                                         array(),
966                                         $targetQuery
967                                 ) .
968                         '</strong></div>' .
969                         '<div id="mw-diff-'.$prefix.'title2">' .
970                                 $sk->revUserTools( $rev ) . '<br />' .
971                         '</div>' .
972                         '<div id="mw-diff-'.$prefix.'title3">' .
973                                 $sk->revComment( $rev ) . $del . '<br />' .
974                         '</div>';
975         }
976
977         /**
978          * Show a form confirming whether a tokenless user really wants to see a file
979          */
980         private function showFileConfirmationForm( $key ) {
981                 global $wgOut, $wgUser, $wgLang;
982                 $file = new ArchivedFile( $this->mTargetObj, '', $this->mFile );
983                 $wgOut->addWikiMsg( 'undelete-show-file-confirm',
984                         $this->mTargetObj->getText(),
985                         $wgLang->date( $file->getTimestamp() ),
986                         $wgLang->time( $file->getTimestamp() ) );
987                 $wgOut->addHTML(
988                         Xml::openElement( 'form', array(
989                                 'method' => 'POST',
990                                 'action' => $this->getTitle()->getLocalUrl(
991                                         'target=' . urlencode( $this->mTarget ) .
992                                         '&file=' . urlencode( $key ) .
993                                         '&token=' . urlencode( $wgUser->editToken( $key ) ) )
994                                 )
995                         ) .
996                         Xml::submitButton( wfMsg( 'undelete-show-file-submit' ) ) .
997                         '</form>'
998                 );
999         }
1000
1001         /**
1002          * Show a deleted file version requested by the visitor.
1003          */
1004         private function showFile( $key ) {
1005                 global $wgOut, $wgRequest;
1006                 $wgOut->disable();
1007
1008                 # We mustn't allow the output to be Squid cached, otherwise
1009                 # if an admin previews a deleted image, and it's cached, then
1010                 # a user without appropriate permissions can toddle off and
1011                 # nab the image, and Squid will serve it
1012                 $wgRequest->response()->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
1013                 $wgRequest->response()->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
1014                 $wgRequest->response()->header( 'Pragma: no-cache' );
1015
1016                 global $IP;
1017                 require_once( "$IP/includes/StreamFile.php" );
1018                 $repo = RepoGroup::singleton()->getLocalRepo();
1019                 $path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
1020                 wfStreamFile( $path );
1021         }
1022
1023         private function showHistory( ) {
1024                 global $wgUser, $wgOut;
1025
1026                 $sk = $wgUser->getSkin();
1027                 if( $this->mAllowed ) {
1028                         $wgOut->setPagetitle( wfMsg( "undeletepage" ) );
1029                 } else {
1030                         $wgOut->setPagetitle( wfMsg( 'viewdeletedpage' ) );
1031                 }
1032
1033                 $wgOut->wrapWikiMsg(  "<div class='mw-undelete-pagetitle'>\n$1\n</div>\n", array ( 'undeletepagetitle', $this->mTargetObj->getPrefixedText() ) );
1034
1035                 $archive = new PageArchive( $this->mTargetObj );
1036                 /*
1037                 $text = $archive->getLastRevisionText();
1038                 if( is_null( $text ) ) {
1039                         $wgOut->addWikiMsg( "nohistory" );
1040                         return;
1041                 }
1042                 */
1043                 $wgOut->addHTML( '<div class="mw-undelete-history">' );
1044                 if ( $this->mAllowed ) {
1045                         $wgOut->addWikiMsg( "undeletehistory" );
1046                         $wgOut->addWikiMsg( "undeleterevdel" );
1047                 } else {
1048                         $wgOut->addWikiMsg( "undeletehistorynoadmin" );
1049                 }
1050                 $wgOut->addHTML( '</div>' );
1051
1052                 # List all stored revisions
1053                 $revisions = $archive->listRevisions();
1054                 $files = $archive->listFiles();
1055
1056                 $haveRevisions = $revisions && $revisions->numRows() > 0;
1057                 $haveFiles = $files && $files->numRows() > 0;
1058
1059                 # Batch existence check on user and talk pages
1060                 if( $haveRevisions ) {
1061                         $batch = new LinkBatch();
1062                         foreach ( $revisions as $row ) {
1063                                 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->ar_user_text ) );
1064                                 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->ar_user_text ) );
1065                         }
1066                         $batch->execute();
1067                         $revisions->seek( 0 );
1068                 }
1069                 if( $haveFiles ) {
1070                         $batch = new LinkBatch();
1071                         foreach ( $files as $row ) {
1072                                 $batch->addObj( Title::makeTitleSafe( NS_USER, $row->fa_user_text ) );
1073                                 $batch->addObj( Title::makeTitleSafe( NS_USER_TALK, $row->fa_user_text ) );
1074                         }
1075                         $batch->execute();
1076                         $files->seek( 0 );
1077                 }
1078
1079                 if ( $this->mAllowed ) {
1080                         $action = $this->getTitle()->getLocalURL( array( 'action' => 'submit' ) );
1081                         # Start the form here
1082                         $top = Xml::openElement( 'form', array( 'method' => 'post', 'action' => $action, 'id' => 'undelete' ) );
1083                         $wgOut->addHTML( $top );
1084                 }
1085
1086                 # Show relevant lines from the deletion log:
1087                 $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'delete' ) ) . "\n" );
1088                 LogEventsList::showLogExtract( $wgOut, 'delete', $this->mTargetObj->getPrefixedText() );
1089                 # Show relevant lines from the suppression log:
1090                 if( $wgUser->isAllowed( 'suppressionlog' ) ) {
1091                         $wgOut->addHTML( Xml::element( 'h2', null, LogPage::logName( 'suppress' ) ) . "\n" );
1092                         LogEventsList::showLogExtract( $wgOut, 'suppress', $this->mTargetObj->getPrefixedText() );
1093                 }
1094
1095                 if( $this->mAllowed && ( $haveRevisions || $haveFiles ) ) {
1096                         # Format the user-visible controls (comment field, submission button)
1097                         # in a nice little table
1098                         if( $wgUser->isAllowed( 'suppressrevision' ) ) {
1099                                 $unsuppressBox =
1100                                         "<tr>
1101                                                 <td>&#160;</td>
1102                                                 <td class='mw-input'>" .
1103                                                         Xml::checkLabel( wfMsg('revdelete-unsuppress'), 'wpUnsuppress',
1104                                                                 'mw-undelete-unsuppress', $this->mUnsuppress ).
1105                                                 "</td>
1106                                         </tr>";
1107                         } else {
1108                                 $unsuppressBox = "";
1109                         }
1110                         $table =
1111                                 Xml::fieldset( wfMsg( 'undelete-fieldset-title' ) ) .
1112                                 Xml::openElement( 'table', array( 'id' => 'mw-undelete-table' ) ) .
1113                                         "<tr>
1114                                                 <td colspan='2' class='mw-undelete-extrahelp'>" .
1115                                                         wfMsgWikiHtml( 'undeleteextrahelp' ) .
1116                                                 "</td>
1117                                         </tr>
1118                                         <tr>
1119                                                 <td class='mw-label'>" .
1120                                                         Xml::label( wfMsg( 'undeletecomment' ), 'wpComment' ) .
1121                                                 "</td>
1122                                                 <td class='mw-input'>" .
1123                                                         Xml::input( 'wpComment', 50, $this->mComment, array( 'id' =>  'wpComment' ) ) .
1124                                                 "</td>
1125                                         </tr>
1126                                         <tr>
1127                                                 <td>&#160;</td>
1128                                                 <td class='mw-submit'>" .
1129                                                         Xml::submitButton( wfMsg( 'undeletebtn' ), array( 'name' => 'restore', 'id' => 'mw-undelete-submit' ) ) . ' ' .
1130                                                         Xml::element( 'input', array( 'type' => 'reset', 'value' => wfMsg( 'undeletereset' ), 'id' => 'mw-undelete-reset' ) ) . ' ' .
1131                                                         Xml::submitButton( wfMsg( 'undeleteinvert' ), array( 'name' => 'invert', 'id' => 'mw-undelete-invert' ) ) .
1132                                                 "</td>
1133                                         </tr>" .
1134                                         $unsuppressBox .
1135                                 Xml::closeElement( 'table' ) .
1136                                 Xml::closeElement( 'fieldset' );
1137
1138                         $wgOut->addHTML( $table );
1139                 }
1140
1141                 $wgOut->addHTML( Xml::element( 'h2', null, wfMsg( 'history' ) ) . "\n" );
1142
1143                 if( $haveRevisions ) {
1144                         # The page's stored (deleted) history:
1145                         $wgOut->addHTML("<ul>");
1146                         $remaining = $revisions->numRows();
1147                         $earliestLiveTime = $this->mTargetObj->getEarliestRevTime();
1148
1149                         foreach ( $revisions as $row ) {
1150                                 $remaining--;
1151                                 $wgOut->addHTML( $this->formatRevisionRow( $row, $earliestLiveTime, $remaining, $sk ) );
1152                         }
1153                         $revisions->free();
1154                         $wgOut->addHTML("</ul>");
1155                 } else {
1156                         $wgOut->addWikiMsg( "nohistory" );
1157                 }
1158
1159                 if( $haveFiles ) {
1160                         $wgOut->addHTML( Xml::element( 'h2', null, wfMsg( 'filehist' ) ) . "\n" );
1161                         $wgOut->addHTML( "<ul>" );
1162                         foreach ( $files as $row ) {
1163                                 $wgOut->addHTML( $this->formatFileRow( $row, $sk ) );
1164                         }
1165                         $files->free();
1166                         $wgOut->addHTML( "</ul>" );
1167                 }
1168
1169                 if ( $this->mAllowed ) {
1170                         # Slip in the hidden controls here
1171                         $misc  = Html::hidden( 'target', $this->mTarget );
1172                         $misc .= Html::hidden( 'wpEditToken', $wgUser->editToken() );
1173                         $misc .= Xml::closeElement( 'form' );
1174                         $wgOut->addHTML( $misc );
1175                 }
1176
1177                 return true;
1178         }
1179
1180         private function formatRevisionRow( $row, $earliestLiveTime, $remaining, $sk ) {
1181                 global $wgUser, $wgLang;
1182
1183                 $rev = Revision::newFromArchiveRow( $row,
1184                         array( 'page' => $this->mTargetObj->getArticleId() ) );
1185                 $stxt = '';
1186                 $ts = wfTimestamp( TS_MW, $row->ar_timestamp );
1187                 // Build checkboxen...
1188                 if( $this->mAllowed ) {
1189                         if( $this->mInvert ) {
1190                                 if( in_array( $ts, $this->mTargetTimestamp ) ) {
1191                                         $checkBox = Xml::check( "ts$ts");
1192                                 } else {
1193                                         $checkBox = Xml::check( "ts$ts", true );
1194                                 }
1195                         } else {
1196                                 $checkBox = Xml::check( "ts$ts" );
1197                         }
1198                 } else {
1199                         $checkBox = '';
1200                 }
1201                 // Build page & diff links...
1202                 if( $this->mCanView ) {
1203                         $titleObj = $this->getTitle();
1204                         # Last link
1205                         if( !$rev->userCan( Revision::DELETED_TEXT ) ) {
1206                                 $pageLink = htmlspecialchars( $wgLang->timeanddate( $ts, true ) );
1207                                 $last = wfMsgHtml('diff');
1208                         } else if( $remaining > 0 || ($earliestLiveTime && $ts > $earliestLiveTime) ) {
1209                                 $pageLink = $this->getPageLink( $rev, $titleObj, $ts, $sk );
1210                                 $last = $sk->linkKnown(
1211                                         $titleObj,
1212                                         wfMsgHtml('diff'),
1213                                         array(),
1214                                         array(
1215                                                 'target' => $this->mTargetObj->getPrefixedText(),
1216                                                 'timestamp' => $ts,
1217                                                 'diff' => 'prev'
1218                                         )
1219                                 );
1220                         } else {
1221                                 $pageLink = $this->getPageLink( $rev, $titleObj, $ts, $sk );
1222                                 $last = wfMsgHtml('diff');
1223                         }
1224                 } else {
1225                         $pageLink = htmlspecialchars( $wgLang->timeanddate( $ts, true ) );
1226                         $last = wfMsgHtml('diff');
1227                 }
1228                 // User links
1229                 $userLink = $sk->revUserTools( $rev );
1230                 // Revision text size
1231                 if( !is_null($size = $row->ar_len) ) {
1232                         $stxt = $sk->formatRevisionSize( $size );
1233                 }
1234                 // Edit summary
1235                 $comment = $sk->revComment( $rev );
1236                 // Revision delete links
1237                 $canHide = $wgUser->isAllowed( 'deleterevision' );
1238                 if( $canHide || ($rev->getVisibility() && $wgUser->isAllowed('deletedhistory')) ) {
1239                         if( !$rev->userCan( Revision::DELETED_RESTRICTED ) ) {
1240                                 $revdlink = $sk->revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1241                         } else {
1242                                 $query = array(
1243                                         'type'   => 'archive',
1244                                         'target' => $this->mTargetObj->getPrefixedDBkey(),
1245                                         'ids'    => $ts
1246                                 );
1247                                 $revdlink = $sk->revDeleteLink( $query,
1248                                         $rev->isDeleted( Revision::DELETED_RESTRICTED ), $canHide );
1249                         }
1250                 } else {
1251                         $revdlink = '';
1252                 }
1253                 return "<li>$checkBox $revdlink ($last) $pageLink . . $userLink $stxt $comment</li>";
1254         }
1255
1256         private function formatFileRow( $row, $sk ) {
1257                 global $wgUser, $wgLang;
1258
1259                 $file = ArchivedFile::newFromRow( $row );
1260
1261                 $ts = wfTimestamp( TS_MW, $row->fa_timestamp );
1262                 if( $this->mAllowed && $row->fa_storage_key ) {
1263                         $checkBox = Xml::check( "fileid" . $row->fa_id );
1264                         $key = urlencode( $row->fa_storage_key );
1265                         $pageLink = $this->getFileLink( $file, $this->getTitle(), $ts, $key, $sk );
1266                 } else {
1267                         $checkBox = '';
1268                         $pageLink = $wgLang->timeanddate( $ts, true );
1269                 }
1270                 $userLink = $this->getFileUser( $file, $sk );
1271                 $data =
1272                         wfMsg( 'widthheight',
1273                                 $wgLang->formatNum( $row->fa_width ),
1274                                 $wgLang->formatNum( $row->fa_height ) ) .
1275                         ' (' .
1276                         wfMsg( 'nbytes', $wgLang->formatNum( $row->fa_size ) ) .
1277                         ')';
1278                 $data = htmlspecialchars( $data );
1279                 $comment = $this->getFileComment( $file, $sk );
1280                 // Add show/hide deletion links if available
1281                 $canHide = $wgUser->isAllowed( 'deleterevision' );
1282                 if( $canHide || ($file->getVisibility() && $wgUser->isAllowed('deletedhistory')) ) {
1283                         if( !$file->userCan(File::DELETED_RESTRICTED ) ) {
1284                                 $revdlink = $sk->revDeleteLinkDisabled( $canHide ); // revision was hidden from sysops
1285                         } else {
1286                                 $query = array(
1287                                         'type' => 'filearchive',
1288                                         'target' => $this->mTargetObj->getPrefixedDBkey(),
1289                                         'ids' => $row->fa_id
1290                                 );
1291                                 $revdlink = $sk->revDeleteLink( $query,
1292                                         $file->isDeleted( File::DELETED_RESTRICTED ), $canHide );
1293                         }
1294                 } else {
1295                         $revdlink = '';
1296                 }
1297                 return "<li>$checkBox $revdlink $pageLink . . $userLink $data $comment</li>\n";
1298         }
1299
1300         /**
1301          * Fetch revision text link if it's available to all users
1302          * @return string
1303          */
1304         function getPageLink( $rev, $titleObj, $ts, $sk ) {
1305                 global $wgLang;
1306
1307                 $time = htmlspecialchars( $wgLang->timeanddate( $ts, true ) );
1308
1309                 if( !$rev->userCan(Revision::DELETED_TEXT) ) {
1310                         return '<span class="history-deleted">' . $time . '</span>';
1311                 } else {
1312                         $link = $sk->linkKnown(
1313                                 $titleObj,
1314                                 $time,
1315                                 array(),
1316                                 array(
1317                                         'target' => $this->mTargetObj->getPrefixedText(),
1318                                         'timestamp' => $ts
1319                                 )
1320                         );
1321                         if( $rev->isDeleted(Revision::DELETED_TEXT) )
1322                                 $link = '<span class="history-deleted">' . $link . '</span>';
1323                         return $link;
1324                 }
1325         }
1326
1327         /**
1328          * Fetch image view link if it's available to all users
1329          *
1330          * @return String: HTML fragment
1331          */
1332         function getFileLink( $file, $titleObj, $ts, $key, $sk ) {
1333                 global $wgLang, $wgUser;
1334
1335                 if( !$file->userCan(File::DELETED_FILE) ) {
1336                         return '<span class="history-deleted">' . $wgLang->timeanddate( $ts, true ) . '</span>';
1337                 } else {
1338                         $link = $sk->linkKnown(
1339                                 $titleObj,
1340                                 $wgLang->timeanddate( $ts, true ),
1341                                 array(),
1342                                 array(
1343                                         'target' => $this->mTargetObj->getPrefixedText(),
1344                                         'file' => $key,
1345                                         'token' => $wgUser->editToken( $key )
1346                                 )
1347                         );
1348                         if( $file->isDeleted(File::DELETED_FILE) )
1349                                 $link = '<span class="history-deleted">' . $link . '</span>';
1350                         return $link;
1351                 }
1352         }
1353
1354         /**
1355          * Fetch file's user id if it's available to this user
1356          *
1357          * @return String: HTML fragment
1358          */
1359         function getFileUser( $file, $sk ) {
1360                 if( !$file->userCan(File::DELETED_USER) ) {
1361                         return '<span class="history-deleted">' . wfMsgHtml( 'rev-deleted-user' ) . '</span>';
1362                 } else {
1363                         $link = $sk->userLink( $file->getRawUser(), $file->getRawUserText() ) .
1364                                 $sk->userToolLinks( $file->getRawUser(), $file->getRawUserText() );
1365                         if( $file->isDeleted(File::DELETED_USER) )
1366                                 $link = '<span class="history-deleted">' . $link . '</span>';
1367                         return $link;
1368                 }
1369         }
1370
1371         /**
1372          * Fetch file upload comment if it's available to this user
1373          *
1374          * @return String: HTML fragment
1375          */
1376         function getFileComment( $file, $sk ) {
1377                 if( !$file->userCan(File::DELETED_COMMENT) ) {
1378                         return '<span class="history-deleted"><span class="comment">' . wfMsgHtml( 'rev-deleted-comment' ) . '</span></span>';
1379                 } else {
1380                         $link = $sk->commentBlock( $file->getRawDescription() );
1381                         if( $file->isDeleted(File::DELETED_COMMENT) )
1382                                 $link = '<span class="history-deleted">' . $link . '</span>';
1383                         return $link;
1384                 }
1385         }
1386
1387         function undelete() {
1388                 global $wgOut, $wgUser;
1389                 if ( wfReadOnly() ) {
1390                         $wgOut->readOnlyPage();
1391                         return;
1392                 }
1393                 if( !is_null( $this->mTargetObj ) ) {
1394                         $archive = new PageArchive( $this->mTargetObj );
1395                         $ok = $archive->undelete(
1396                                 $this->mTargetTimestamp,
1397                                 $this->mComment,
1398                                 $this->mFileVersions,
1399                                 $this->mUnsuppress );
1400
1401                         if( is_array($ok) ) {
1402                                 if ( $ok[1] ) // Undeleted file count
1403                                         wfRunHooks( 'FileUndeleteComplete', array(
1404                                                 $this->mTargetObj, $this->mFileVersions,
1405                                                 $wgUser, $this->mComment) );
1406
1407                                 $skin = $wgUser->getSkin();
1408                                 $link = $skin->linkKnown( $this->mTargetObj );
1409                                 $wgOut->addHTML( wfMsgWikiHtml( 'undeletedpage', $link ) );
1410                         } else {
1411                                 $wgOut->showFatalError( wfMsg( "cannotundelete" ) );
1412                                 $wgOut->addHTML( '<p>' . wfMsgHtml( "undeleterevdel" ) . '</p>' );
1413                         }
1414
1415                         // Show file deletion warnings and errors
1416                         $status = $archive->getFileStatus();
1417                         if( $status && !$status->isGood() ) {
1418                                 $wgOut->addWikiText( $status->getWikiText( 'undelete-error-short', 'undelete-error-long' ) );
1419                         }
1420                 } else {
1421                         $wgOut->showFatalError( wfMsg( "cannotundelete" ) );
1422                 }
1423                 return false;
1424         }
1425 }