]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/specials/SpecialRevisiondelete.php
MediaWiki 1.16.1-scripts
[autoinstallsdev/mediawiki.git] / includes / specials / SpecialRevisiondelete.php
1 <?php
2 /**
3  * Special page allowing users with the appropriate permissions to view
4  * and hide revisions. Log items can also be hidden.
5  *
6  * @file
7  * @ingroup SpecialPage
8  */
9
10 class SpecialRevisionDelete extends UnlistedSpecialPage {
11         /** Skin object */
12         var $skin;
13
14         /** True if the submit button was clicked, and the form was posted */
15         var $submitClicked;
16
17         /** Target ID list */
18         var $ids;
19
20         /** Archive name, for reviewing deleted files */
21         var $archiveName;
22
23         /** Edit token for securing image views against XSS */
24         var $token;
25
26         /** Title object for target parameter */
27         var $targetObj;
28
29         /** Deletion type, may be revision, archive, oldimage, filearchive, logging. */
30         var $typeName;
31
32         /** Array of checkbox specs (message, name, deletion bits) */
33         var $checks;
34
35         /** Information about the current type */
36         var $typeInfo;
37
38         /** The RevDel_List object, storing the list of items to be deleted/undeleted */
39         var $list;
40
41         /**
42          * Assorted information about each type, needed by the special page.
43          * TODO Move some of this to the list class
44          */
45         static $allowedTypes = array(
46                 'revision' => array(
47                         'check-label' => 'revdelete-hide-text',
48                         'deletion-bits' => Revision::DELETED_TEXT,
49                         'success' => 'revdelete-success',
50                         'failure' => 'revdelete-failure',
51                         'list-class' => 'RevDel_RevisionList',
52                 ),
53                 'archive' => array(
54                         'check-label' => 'revdelete-hide-text',
55                         'deletion-bits' => Revision::DELETED_TEXT,
56                         'success' => 'revdelete-success',
57                         'failure' => 'revdelete-failure',
58                         'list-class' => 'RevDel_ArchiveList',
59                 ),
60                 'oldimage'=> array(
61                         'check-label' => 'revdelete-hide-image',
62                         'deletion-bits' => File::DELETED_FILE,
63                         'success' => 'revdelete-success',
64                         'failure' => 'revdelete-failure',
65                         'list-class' => 'RevDel_FileList',
66                 ),
67                 'filearchive' => array(
68                         'check-label' => 'revdelete-hide-image',
69                         'deletion-bits' => File::DELETED_FILE,
70                         'success' => 'revdelete-success',
71                         'failure' => 'revdelete-failure',
72                         'list-class' => 'RevDel_ArchivedFileList',
73                 ),
74                 'logging' => array(
75                         'check-label' => 'revdelete-hide-name',
76                         'deletion-bits' => LogPage::DELETED_ACTION,
77                         'success' => 'logdelete-success',
78                         'failure' => 'logdelete-failure',
79                         'list-class' => 'RevDel_LogList',
80                 ),
81         );
82
83         /** Type map to support old log entries */
84         static $deprecatedTypeMap = array(
85                 'oldid' => 'revision',
86                 'artimestamp' => 'archive',
87                 'oldimage' => 'oldimage',
88                 'fileid' => 'filearchive',
89                 'logid' => 'logging',
90         );
91
92         public function __construct() {
93                 parent::__construct( 'Revisiondelete', 'deletedhistory' );
94         }
95
96         public function execute( $par ) {
97                 global $wgOut, $wgUser, $wgRequest;
98                 if( !$wgUser->isAllowed( 'deletedhistory' ) ) {
99                         $wgOut->permissionRequired( 'deletedhistory' );
100                         return;
101                 } else if( wfReadOnly() ) {
102                         $wgOut->readOnlyPage();
103                         return;
104                 }
105                 $this->mIsAllowed = $wgUser->isAllowed('deleterevision'); // for changes
106                 $this->skin = $wgUser->getSkin();
107                 $this->setHeaders();
108                 $this->outputHeader();
109                 $this->submitClicked = $wgRequest->wasPosted() && $wgRequest->getBool( 'wpSubmit' );
110                 # Handle our many different possible input types.
111                 $ids = $wgRequest->getVal( 'ids' );
112                 if ( !is_null( $ids ) ) {
113                         # Allow CSV, for backwards compatibility, or a single ID for show/hide links
114                         $this->ids = explode( ',', $ids );
115                 } else {
116                         # Array input
117                         $this->ids = array_keys( $wgRequest->getArray('ids',array()) );
118                 }
119                 // $this->ids = array_map( 'intval', $this->ids );
120                 $this->ids = array_unique( array_filter( $this->ids ) );
121
122                 if ( $wgRequest->getVal( 'action' ) == 'historysubmit' ) {
123                         # For show/hide form submission from history page
124                         $this->targetObj = $GLOBALS['wgTitle'];
125                         $this->typeName = 'revision';
126                 } else {
127                         $this->typeName = $wgRequest->getVal( 'type' );
128                         $this->targetObj = Title::newFromText( $wgRequest->getText( 'target' ) );
129                 }
130
131                 # For reviewing deleted files...
132                 $this->archiveName = $wgRequest->getVal( 'file' );
133                 $this->token = $wgRequest->getVal( 'token' );
134                 if ( $this->archiveName && $this->targetObj ) {
135                         $this->tryShowFile( $this->archiveName );
136                         return;
137                 }
138
139                 if ( isset( self::$deprecatedTypeMap[$this->typeName] ) ) {
140                         $this->typeName = self::$deprecatedTypeMap[$this->typeName];
141                 }
142
143                 # No targets?
144                 if( !isset( self::$allowedTypes[$this->typeName] ) || count( $this->ids ) == 0 ) {
145                         $wgOut->showErrorPage( 'revdelete-nooldid-title', 'revdelete-nooldid-text' );
146                         return;
147                 }
148                 $this->typeInfo = self::$allowedTypes[$this->typeName];
149
150                 # If we have revisions, get the title from the first one
151                 # since they should all be from the same page. This allows 
152                 # for more flexibility with page moves...
153                 if( $this->typeName == 'revision' ) {
154                         $rev = Revision::newFromId( $this->ids[0] );
155                         $this->targetObj = $rev ? $rev->getTitle() : $this->targetObj;
156                 }
157                 
158                 $this->otherReason = $wgRequest->getVal( 'wpReason' );
159                 # We need a target page!
160                 if( is_null($this->targetObj) ) {
161                         $wgOut->addWikiMsg( 'undelete-header' );
162                         return;
163                 }
164                 # Give a link to the logs/hist for this page
165                 $this->showConvenienceLinks();
166
167                 # Initialise checkboxes
168                 $this->checks = array(
169                         array( $this->typeInfo['check-label'], 'wpHidePrimary', $this->typeInfo['deletion-bits'] ),
170                         array( 'revdelete-hide-comment', 'wpHideComment', Revision::DELETED_COMMENT ),
171                         array( 'revdelete-hide-user', 'wpHideUser', Revision::DELETED_USER )
172                 );
173                 if( $wgUser->isAllowed('suppressrevision') ) {
174                         $this->checks[] = array( 'revdelete-hide-restricted',
175                                 'wpHideRestricted', Revision::DELETED_RESTRICTED );
176                 }
177
178                 # Either submit or create our form
179                 if( $this->mIsAllowed && $this->submitClicked ) {
180                         $this->submit( $wgRequest );
181                 } else {
182                         $this->showForm();
183                 }
184                 
185                 $qc = $this->getLogQueryCond();
186                 # Show relevant lines from the deletion log
187                 $wgOut->addHTML( "<h2>" . htmlspecialchars( LogPage::logName( 'delete' ) ) . "</h2>\n" );
188                 LogEventsList::showLogExtract( $wgOut, 'delete',
189                         $this->targetObj->getPrefixedText(), '', array( 'lim' => 25, 'conds' => $qc ) );
190                 # Show relevant lines from the suppression log
191                 if( $wgUser->isAllowed( 'suppressionlog' ) ) {
192                         $wgOut->addHTML( "<h2>" . htmlspecialchars( LogPage::logName( 'suppress' ) ) . "</h2>\n" );
193                         LogEventsList::showLogExtract( $wgOut, 'suppress',
194                                 $this->targetObj->getPrefixedText(), '', array( 'lim' => 25, 'conds' => $qc ) );
195                 }
196         }
197
198         /**
199          * Show some useful links in the subtitle
200          */
201         protected function showConvenienceLinks() {
202                 global $wgOut, $wgUser, $wgLang;
203                 # Give a link to the logs/hist for this page
204                 if( $this->targetObj ) {
205                         $links = array();
206                         $links[] = $this->skin->linkKnown(
207                                 SpecialPage::getTitleFor( 'Log' ),
208                                 wfMsgHtml( 'viewpagelogs' ),
209                                 array(),
210                                 array( 'page' => $this->targetObj->getPrefixedText() )
211                         );
212                         if ( $this->targetObj->getNamespace() != NS_SPECIAL ) {
213                                 # Give a link to the page history
214                                 $links[] = $this->skin->linkKnown(
215                                         $this->targetObj,
216                                         wfMsgHtml( 'pagehist' ),
217                                         array(),
218                                         array( 'action' => 'history' )
219                                 );
220                                 # Link to deleted edits
221                                 if( $wgUser->isAllowed('undelete') ) {
222                                         $undelete = SpecialPage::getTitleFor( 'Undelete' );
223                                         $links[] = $this->skin->linkKnown(
224                                                 $undelete,
225                                                 wfMsgHtml( 'deletedhist' ),
226                                                 array(),
227                                                 array( 'target' => $this->targetObj->getPrefixedDBkey() )
228                                         );
229                                 }
230                         }
231                         # Logs themselves don't have histories or archived revisions
232                         $wgOut->setSubtitle( '<p>' . $wgLang->pipeList( $links ) . '</p>' );
233                 }
234         }
235
236         /**
237          * Get the condition used for fetching log snippets
238          */
239         protected function getLogQueryCond() {
240                 $conds = array();
241                 // Revision delete logs for these item
242                 $conds['log_type'] = array('delete','suppress');
243                 $conds['log_action'] = $this->getList()->getLogAction();
244                 $conds['ls_field'] = RevisionDeleter::getRelationType( $this->typeName );
245                 $conds['ls_value'] = $this->ids;
246                 return $conds;
247         }
248
249         /**
250          * Show a deleted file version requested by the visitor.
251          * TODO Mostly copied from Special:Undelete. Refactor.
252          */
253         protected function tryShowFile( $archiveName ) {
254                 global $wgOut, $wgRequest, $wgUser, $wgLang;
255
256                 $repo = RepoGroup::singleton()->getLocalRepo();
257                 $oimage = $repo->newFromArchiveName( $this->targetObj, $archiveName );
258                 $oimage->load();
259                 // Check if user is allowed to see this file
260                 if ( !$oimage->exists() ) {
261                         $wgOut->addWikiMsg( 'revdelete-no-file' );
262                         return;
263                 }
264                 if( !$oimage->userCan(File::DELETED_FILE) ) {
265                         if( $oimage->isDeleted( File::DELETED_RESTRICTED ) ) {
266                                 $wgOut->permissionRequired( 'suppressrevision' );
267                         } else {
268                                 $wgOut->permissionRequired( 'deletedtext' );
269                         }
270                         return;
271                 }
272                 if ( !$wgUser->matchEditToken( $this->token, $archiveName ) ) {
273                         $wgOut->addWikiMsg( 'revdelete-show-file-confirm',
274                                 $this->targetObj->getText(),
275                                 $wgLang->date( $oimage->getTimestamp() ),
276                                 $wgLang->time( $oimage->getTimestamp() ) );
277                         $wgOut->addHTML(
278                                 Xml::openElement( 'form', array(
279                                         'method' => 'POST',
280                                         'action' => $this->getTitle()->getLocalUrl(
281                                                 'target=' . urlencode( $oimage->getName() ) .
282                                                 '&file=' . urlencode( $archiveName ) .
283                                                 '&token=' . urlencode( $wgUser->editToken( $archiveName ) ) )
284                                         )
285                                 ) .
286                                 Xml::submitButton( wfMsg( 'revdelete-show-file-submit' ) ) .
287                                 '</form>'
288                         );
289                         return;
290                 }
291                 $wgOut->disable();
292                 # We mustn't allow the output to be Squid cached, otherwise
293                 # if an admin previews a deleted image, and it's cached, then
294                 # a user without appropriate permissions can toddle off and
295                 # nab the image, and Squid will serve it
296                 $wgRequest->response()->header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', 0 ) . ' GMT' );
297                 $wgRequest->response()->header( 'Cache-Control: no-cache, no-store, max-age=0, must-revalidate' );
298                 $wgRequest->response()->header( 'Pragma: no-cache' );
299
300                 # Stream the file to the client
301                 global $IP;
302                 require_once( "$IP/includes/StreamFile.php" );
303                 $key = $oimage->getStorageKey();
304                 $path = $repo->getZonePath( 'deleted' ) . '/' . $repo->getDeletedHashPath( $key ) . $key;
305                 wfStreamFile( $path );
306         }
307
308         /**
309          * Get the list object for this request
310          */
311         protected function getList() {
312                 if ( is_null( $this->list ) ) {
313                         $class = $this->typeInfo['list-class'];
314                         $this->list = new $class( $this, $this->targetObj, $this->ids );
315                 }
316                 return $this->list;
317         }
318
319         /**
320          * Show a list of items that we will operate on, and show a form with checkboxes 
321          * which will allow the user to choose new visibility settings.
322          */
323         protected function showForm() {
324                 global $wgOut, $wgUser, $wgLang;
325                 $UserAllowed = true;
326
327                 if ( $this->typeName == 'logging' ) {
328                         $wgOut->addWikiMsg( 'logdelete-selected', $wgLang->formatNum( count($this->ids) ) );
329                 } else {
330                         $wgOut->addWikiMsg( 'revdelete-selected',
331                                 $this->targetObj->getPrefixedText(), count( $this->ids ) );
332                 }
333
334                 $wgOut->addHTML( "<ul>" );
335
336                 $where = $revObjs = array();
337                 
338                 $numRevisions = 0;
339                 // Live revisions...
340                 $list = $this->getList();
341                 for ( $list->reset(); $list->current(); $list->next() ) {
342                         $item = $list->current();
343                         if ( !$item->canView() ) {
344                                 if( !$this->submitClicked ) {
345                                         $wgOut->permissionRequired( 'suppressrevision' );
346                                         return;
347                                 }
348                                 $UserAllowed = false;
349                         }
350                         $numRevisions++;
351                         $wgOut->addHTML( $item->getHTML() );
352                 }
353
354                 if( !$numRevisions ) {
355                         $wgOut->showErrorPage( 'revdelete-nooldid-title', 'revdelete-nooldid-text' );
356                         return;
357                 }
358                 
359                 $wgOut->addHTML( "</ul>" );
360                 // Explanation text
361                 $this->addUsageText();
362
363                 // Normal sysops can always see what they did, but can't always change it
364                 if( !$UserAllowed ) return;
365
366                 // Show form if the user can submit
367                 if( $this->mIsAllowed ) {
368                         $out = Xml::openElement( 'form', array( 'method' => 'post',
369                                         'action' => $this->getTitle()->getLocalUrl( array( 'action' => 'submit' ) ), 
370                                         'id' => 'mw-revdel-form-revisions' ) ) .
371                                 Xml::fieldset( wfMsg( 'revdelete-legend' ) ) .
372                                 $this->buildCheckBoxes() .
373                                 Xml::openElement( 'table' ) .
374                                 "<tr>\n" .
375                                         '<td class="mw-label">' .
376                                                 Xml::label( wfMsg( 'revdelete-log' ), 'wpRevDeleteReasonList' ) .
377                                         '</td>' .
378                                         '<td class="mw-input">' .
379                                                 Xml::listDropDown( 'wpRevDeleteReasonList',
380                                                         wfMsgForContent( 'revdelete-reason-dropdown' ),
381                                                         wfMsgForContent( 'revdelete-reasonotherlist' ), '', 'wpReasonDropDown', 1
382                                                 ) .
383                                         '</td>' .
384                                 "</tr><tr>\n" .
385                                         '<td class="mw-label">' .
386                                                 Xml::label( wfMsg( 'revdelete-otherreason' ), 'wpReason' ) .
387                                         '</td>' .
388                                         '<td class="mw-input">' .
389                                                 Xml::input( 'wpReason', 60, $this->otherReason, array( 'id' => 'wpReason' ) ) .
390                                         '</td>' .
391                                 "</tr><tr>\n" .
392                                         '<td></td>' .
393                                         '<td class="mw-submit">' .
394                                                 Xml::submitButton( wfMsgExt('revdelete-submit','parsemag',$numRevisions),
395                                                         array( 'name' => 'wpSubmit' ) ) .
396                                         '</td>' .
397                                 "</tr>\n" .
398                                 Xml::closeElement( 'table' ) .
399                                 Xml::hidden( 'wpEditToken', $wgUser->editToken() ) .
400                                 Xml::hidden( 'target', $this->targetObj->getPrefixedText() ) .
401                                 Xml::hidden( 'type', $this->typeName ) .
402                                 Xml::hidden( 'ids', implode( ',', $this->ids ) ) .
403                                 Xml::closeElement( 'fieldset' ) . "\n";
404                 } else {
405                         $out = '';
406                 }
407                 if( $this->mIsAllowed ) {
408                         $out .= Xml::closeElement( 'form' ) . "\n";
409                         // Show link to edit the dropdown reasons
410                         if( $wgUser->isAllowed( 'editinterface' ) ) {
411                                 $title = Title::makeTitle( NS_MEDIAWIKI, 'revdelete-reason-dropdown' );
412                                 $link = $wgUser->getSkin()->link(
413                                         $title,
414                                         wfMsgHtml( 'revdelete-edit-reasonlist' ),
415                                         array(),
416                                         array( 'action' => 'edit' )
417                                 );
418                                 $out .= Xml::tags( 'p', array( 'class' => 'mw-revdel-editreasons' ), $link ) . "\n";
419                         }
420                 }
421                 $wgOut->addHTML( $out );
422         }
423
424         /**
425          * Show some introductory text
426          * FIXME Wikimedia-specific policy text
427          */
428         protected function addUsageText() {
429                 global $wgOut, $wgUser;
430                 $wgOut->addWikiMsg( 'revdelete-text' );
431                 if( $wgUser->isAllowed( 'suppressrevision' ) ) {
432                         $wgOut->addWikiMsg( 'revdelete-suppress-text' );
433                 }
434                 if( $this->mIsAllowed ) {
435                         $wgOut->addWikiMsg( 'revdelete-confirm' );
436                 }
437         }
438         
439         /**
440         * @return String: HTML
441         */
442         protected function buildCheckBoxes() {
443                 global $wgRequest;
444
445                 $html = '<table>';
446                 // If there is just one item, use checkboxes
447                 $list = $this->getList();
448                 if( $list->length() == 1 ) {
449                         $list->reset();
450                         $bitfield = $list->current()->getBits(); // existing field
451                         if( $this->submitClicked ) {
452                                 $bitfield = $this->extractBitfield( $this->extractBitParams($wgRequest), $bitfield );
453                         }
454                         foreach( $this->checks as $item ) {
455                                 list( $message, $name, $field ) = $item;
456                                 $innerHTML = Xml::checkLabel( wfMsg($message), $name, $name, $bitfield & $field );
457                                 if( $field == Revision::DELETED_RESTRICTED )
458                                         $innerHTML = "<b>$innerHTML</b>";
459                                 $line = Xml::tags( 'td', array( 'class' => 'mw-input' ), $innerHTML );
460                                 $html .= "<tr>$line</tr>\n";
461                         }
462                 // Otherwise, use tri-state radios
463                 } else {
464                         $html .= '<tr>';
465                         $html .= '<th class="mw-revdel-checkbox">'.wfMsgHtml('revdelete-radio-same').'</th>';
466                         $html .= '<th class="mw-revdel-checkbox">'.wfMsgHtml('revdelete-radio-unset').'</th>';
467                         $html .= '<th class="mw-revdel-checkbox">'.wfMsgHtml('revdelete-radio-set').'</th>';
468                         $html .= "<th></th></tr>\n";
469                         foreach( $this->checks as $item ) {
470                                 list( $message, $name, $field ) = $item;
471                                 // If there are several items, use third state by default...
472                                 if( $this->submitClicked ) {
473                                         $selected = $wgRequest->getInt( $name, 0 /* unchecked */ );
474                                 } else {
475                                         $selected = -1; // use existing field
476                                 }
477                                 $line = '<td class="mw-revdel-checkbox">' . Xml::radio( $name, -1, $selected == -1 ) . '</td>';
478                                 $line .= '<td class="mw-revdel-checkbox">' . Xml::radio( $name, 0, $selected == 0 ) . '</td>';
479                                 $line .= '<td class="mw-revdel-checkbox">' . Xml::radio( $name, 1, $selected == 1 ) . '</td>';
480                                 $label = wfMsgHtml($message);
481                                 if( $field == Revision::DELETED_RESTRICTED ) {
482                                         $label = "<b>$label</b>";
483                                 }
484                                 $line .= "<td>$label</td>";
485                                 $html .= "<tr>$line</tr>\n";
486                         }
487                 }
488                 
489                 $html .= '</table>';
490                 return $html;
491         }
492
493         /**
494          * UI entry point for form submission.
495          * @param $request WebRequest
496          */
497         protected function submit( $request ) {
498                 global $wgUser, $wgOut;
499                 # Check edit token on submission
500                 if( $this->submitClicked && !$wgUser->matchEditToken( $request->getVal('wpEditToken') ) ) {
501                         $wgOut->addWikiMsg( 'sessionfailure' );
502                         return false;
503                 }
504                 $bitParams = $this->extractBitParams( $request );
505                 $listReason = $request->getText( 'wpRevDeleteReasonList', 'other' ); // from dropdown
506                 $comment = $listReason;
507                 if( $comment != 'other' && $this->otherReason != '' ) {
508                         // Entry from drop down menu + additional comment
509                         $comment .= wfMsgForContent( 'colon-separator' ) . $this->otherReason;
510                 } elseif( $comment == 'other' ) {
511                         $comment = $this->otherReason;
512                 }
513                 # Can the user set this field?
514                 if( $bitParams[Revision::DELETED_RESTRICTED]==1 && !$wgUser->isAllowed('suppressrevision') ) {
515                         $wgOut->permissionRequired( 'suppressrevision' );
516                         return false;
517                 }
518                 # If the save went through, go to success message...
519                 $status = $this->save( $bitParams, $comment, $this->targetObj );
520                 if ( $status->isGood() ) {
521                         $this->success();
522                         return true;
523                 # ...otherwise, bounce back to form...
524                 } else {
525                         $this->failure( $status );
526                 }
527                 return false;
528         }
529
530         /**
531          * Report that the submit operation succeeded
532          */
533         protected function success() {
534                 global $wgOut;
535                 $wgOut->setPagetitle( wfMsg( 'actioncomplete' ) );
536                 $wgOut->wrapWikiMsg( '<span class="success">$1</span>', $this->typeInfo['success'] );
537                 $this->list->reloadFromMaster();
538                 $this->showForm();
539         }
540
541         /**
542          * Report that the submit operation failed
543          */
544         protected function failure( $status ) {
545                 global $wgOut;
546                 $wgOut->setPagetitle( wfMsg( 'actionfailed' ) );
547                 $wgOut->addWikiText( $status->getWikiText( $this->typeInfo['failure'] ) );
548                 $this->showForm();
549         }
550
551         /**
552          * Put together an array that contains -1, 0, or the *_deleted const for each bit
553          * @param $request WebRequest
554          * @return array
555          */
556         protected function extractBitParams( $request ) {
557                 $bitfield = array();
558                 foreach( $this->checks as $item ) {
559                         list( /* message */ , $name, $field ) = $item;
560                         $val = $request->getInt( $name, 0 /* unchecked */ );
561                         if( $val < -1 || $val > 1) {
562                                 $val = -1; // -1 for existing value
563                         }
564                         $bitfield[$field] = $val;
565                 }
566                 if( !isset($bitfield[Revision::DELETED_RESTRICTED]) ) {
567                         $bitfield[Revision::DELETED_RESTRICTED] = 0;
568                 }
569                 return $bitfield;
570         }
571         
572         /**
573          * Put together a rev_deleted bitfield
574          * @param $bitPars array extractBitParams() params
575          * @param $oldfield int current bitfield
576          * @return array
577          */
578         public static function extractBitfield( $bitPars, $oldfield ) {
579                 // Build the actual new rev_deleted bitfield
580                 $newBits = 0;
581                 foreach( $bitPars as $const => $val ) {
582                         if( $val == 1 ) {
583                                 $newBits |= $const; // $const is the *_deleted const
584                         } else if( $val == -1 ) {
585                                 $newBits |= ($oldfield & $const); // use existing
586                         }
587                 }
588                 return $newBits;
589         }
590
591         /**
592          * Do the write operations. Simple wrapper for RevDel_*List::setVisibility().
593          */
594         protected function save( $bitfield, $reason, $title ) {
595                 return $this->getList()->setVisibility(
596                         array( 'value' => $bitfield, 'comment' => $reason )
597                 );
598         }
599 }
600
601 /**
602  * Temporary b/c interface, collection of static functions.
603  * @ingroup SpecialPage
604  */
605 class RevisionDeleter {
606         /**
607          * Checks for a change in the bitfield for a certain option and updates the
608          * provided array accordingly.
609          *
610          * @param $desc String: description to add to the array if the option was
611          * enabled / disabled.
612          * @param $field Integer: the bitmask describing the single option.
613          * @param $diff Integer: the xor of the old and new bitfields.
614          * @param $new Integer: the new bitfield 
615          * @param $arr Array: the array to update.
616          */
617         protected static function checkItem( $desc, $field, $diff, $new, &$arr ) {
618                 if( $diff & $field ) {
619                         $arr[ ( $new & $field ) ? 0 : 1 ][] = $desc;
620                 }
621         }
622
623         /**
624          * Gets an array describing the changes made to the visibilit of the revision.
625          * If the resulting array is $arr, then $arr[0] will contain an array of strings
626          * describing the items that were hidden, $arr[2] will contain an array of strings
627          * describing the items that were unhidden, and $arr[3] will contain an array with
628          * a single string, which can be one of "applied restrictions to sysops",
629          * "removed restrictions from sysops", or null.
630          *
631          * @param $n Integer: the new bitfield.
632          * @param $o Integer: the old bitfield.
633          * @return An array as described above.
634          */
635         protected static function getChanges( $n, $o ) {
636                 $diff = $n ^ $o;
637                 $ret = array( 0 => array(), 1 => array(), 2 => array() );
638                 // Build bitfield changes in language
639                 self::checkItem( wfMsgForContent( 'revdelete-content' ),
640                         Revision::DELETED_TEXT, $diff, $n, $ret );
641                 self::checkItem( wfMsgForContent( 'revdelete-summary' ),
642                         Revision::DELETED_COMMENT, $diff, $n, $ret );
643                 self::checkItem( wfMsgForContent( 'revdelete-uname' ),
644                         Revision::DELETED_USER, $diff, $n, $ret );
645                 // Restriction application to sysops
646                 if( $diff & Revision::DELETED_RESTRICTED ) {
647                         if( $n & Revision::DELETED_RESTRICTED )
648                                 $ret[2][] = wfMsgForContent( 'revdelete-restricted' );
649                         else
650                                 $ret[2][] = wfMsgForContent( 'revdelete-unrestricted' );
651                 }
652                 return $ret;
653         }
654
655         /**
656          * Gets a log message to describe the given revision visibility change. This
657          * message will be of the form "[hid {content, edit summary, username}];
658          * [unhid {...}][applied restrictions to sysops] for $count revisions: $comment".
659          *
660          * @param $count Integer: The number of effected revisions.
661          * @param $nbitfield Integer: The new bitfield for the revision.
662          * @param $obitfield Integer: The old bitfield for the revision.
663          * @param $isForLog Boolean
664          */
665         public static function getLogMessage( $count, $nbitfield, $obitfield, $isForLog = false ) {
666                 global $wgLang;
667                 $s = '';
668                 $changes = self::getChanges( $nbitfield, $obitfield );
669                 if( count( $changes[0] ) ) {
670                         $s .= wfMsgForContent( 'revdelete-hid', implode( ', ', $changes[0] ) );
671                 }
672                 if( count( $changes[1] ) ) {
673                         if ($s) $s .= '; ';
674                         $s .= wfMsgForContent( 'revdelete-unhid', implode( ', ', $changes[1] ) );
675                 }
676                 if( count( $changes[2] ) ) {
677                         $s .= $s ? ' (' . $changes[2][0] . ')' : $changes[2][0];
678                 }
679                 $msg = $isForLog ? 'logdelete-log-message' : 'revdelete-log-message';
680                 return wfMsgExt( $msg, array( 'parsemag', 'content' ), $s, $wgLang->formatNum($count) );
681
682         }
683         
684         // Get DB field name for URL param...
685         // Future code for other things may also track
686         // other types of revision-specific changes.
687         // @returns string One of log_id/rev_id/fa_id/ar_timestamp/oi_archive_name
688         public static function getRelationType( $typeName ) {
689                 if ( isset( SpecialRevisionDelete::$deprecatedTypeMap[$typeName] ) ) {
690                         $typeName = SpecialRevisionDelete::$deprecatedTypeMap[$typeName];
691                 }
692                 if ( isset( SpecialRevisionDelete::$allowedTypes[$typeName] ) ) {
693                         $class = SpecialRevisionDelete::$allowedTypes[$typeName]['list-class'];
694                         $list = new $class( null, null, null );
695                         return $list->getIdField();
696                 } else {
697                         return null;
698                 }
699         }
700 }
701
702 /**
703  * Abstract base class for a list of deletable items
704  */
705 abstract class RevDel_List {
706         var $special, $title, $ids, $res, $current;
707         var $type = null; // override this
708         var $idField = null; // override this
709         var $dateField = false; // override this
710         var $authorIdField = false; // override this
711         var $authorNameField = false; // override this
712
713         /**
714          * @param $special The parent SpecialPage
715          * @param $title The target title
716          * @param $ids Array of IDs
717          */
718         public function __construct( $special, $title, $ids ) {
719                 $this->special = $special;
720                 $this->title = $title;
721                 $this->ids = $ids;
722         }
723
724         /**
725          * Get the internal type name of this list. Equal to the table name.
726          */
727         public function getType() {
728                 return $this->type;
729         }
730
731         /**
732          * Get the DB field name associated with the ID list
733          */
734         public function getIdField() {
735                 return $this->idField;
736         }
737
738         /**
739          * Get the DB field name storing timestamps
740          */
741         public function getTimestampField() {
742                 return $this->dateField;
743         }
744
745         /**
746          * Get the DB field name storing user ids
747          */
748         public function getAuthorIdField() {
749                 return $this->authorIdField;
750         }
751
752         /**
753          * Get the DB field name storing user names
754          */
755         public function getAuthorNameField() {
756                 return $this->authorNameField;
757         }
758         /**
759          * Set the visibility for the revisions in this list. Logging and 
760          * transactions are done here.
761          *
762          * @param $params Associative array of parameters. Members are:
763          *     value:       The integer value to set the visibility to
764          *     comment:     The log comment.
765          * @return Status
766          */
767         public function setVisibility( $params ) {
768                 $bitPars = $params['value'];
769                 $comment = $params['comment'];
770
771                 $this->res = false;
772                 $dbw = wfGetDB( DB_MASTER );
773                 $this->doQuery( $dbw );
774                 $dbw->begin();
775                 $status = Status::newGood();
776                 $missing = array_flip( $this->ids );
777                 $this->clearFileOps();
778                 $idsForLog = array();
779                 $authorIds = $authorIPs = array();
780
781                 for ( $this->reset(); $this->current(); $this->next() ) {
782                         $item = $this->current();
783                         unset( $missing[ $item->getId() ] );
784
785                         $oldBits = $item->getBits();
786                         // Build the actual new rev_deleted bitfield
787                         $newBits = SpecialRevisionDelete::extractBitfield( $bitPars, $oldBits );
788
789                         if ( $oldBits == $newBits ) {
790                                 $status->warning( 'revdelete-no-change', $item->formatDate(), $item->formatTime() );
791                                 $status->failCount++;
792                                 continue;
793                         } elseif ( $oldBits == 0 && $newBits != 0 ) {
794                                 $opType = 'hide';
795                         } elseif ( $oldBits != 0 && $newBits == 0 ) {
796                                 $opType = 'show';
797                         } else {
798                                 $opType = 'modify';
799                         }
800
801                         if ( $item->isHideCurrentOp( $newBits ) ) {
802                                 // Cannot hide current version text
803                                 $status->error( 'revdelete-hide-current', $item->formatDate(), $item->formatTime() );
804                                 $status->failCount++;
805                                 continue;
806                         }
807                         if ( !$item->canView() ) {
808                                 // Cannot access this revision
809                                 $msg = ($opType == 'show') ?
810                                         'revdelete-show-no-access' : 'revdelete-modify-no-access';
811                                 $status->error( $msg, $item->formatDate(), $item->formatTime() );
812                                 $status->failCount++;
813                                 continue;
814                         }
815                         // Cannot just "hide from Sysops" without hiding any fields
816                         if( $newBits == Revision::DELETED_RESTRICTED ) {
817                                 $status->warning( 'revdelete-only-restricted', $item->formatDate(), $item->formatTime() );
818                                 $status->failCount++;
819                                 continue;
820                         } 
821
822                         // Update the revision
823                         $ok = $item->setBits( $newBits );
824
825                         if ( $ok ) {
826                                 $idsForLog[] = $item->getId();
827                                 $status->successCount++;
828                                 if( $item->getAuthorId() > 0 ) {
829                                         $authorIds[] = $item->getAuthorId();
830                                 } else if( IP::isIPAddress( $item->getAuthorName() ) ) {
831                                         $authorIPs[] = $item->getAuthorName();
832                                 }
833                         } else {
834                                 $status->error( 'revdelete-concurrent-change', $item->formatDate(), $item->formatTime() );
835                                 $status->failCount++;
836                         }
837                 }
838
839                 // Handle missing revisions
840                 foreach ( $missing as $id => $unused ) {
841                         $status->error( 'revdelete-modify-missing', $id );
842                         $status->failCount++;
843                 }
844
845                 if ( $status->successCount == 0 ) {
846                         $status->ok = false;
847                         $dbw->rollback();
848                         return $status;
849                 }
850
851                 // Save success count 
852                 $successCount = $status->successCount;
853
854                 // Move files, if there are any
855                 $status->merge( $this->doPreCommitUpdates() );
856                 if ( !$status->isOK() ) {
857                         // Fatal error, such as no configured archive directory
858                         $dbw->rollback();
859                         return $status;
860                 }
861
862                 // Log it
863                 $this->updateLog( array(
864                         'title' => $this->title, 
865                         'count' => $successCount, 
866                         'newBits' => $newBits, 
867                         'oldBits' => $oldBits,
868                         'comment' => $comment,
869                         'ids' => $idsForLog,
870                         'authorIds' => $authorIds,
871                         'authorIPs' => $authorIPs
872                 ) );
873                 $dbw->commit();
874
875                 // Clear caches
876                 $status->merge( $this->doPostCommitUpdates() );
877                 return $status;
878         }
879
880         /**
881          * Reload the list data from the master DB. This can be done after setVisibility()
882          * to allow $item->getHTML() to show the new data.
883          */
884         function reloadFromMaster() {
885                 $dbw = wfGetDB( DB_MASTER );
886                 $this->res = $this->doQuery( $dbw );
887         }
888
889         /**
890          * Record a log entry on the action
891          * @param $params Associative array of parameters:
892          *     newBits:         The new value of the *_deleted bitfield
893          *     oldBits:         The old value of the *_deleted bitfield. 
894          *     title:           The target title
895          *     ids:             The ID list
896          *     comment:         The log comment
897          *     authorsIds:      The array of the user IDs of the offenders
898          *     authorsIPs:      The array of the IP/anon user offenders
899          */
900         protected function updateLog( $params ) {
901                 // Get the URL param's corresponding DB field
902                 $field = RevisionDeleter::getRelationType( $this->getType() );
903                 if( !$field ) {
904                         throw new MWException( "Bad log URL param type!" );
905                 }
906                 // Put things hidden from sysops in the oversight log
907                 if ( ( $params['newBits'] | $params['oldBits'] ) & $this->getSuppressBit() ) {
908                         $logType = 'suppress';
909                 } else {
910                         $logType = 'delete';
911                 }
912                 // Add params for effected page and ids
913                 $logParams = $this->getLogParams( $params );
914                 // Actually add the deletion log entry
915                 $log = new LogPage( $logType );
916                 $logid = $log->addEntry( $this->getLogAction(), $params['title'],
917                         $params['comment'], $logParams );
918                 // Allow for easy searching of deletion log items for revision/log items
919                 $log->addRelations( $field, $params['ids'], $logid );
920                 $log->addRelations( 'target_author_id', $params['authorIds'], $logid );
921                 $log->addRelations( 'target_author_ip', $params['authorIPs'], $logid );
922         }
923
924         /**
925          * Get the log action for this list type
926          */
927         public function getLogAction() {
928                 return 'revision';
929         }
930
931         /**
932          * Get log parameter array.
933          * @param $params Associative array of log parameters, same as updateLog()
934          * @return array
935          */
936         public function getLogParams( $params ) {
937                 return array(
938                         $this->getType(),
939                         implode( ',', $params['ids'] ),
940                         "ofield={$params['oldBits']}",
941                         "nfield={$params['newBits']}"
942                 );
943         }
944
945         /**
946          * Initialise the current iteration pointer
947          */
948         protected function initCurrent() {
949                 $row = $this->res->current();
950                 if ( $row ) {
951                         $this->current = $this->newItem( $row );
952                 } else {
953                         $this->current = false;
954                 }
955         }
956
957         /**
958          * Start iteration. This must be called before current() or next(). 
959          * @return First list item
960          */
961         public function reset() {
962                 if ( !$this->res ) {
963                         $this->res = $this->doQuery( wfGetDB( DB_SLAVE ) );
964                 } else {
965                         $this->res->rewind();
966                 }
967                 $this->initCurrent();
968                 return $this->current;
969         }
970
971         /**
972          * Get the current list item, or false if we are at the end
973          */
974         public function current() {
975                 return $this->current;
976         }
977
978         /**
979          * Move the iteration pointer to the next list item, and return it.
980          */
981         public function next() {
982                 $this->res->next();
983                 $this->initCurrent();
984                 return $this->current;
985         }
986         
987         /**
988          * Get the number of items in the list.
989          */
990         public function length() {
991                 if( !$this->res ) {
992                         return 0;
993                 } else {
994                         return $this->res->numRows();
995                 }
996         }
997
998         /**
999          * Clear any data structures needed for doPreCommitUpdates() and doPostCommitUpdates()
1000          * STUB
1001          */
1002         public function clearFileOps() {
1003         }
1004
1005         /** 
1006          * A hook for setVisibility(): do batch updates pre-commit.
1007          * STUB
1008          * @return Status
1009          */
1010         public function doPreCommitUpdates() {
1011                 return Status::newGood();
1012         }
1013
1014         /**
1015          * A hook for setVisibility(): do any necessary updates post-commit. 
1016          * STUB
1017          * @return Status 
1018          */
1019         public function doPostCommitUpdates() {
1020                 return Status::newGood();
1021         }
1022
1023         /**
1024          * Create an item object from a DB result row
1025          * @param $row stdclass
1026          */
1027         abstract public function newItem( $row );
1028
1029         /**
1030          * Do the DB query to iterate through the objects.
1031          * @param $db Database object to use for the query
1032          */
1033         abstract public function doQuery( $db );
1034
1035         /**
1036          * Get the integer value of the flag used for suppression
1037          */
1038         abstract public function getSuppressBit();
1039 }
1040
1041 /**
1042  * Abstract base class for deletable items
1043  */
1044 abstract class RevDel_Item {
1045         /** The parent SpecialPage */
1046         var $special;
1047
1048         /** The parent RevDel_List */
1049         var $list;
1050
1051         /** The DB result row */
1052         var $row;
1053
1054         /** 
1055          * @param $list RevDel_List
1056          * @param $row DB result row
1057          */
1058         public function __construct( $list, $row ) {
1059                 $this->special = $list->special;
1060                 $this->list = $list;
1061                 $this->row = $row;
1062         }
1063
1064         /**
1065          * Get the ID, as it would appear in the ids URL parameter
1066          */
1067         public function getId() {
1068                 $field = $this->list->getIdField();
1069                 return $this->row->$field;
1070         }
1071
1072         /**
1073          * Get the date, formatted with $wgLang
1074          */
1075         public function formatDate() {
1076                 global $wgLang;
1077                 return $wgLang->date( $this->getTimestamp() );
1078         }
1079
1080         /**
1081          * Get the time, formatted with $wgLang
1082          */
1083         public function formatTime() {
1084                 global $wgLang;
1085                 return $wgLang->time( $this->getTimestamp() );
1086         }
1087
1088         /**
1089          * Get the timestamp in MW 14-char form
1090          */
1091         public function getTimestamp() {
1092                 $field = $this->list->getTimestampField();
1093                 return wfTimestamp( TS_MW, $this->row->$field );
1094         }
1095         
1096         /**
1097          * Get the author user ID
1098          */     
1099         public function getAuthorId() {
1100                 $field = $this->list->getAuthorIdField();
1101                 return intval( $this->row->$field );
1102         }
1103
1104         /**
1105          * Get the author user name
1106          */     
1107         public function getAuthorName() {
1108                 $field = $this->list->getAuthorNameField();
1109                 return strval( $this->row->$field );
1110         }
1111
1112         /** 
1113          * Returns true if the item is "current", and the operation to set the given
1114          * bits can't be executed for that reason
1115          * STUB
1116          */
1117         public function isHideCurrentOp( $newBits ) {
1118                 return false;
1119         }
1120
1121         /**
1122          * Returns true if the current user can view the item
1123          */
1124         abstract public function canView();
1125         
1126         /**
1127          * Returns true if the current user can view the item text/file
1128          */
1129         abstract public function canViewContent();
1130
1131         /**
1132          * Get the current deletion bitfield value
1133          */
1134         abstract public function getBits();
1135
1136         /**
1137          * Get the HTML of the list item. Should be include <li></li> tags.
1138          * This is used to show the list in HTML form, by the special page.
1139          */
1140         abstract public function getHTML();
1141
1142         /**
1143          * Set the visibility of the item. This should do any necessary DB queries.
1144          *
1145          * The DB update query should have a condition which forces it to only update
1146          * if the value in the DB matches the value fetched earlier with the SELECT. 
1147          * If the update fails because it did not match, the function should return 
1148          * false. This prevents concurrency problems.
1149          *
1150          * @return boolean success
1151          */
1152         abstract public function setBits( $newBits );
1153 }
1154
1155 /**
1156  * List for revision table items
1157  */
1158 class RevDel_RevisionList extends RevDel_List {
1159         var $currentRevId;
1160         var $type = 'revision';
1161         var $idField = 'rev_id';
1162         var $dateField = 'rev_timestamp';
1163         var $authorIdField = 'rev_user';
1164         var $authorNameField = 'rev_user_text';
1165
1166         public function doQuery( $db ) {
1167                 $ids = array_map( 'intval', $this->ids );
1168                 return $db->select( array('revision','page'), '*',
1169                         array(
1170                                 'rev_page' => $this->title->getArticleID(),
1171                                 'rev_id'   => $ids,
1172                                 'rev_page = page_id'
1173                         ),
1174                         __METHOD__,
1175                         array( 'ORDER BY' => 'rev_id DESC' )
1176                 );
1177         }
1178
1179         public function newItem( $row ) {
1180                 return new RevDel_RevisionItem( $this, $row );
1181         }
1182
1183         public function getCurrent() {
1184                 if ( is_null( $this->currentRevId ) ) {
1185                         $dbw = wfGetDB( DB_MASTER );
1186                         $this->currentRevId = $dbw->selectField( 
1187                                 'page', 'page_latest', $this->title->pageCond(), __METHOD__ );
1188                 }
1189                 return $this->currentRevId;
1190         }
1191
1192         public function getSuppressBit() {
1193                 return Revision::DELETED_RESTRICTED;
1194         }
1195
1196         public function doPreCommitUpdates() {
1197                 $this->title->invalidateCache();
1198                 return Status::newGood();
1199         }
1200
1201         public function doPostCommitUpdates() {
1202                 $this->title->purgeSquid();
1203                 // Extensions that require referencing previous revisions may need this
1204                 wfRunHooks( 'ArticleRevisionVisiblitySet', array( &$this->title ) );
1205                 return Status::newGood();
1206         }
1207 }
1208
1209 /**
1210  * Item class for a revision table row
1211  */
1212 class RevDel_RevisionItem extends RevDel_Item {
1213         var $revision;
1214
1215         public function __construct( $list, $row ) {
1216                 parent::__construct( $list, $row );
1217                 $this->revision = new Revision( $row );
1218         }
1219
1220         public function canView() {
1221                 return $this->revision->userCan( Revision::DELETED_RESTRICTED );
1222         }
1223         
1224         public function canViewContent() {
1225                 return $this->revision->userCan( Revision::DELETED_TEXT );
1226         }
1227
1228         public function getBits() {
1229                 return $this->revision->mDeleted;
1230         }
1231
1232         public function setBits( $bits ) {
1233                 $dbw = wfGetDB( DB_MASTER );
1234                 // Update revision table
1235                 $dbw->update( 'revision',
1236                         array( 'rev_deleted' => $bits ),
1237                         array( 
1238                                 'rev_id' => $this->revision->getId(), 
1239                                 'rev_page' => $this->revision->getPage(),
1240                                 'rev_deleted' => $this->getBits()
1241                         ),
1242                         __METHOD__
1243                 );
1244                 if ( !$dbw->affectedRows() ) {
1245                         // Concurrent fail!
1246                         return false;
1247                 }
1248                 // Update recentchanges table
1249                 $dbw->update( 'recentchanges',
1250                         array( 
1251                                 'rc_deleted' => $bits,
1252                                 'rc_patrolled' => 1
1253                         ),
1254                         array(
1255                                 'rc_this_oldid' => $this->revision->getId(), // condition
1256                                 // non-unique timestamp index
1257                                 'rc_timestamp' => $dbw->timestamp( $this->revision->getTimestamp() ),
1258                         ),
1259                         __METHOD__
1260                 );
1261                 return true;
1262         }
1263
1264         public function isDeleted() {
1265                 return $this->revision->isDeleted( Revision::DELETED_TEXT );
1266         }
1267
1268         public function isHideCurrentOp( $newBits ) {
1269                 return ( $newBits & Revision::DELETED_TEXT ) 
1270                         && $this->list->getCurrent() == $this->getId();
1271         }
1272
1273         /**
1274          * Get the HTML link to the revision text.
1275          * Overridden by RevDel_ArchiveItem.
1276          */
1277         protected function getRevisionLink() {
1278                 global $wgLang;
1279                 $date = $wgLang->timeanddate( $this->revision->getTimestamp(), true );
1280                 if ( $this->isDeleted() && !$this->canViewContent() ) {
1281                         return $date;
1282                 }
1283                 return $this->special->skin->link(
1284                         $this->list->title,
1285                         $date, 
1286                         array(),
1287                         array(
1288                                 'oldid' => $this->revision->getId(),
1289                                 'unhide' => 1
1290                         )
1291                 );
1292         }
1293
1294         /**
1295          * Get the HTML link to the diff.
1296          * Overridden by RevDel_ArchiveItem
1297          */
1298         protected function getDiffLink() {
1299                 if ( $this->isDeleted() && !$this->canViewContent() ) {
1300                         return wfMsgHtml('diff');
1301                 } else {
1302                         return 
1303                                 $this->special->skin->link( 
1304                                         $this->list->title, 
1305                                         wfMsgHtml('diff'),
1306                                         array(),
1307                                         array(
1308                                                 'diff' => $this->revision->getId(),
1309                                                 'oldid' => 'prev',
1310                                                 'unhide' => 1
1311                                         ),
1312                                         array(
1313                                                 'known',
1314                                                 'noclasses'
1315                                         )
1316                                 );
1317                 }
1318         }
1319
1320         public function getHTML() {
1321                 $difflink = $this->getDiffLink();
1322                 $revlink = $this->getRevisionLink();
1323                 $userlink = $this->special->skin->revUserLink( $this->revision );
1324                 $comment = $this->special->skin->revComment( $this->revision );
1325                 if ( $this->isDeleted() ) {
1326                         $revlink = "<span class=\"history-deleted\">$revlink</span>";
1327                 }
1328                 return "<li>($difflink) $revlink $userlink $comment</li>";
1329         }
1330 }
1331
1332 /**
1333  * List for archive table items, i.e. revisions deleted via action=delete
1334  */
1335 class RevDel_ArchiveList extends RevDel_RevisionList {
1336         var $type = 'archive';
1337         var $idField = 'ar_timestamp';
1338         var $dateField = 'ar_timestamp';
1339         var $authorIdField = 'ar_user';
1340         var $authorNameField = 'ar_user_text';
1341
1342         public function doQuery( $db ) {
1343                 $timestamps = array();
1344                 foreach ( $this->ids as $id ) {
1345                         $timestamps[] = $db->timestamp( $id );
1346                 }
1347                 return $db->select( 'archive', '*',
1348                                 array(
1349                                         'ar_namespace' => $this->title->getNamespace(),
1350                                         'ar_title'     => $this->title->getDBkey(),
1351                                         'ar_timestamp' => $timestamps
1352                                 ),
1353                                 __METHOD__,
1354                                 array( 'ORDER BY' => 'ar_timestamp DESC' )
1355                         );
1356         }
1357
1358         public function newItem( $row ) {
1359                 return new RevDel_ArchiveItem( $this, $row );
1360         }
1361
1362         public function doPreCommitUpdates() {
1363                 return Status::newGood();
1364         }
1365
1366         public function doPostCommitUpdates() {
1367                 return Status::newGood();
1368         }
1369 }
1370
1371 /**
1372  * Item class for a archive table row
1373  */
1374 class RevDel_ArchiveItem extends RevDel_RevisionItem {
1375         public function __construct( $list, $row ) {
1376                 RevDel_Item::__construct( $list, $row );
1377                 $this->revision = Revision::newFromArchiveRow( $row,
1378                         array( 'page' => $this->list->title->getArticleId() ) );
1379         }
1380
1381         public function getId() {
1382                 # Convert DB timestamp to MW timestamp
1383                 return $this->revision->getTimestamp();
1384         }
1385         
1386         public function setBits( $bits ) {
1387                 $dbw = wfGetDB( DB_MASTER );
1388                 $dbw->update( 'archive',
1389                         array( 'ar_deleted' => $bits ),
1390                         array( 'ar_namespace' => $this->list->title->getNamespace(),
1391                                 'ar_title'     => $this->list->title->getDBkey(),
1392                                 // use timestamp for index
1393                                 'ar_timestamp' => $this->row->ar_timestamp,
1394                                 'ar_rev_id'    => $this->row->ar_rev_id,
1395                                 'ar_deleted' => $this->getBits()
1396                         ),
1397                         __METHOD__ );
1398                 return (bool)$dbw->affectedRows();
1399         }
1400
1401         protected function getRevisionLink() {
1402                 global $wgLang;
1403                 $undelete = SpecialPage::getTitleFor( 'Undelete' );
1404                 $date = $wgLang->timeanddate( $this->revision->getTimestamp(), true );
1405                 if ( $this->isDeleted() && !$this->canViewContent() ) {
1406                         return $date;
1407                 }
1408                 return $this->special->skin->link( $undelete, $date, array(),
1409                         array(
1410                                 'target' => $this->list->title->getPrefixedText(),
1411                                 'timestamp' => $this->revision->getTimestamp()
1412                         ) );
1413         }
1414
1415         protected function getDiffLink() {
1416                 if ( $this->isDeleted() && !$this->canViewContent() ) {
1417                         return wfMsgHtml( 'diff' );
1418                 }
1419                 $undelete = SpecialPage::getTitleFor( 'Undelete' );             
1420                 return $this->special->skin->link( $undelete, wfMsgHtml('diff'), array(), 
1421                         array(
1422                                 'target' => $this->list->title->getPrefixedText(),
1423                                 'diff' => 'prev',
1424                                 'timestamp' => $this->revision->getTimestamp()
1425                         ) );
1426         }
1427 }
1428
1429 /**
1430  * List for oldimage table items
1431  */
1432 class RevDel_FileList extends RevDel_List {
1433         var $type = 'oldimage';
1434         var $idField = 'oi_archive_name';
1435         var $dateField = 'oi_timestamp';
1436         var $authorIdField = 'oi_user';
1437         var $authorNameField = 'oi_user_text';
1438         var $storeBatch, $deleteBatch, $cleanupBatch;
1439
1440         public function doQuery( $db ) {
1441                 $archiveName = array();
1442                 foreach( $this->ids as $timestamp ) {
1443                         $archiveNames[] = $timestamp . '!' . $this->title->getDBkey();
1444                 }
1445                 return $db->select( 'oldimage', '*',
1446                         array(
1447                                 'oi_name'         => $this->title->getDBkey(),
1448                                 'oi_archive_name' => $archiveNames
1449                         ),
1450                         __METHOD__,
1451                         array( 'ORDER BY' => 'oi_timestamp DESC' )
1452                 );
1453         }
1454
1455         public function newItem( $row ) {
1456                 return new RevDel_FileItem( $this, $row );
1457         }
1458
1459         public function clearFileOps() {
1460                 $this->deleteBatch = array();
1461                 $this->storeBatch = array();
1462                 $this->cleanupBatch = array();
1463         }
1464
1465         public function doPreCommitUpdates() {
1466                 $status = Status::newGood();
1467                 $repo = RepoGroup::singleton()->getLocalRepo();
1468                 if ( $this->storeBatch ) {
1469                         $status->merge( $repo->storeBatch( $this->storeBatch, FileRepo::OVERWRITE_SAME ) );
1470                 }
1471                 if ( !$status->isOK() ) {
1472                         return $status;
1473                 }
1474                 if ( $this->deleteBatch ) {
1475                         $status->merge( $repo->deleteBatch( $this->deleteBatch ) );
1476                 }
1477                 if ( !$status->isOK() ) {
1478                         // Running cleanupDeletedBatch() after a failed storeBatch() with the DB already
1479                         // modified (but destined for rollback) causes data loss
1480                         return $status;
1481                 }
1482                 if ( $this->cleanupBatch ) {
1483                         $status->merge( $repo->cleanupDeletedBatch( $this->cleanupBatch ) );
1484                 }
1485                 return $status;
1486         }
1487
1488         public function doPostCommitUpdates() {
1489                 $file = wfLocalFile( $this->title );
1490                 $file->purgeCache();
1491                 $file->purgeDescription();
1492                 return Status::newGood();
1493         }
1494
1495         public function getSuppressBit() {
1496                 return File::DELETED_RESTRICTED;
1497         }
1498 }
1499
1500 /**
1501  * Item class for an oldimage table row
1502  */
1503 class RevDel_FileItem extends RevDel_Item {
1504         var $file;
1505
1506         public function __construct( $list, $row ) {
1507                 parent::__construct( $list, $row );
1508                 $this->file = RepoGroup::singleton()->getLocalRepo()->newFileFromRow( $row );
1509         }
1510
1511         public function getId() {
1512                 $parts = explode( '!', $this->row->oi_archive_name );
1513                 return $parts[0];
1514         }
1515
1516         public function canView() {
1517                 return $this->file->userCan( File::DELETED_RESTRICTED );
1518         }
1519         
1520         public function canViewContent() {
1521                 return $this->file->userCan( File::DELETED_FILE );
1522         }
1523
1524         public function getBits() {
1525                 return $this->file->getVisibility();
1526         }
1527
1528         public function setBits( $bits ) {
1529                 # Queue the file op
1530                 # FIXME: move to LocalFile.php
1531                 if ( $this->isDeleted() ) {
1532                         if ( $bits & File::DELETED_FILE ) {
1533                                 # Still deleted
1534                         } else {
1535                                 # Newly undeleted
1536                                 $key = $this->file->getStorageKey();
1537                                 $srcRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1538                                 $this->list->storeBatch[] = array(
1539                                         $this->file->repo->getVirtualUrl( 'deleted' ) . '/' . $srcRel,
1540                                         'public',
1541                                         $this->file->getRel()
1542                                 );
1543                                 $this->list->cleanupBatch[] = $key;
1544                         }
1545                 } elseif ( $bits & File::DELETED_FILE ) {
1546                         # Newly deleted
1547                         $key = $this->file->getStorageKey();
1548                         $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1549                         $this->list->deleteBatch[] = array( $this->file->getRel(), $dstRel );
1550                 }
1551                 
1552                 # Do the database operations
1553                 $dbw = wfGetDB( DB_MASTER );
1554                 $dbw->update( 'oldimage',
1555                         array( 'oi_deleted' => $bits ),
1556                         array( 
1557                                 'oi_name' => $this->row->oi_name,
1558                                 'oi_timestamp' => $this->row->oi_timestamp,
1559                                 'oi_deleted' => $this->getBits()
1560                         ),
1561                         __METHOD__
1562                 );
1563                 return (bool)$dbw->affectedRows();
1564         }
1565
1566         public function isDeleted() {
1567                 return $this->file->isDeleted( File::DELETED_FILE );
1568         }
1569
1570         /**
1571          * Get the link to the file. 
1572          * Overridden by RevDel_ArchivedFileItem.
1573          */
1574         protected function getLink() {
1575                 global $wgLang, $wgUser;
1576                 $date = $wgLang->timeanddate( $this->file->getTimestamp(), true  );             
1577                 if ( $this->isDeleted() ) {
1578                         # Hidden files...
1579                         if ( !$this->canViewContent() ) {
1580                                 $link = $date;
1581                         } else {
1582                                 $link = $this->special->skin->link( 
1583                                         $this->special->getTitle(), 
1584                                         $date, array(), 
1585                                         array(
1586                                                 'target' => $this->list->title->getPrefixedText(),
1587                                                 'file'   => $this->file->getArchiveName(),
1588                                                 'token'  => $wgUser->editToken( $this->file->getArchiveName() )
1589                                         )
1590                                 );
1591                         }
1592                         return '<span class="history-deleted">' . $link . '</span>';
1593                 } else {
1594                         # Regular files...
1595                         $url = $this->file->getUrl();
1596                         return Xml::element( 'a', array( 'href' => $this->file->getUrl() ), $date );
1597                 }
1598         }
1599         /**
1600          * Generate a user tool link cluster if the current user is allowed to view it
1601          * @return string HTML
1602          */
1603         protected function getUserTools() {
1604                 if( $this->file->userCan( Revision::DELETED_USER ) ) {
1605                         $link = $this->special->skin->userLink( $this->file->user, $this->file->user_text ) .
1606                                 $this->special->skin->userToolLinks( $this->file->user, $this->file->user_text );
1607                 } else {
1608                         $link = wfMsgHtml( 'rev-deleted-user' );
1609                 }
1610                 if( $this->file->isDeleted( Revision::DELETED_USER ) ) {
1611                         return '<span class="history-deleted">' . $link . '</span>';
1612                 }
1613                 return $link;
1614         }
1615
1616         /**
1617          * Wrap and format the file's comment block, if the current
1618          * user is allowed to view it.
1619          *
1620          * @return string HTML
1621          */
1622         protected function getComment() {
1623                 if( $this->file->userCan( File::DELETED_COMMENT ) ) {
1624                         $block = $this->special->skin->commentBlock( $this->file->description );
1625                 } else {
1626                         $block = ' ' . wfMsgHtml( 'rev-deleted-comment' );
1627                 }
1628                 if( $this->file->isDeleted( File::DELETED_COMMENT ) ) {
1629                         return "<span class=\"history-deleted\">$block</span>";
1630                 }
1631                 return $block;
1632         }
1633
1634         public function getHTML() {
1635                 global $wgLang;
1636                 $data = 
1637                         wfMsg(
1638                                 'widthheight', 
1639                                 $wgLang->formatNum( $this->file->getWidth() ),
1640                                 $wgLang->formatNum( $this->file->getHeight() ) 
1641                         ) .
1642                         ' (' . 
1643                         wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $this->file->getSize() ) ) . 
1644                         ')';
1645                 $pageLink = $this->getLink();
1646
1647                 return '<li>' . $this->getLink() . ' ' . $this->getUserTools() . ' ' .
1648                         $data . ' ' . $this->getComment(). '</li>';
1649         }
1650 }
1651
1652 /**
1653  * List for filearchive table items
1654  */
1655 class RevDel_ArchivedFileList extends RevDel_FileList {
1656         var $type = 'filearchive';
1657         var $idField = 'fa_id';
1658         var $dateField = 'fa_timestamp';
1659         var $authorIdField = 'fa_user';
1660         var $authorNameField = 'fa_user_text';
1661         
1662         public function doQuery( $db ) {
1663                 $ids = array_map( 'intval', $this->ids );
1664                 return $db->select( 'filearchive', '*',
1665                         array(
1666                                 'fa_name' => $this->title->getDBkey(),
1667                                 'fa_id'   => $ids
1668                         ),
1669                         __METHOD__,
1670                         array( 'ORDER BY' => 'fa_id DESC' )
1671                 );
1672         }
1673
1674         public function newItem( $row ) {
1675                 return new RevDel_ArchivedFileItem( $this, $row );
1676         }
1677 }
1678
1679 /**
1680  * Item class for a filearchive table row
1681  */
1682 class RevDel_ArchivedFileItem extends RevDel_FileItem {
1683         public function __construct( $list, $row ) {
1684                 RevDel_Item::__construct( $list, $row );
1685                 $this->file = ArchivedFile::newFromRow( $row );
1686         }
1687
1688         public function getId() {
1689                 return $this->row->fa_id;
1690         }
1691
1692         public function setBits( $bits ) {
1693                 $dbw = wfGetDB( DB_MASTER );
1694                 $dbw->update( 'filearchive',
1695                         array( 'fa_deleted' => $bits ),
1696                         array(
1697                                 'fa_id' => $this->row->fa_id,
1698                                 'fa_deleted' => $this->getBits(),
1699                         ),
1700                         __METHOD__
1701                 );
1702                 return (bool)$dbw->affectedRows();
1703         }
1704
1705         protected function getLink() {
1706                 global $wgLang, $wgUser;
1707                 $date = $wgLang->timeanddate( $this->file->getTimestamp(), true  );
1708                 $undelete = SpecialPage::getTitleFor( 'Undelete' );
1709                 $key = $this->file->getKey();
1710                 # Hidden files...
1711                 if( !$this->canViewContent() ) {
1712                         $link = $date;
1713                 } else {
1714                         $link = $this->special->skin->link( $undelete, $date, array(),
1715                                 array(
1716                                         'target' => $this->list->title->getPrefixedText(),
1717                                         'file' => $key,
1718                                         'token' => $wgUser->editToken( $key )
1719                                 )
1720                         );
1721                 }
1722                 if( $this->isDeleted() ) {
1723                         $link = '<span class="history-deleted">' . $link . '</span>';
1724                 }
1725                 return $link;
1726         }
1727 }
1728
1729 /**
1730  * List for logging table items
1731  */
1732 class RevDel_LogList extends RevDel_List {
1733         var $type = 'logging';
1734         var $idField = 'log_id';
1735         var $dateField = 'log_timestamp';
1736         var $authorIdField = 'log_user';
1737         var $authorNameField = 'log_user_text';
1738
1739         public function doQuery( $db ) {
1740                 global $wgMessageCache;
1741                 $wgMessageCache->loadAllMessages();
1742                 $ids = array_map( 'intval', $this->ids );
1743                 return $db->select( 'logging', '*',
1744                         array( 'log_id' => $ids ),
1745                         __METHOD__,
1746                         array( 'ORDER BY' => 'log_id DESC' )
1747                 );
1748         }
1749
1750         public function newItem( $row ) {
1751                 return new RevDel_LogItem( $this, $row );
1752         }
1753
1754         public function getSuppressBit() {
1755                 return Revision::DELETED_RESTRICTED;
1756         }
1757
1758         public function getLogAction() {
1759                 return 'event';
1760         }
1761
1762         public function getLogParams( $params ) {
1763                 return array(
1764                         implode( ',', $params['ids'] ),
1765                         "ofield={$params['oldBits']}",
1766                         "nfield={$params['newBits']}"
1767                 );
1768         }
1769 }
1770
1771 /**
1772  * Item class for a logging table row
1773  */
1774 class RevDel_LogItem extends RevDel_Item {
1775         public function canView() {
1776                 return LogEventsList::userCan( $this->row, Revision::DELETED_RESTRICTED );
1777         }
1778         
1779         public function canViewContent() {
1780                 return true; // none
1781         }
1782
1783         public function getBits() {
1784                 return $this->row->log_deleted;
1785         }
1786
1787         public function setBits( $bits ) {
1788                 $dbw = wfGetDB( DB_MASTER );
1789                 $dbw->update( 'recentchanges',
1790                         array( 
1791                                 'rc_deleted' => $bits, 
1792                                 'rc_patrolled' => 1 
1793                         ),
1794                         array(
1795                                 'rc_logid' => $this->row->log_id,
1796                                 'rc_timestamp' => $this->row->log_timestamp // index
1797                         ),
1798                         __METHOD__
1799                 );
1800                 $dbw->update( 'logging',
1801                         array( 'log_deleted' => $bits ),
1802                         array(
1803                                 'log_id' => $this->row->log_id,
1804                                 'log_deleted' => $this->getBits()
1805                         ),
1806                         __METHOD__
1807                 );
1808                 return (bool)$dbw->affectedRows();
1809         }
1810
1811         public function getHTML() {
1812                 global $wgLang;
1813
1814                 $date = htmlspecialchars( $wgLang->timeanddate( $this->row->log_timestamp ) );
1815                 $paramArray = LogPage::extractParams( $this->row->log_params );
1816                 $title = Title::makeTitle( $this->row->log_namespace, $this->row->log_title );
1817
1818                 // Log link for this page
1819                 $loglink = $this->special->skin->link(
1820                         SpecialPage::getTitleFor( 'Log' ),
1821                         wfMsgHtml( 'log' ),
1822                         array(),
1823                         array( 'page' => $title->getPrefixedText() )
1824                 );
1825                 // Action text
1826                 if( !$this->canView() ) {
1827                         $action = '<span class="history-deleted">' . wfMsgHtml('rev-deleted-event') . '</span>';
1828                 } else {
1829                         $action = LogPage::actionText( $this->row->log_type, $this->row->log_action, $title,
1830                                 $this->special->skin, $paramArray, true, true );
1831                         if( $this->row->log_deleted & LogPage::DELETED_ACTION )
1832                                 $action = '<span class="history-deleted">' . $action . '</span>';
1833                 }
1834                 // User links
1835                 $userLink = $this->special->skin->userLink( $this->row->log_user,
1836                         User::WhoIs( $this->row->log_user ) );
1837                 if( LogEventsList::isDeleted($this->row,LogPage::DELETED_USER) ) {
1838                         $userLink = '<span class="history-deleted">' . $userLink . '</span>';
1839                 }
1840                 // Comment
1841                 $comment = $wgLang->getDirMark() . $this->special->skin->commentBlock( $this->row->log_comment );
1842                 if( LogEventsList::isDeleted($this->row,LogPage::DELETED_COMMENT) ) {
1843                         $comment = '<span class="history-deleted">' . $comment . '</span>';
1844                 }
1845                 return "<li>($loglink) $date $userLink $action $comment</li>";
1846         }
1847 }