Fix bug in r66793
[lhc/web/wiklou.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 of message keys describing the changes made to the visibility
625 * of the revision. If the resulting array is $arr, then $arr[0] will contain an
626 * array of strings describing the items that were hidden, $arr[2] will contain
627 * an array of strings describing the items that were unhidden, and $arr[3] will
628 * contain an array with a single string, which can be one of "applied
629 * restrictions to sysops", "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( 'revdelete-content',
640 Revision::DELETED_TEXT, $diff, $n, $ret );
641 self::checkItem( 'revdelete-summary',
642 Revision::DELETED_COMMENT, $diff, $n, $ret );
643 self::checkItem( '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][] = 'revdelete-restricted';
649 else
650 $ret[2][] = '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 * @param $forContent Boolean
665 */
666 public static function getLogMessage( $count, $nbitfield, $obitfield, $isForLog = false, $forContent = false ) {
667 global $wgLang, $wgContLang;
668
669 $lang = $forContent ? $wgContLang : $wgLang;
670 $msgFunc = $forContent ? "wfMsgForContent" : "wfMsg";
671
672 $s = '';
673 $changes = self::getChanges( $nbitfield, $obitfield );
674 array_walk($changes, 'RevisionDeleter::expandMessageArray', $forContent);
675
676 $changesText = array();
677
678 if( count( $changes[0] ) ) {
679 $changesText[] = $msgFunc( 'revdelete-hid', $lang->commaList( $changes[0] ) );
680 }
681 if( count( $changes[1] ) ) {
682 $changesText[] = $msgFunc( 'revdelete-unhid', $lang->commaList( $changes[1] ) );
683 }
684
685 $s = $lang->semicolonList( $changesText );
686 if( count( $changes[2] ) ) {
687 $s .= $s ? ' (' . $changes[2][0] . ')' : ' ' . $changes[2][0];
688 }
689
690 $msg = $isForLog ? 'logdelete-log-message' : 'revdelete-log-message';
691 return wfMsgExt( $msg, $forContent ? array( 'parsemag', 'content' ) : array( 'parsemag' ), $s, $lang->formatNum($count) );
692 }
693
694 private static function expandMessageArray(& $msg, $key, $forContent) {
695 if ( is_array ($msg) ) {
696 array_walk($msg, 'RevisionDeleter::expandMessageArray', $forContent);
697 } else {
698 if ( $forContent ) {
699 $msg = wfMsgForContent($msg);
700 } else {
701 $msg = wfMsg($msg);
702 }
703 }
704 }
705
706 // Get DB field name for URL param...
707 // Future code for other things may also track
708 // other types of revision-specific changes.
709 // @returns string One of log_id/rev_id/fa_id/ar_timestamp/oi_archive_name
710 public static function getRelationType( $typeName ) {
711 if ( isset( SpecialRevisionDelete::$deprecatedTypeMap[$typeName] ) ) {
712 $typeName = SpecialRevisionDelete::$deprecatedTypeMap[$typeName];
713 }
714 if ( isset( SpecialRevisionDelete::$allowedTypes[$typeName] ) ) {
715 $class = SpecialRevisionDelete::$allowedTypes[$typeName]['list-class'];
716 $list = new $class( null, null, null );
717 return $list->getIdField();
718 } else {
719 return null;
720 }
721 }
722
723 // Checks if a revision still exists in the revision table.
724 // If it doesn't, returns the corresponding ar_timestamp field
725 // so that this key can be used instead.
726 public static function checkRevisionExistence( $title, $revid ) {
727 $dbr = wfGetDB( DB_SLAVE );
728 $exists = $dbr->selectField( 'revision', '1',
729 array( 'rev_id' => $revid ), __METHOD__ );
730
731 if ( $exists ) {
732 return true;
733 }
734
735 $timestamp = $dbr->selectField( 'archive', 'ar_timestamp',
736 array( 'ar_namespace' => $title->getNamespace(),
737 'ar_title' => $title->getDBkey(),
738 'ar_rev_id' => $revid ), __METHOD__ );
739
740 return $timestamp;
741 }
742
743 // Creates utility links for log entries.
744 public static function getLogLinks( $title, $paramArray, $skin, $messages ) {
745 global $wgLang;
746
747 if( count($paramArray) >= 2 ) {
748 // Different revision types use different URL params...
749 $originalKey = $key = $paramArray[0];
750 // $paramArray[1] is a CSV of the IDs
751 $Ids = explode( ',', $paramArray[1] );
752 $query = $paramArray[1];
753 $revert = array();
754
755 // For if undeleted revisions are found amidst deleted ones.
756 $undeletedRevisions = array();
757
758 // This is not going to work if some revs are deleted and some
759 // aren't.
760 if ($key == 'revision') {
761 foreach( $Ids as $k => $id ) {
762 $existResult =
763 self::checkRevisionExistence( $title, $id );
764
765 if ($existResult !== true) {
766 $key = 'archive';
767 $Ids[$k] = $existResult;
768 } else {
769 // Undeleted revision amidst deleted ones
770 unset($Ids[$k]);
771 $undeletedRevisions[] = $id;
772 }
773 }
774
775 if ( $key == $originalKey ) {
776 $Ids = $undeletedRevisions;
777 $undeletedRevisions = array();
778 }
779 }
780
781 // Diff link for single rev deletions
782 if( count($Ids) == 1 && !count($undeletedRevisions) ) {
783 // Live revision diffs...
784 if( in_array( $key, array( 'oldid', 'revision' ) ) ) {
785 $revert[] = $skin->link(
786 $title,
787 $messages['diff'],
788 array(),
789 array(
790 'diff' => intval( $Ids[0] ),
791 'unhide' => 1
792 ),
793 array( 'known', 'noclasses' )
794 );
795 // Deleted revision diffs...
796 } else if( in_array( $key, array( 'artimestamp','archive' ) ) ) {
797 $revert[] = $skin->link(
798 SpecialPage::getTitleFor( 'Undelete' ),
799 $messages['diff'],
800 array(),
801 array(
802 'target' => $title->getPrefixedDBKey(),
803 'diff' => 'prev',
804 'timestamp' => $Ids[0]
805 ),
806 array( 'known', 'noclasses' )
807 );
808 }
809 }
810
811 // View/modify link...
812 if ( count($undeletedRevisions) ) {
813 // FIXME THIS IS A HORRIBLE HORRIBLE HACK AND SHOULD DIE
814 // It's not possible to pass a list of both deleted and
815 // undeleted revisions to SpecialRevisionDelete, so we're
816 // stuck with two links. See bug 23363.
817 $restoreLinks = array();
818
819 $restoreLinks[] = $skin->link(
820 SpecialPage::getTitleFor( 'Revisiondelete' ),
821 $messages['revdel-restore-visible'],
822 array(),
823 array(
824 'target' => $title->getPrefixedText(),
825 'type' => $originalKey,
826 'ids' => implode(',', $undeletedRevisions),
827 ),
828 array( 'known', 'noclasses' )
829 );
830
831 $restoreLinks[] = $skin->link(
832 SpecialPage::getTitleFor( 'Revisiondelete' ),
833 $messages['revdel-restore-deleted'],
834 array(),
835 array(
836 'target' => $title->getPrefixedText(),
837 'type' => $key,
838 'ids' => implode(',', $Ids),
839 ),
840 array( 'known', 'noclasses' )
841 );
842
843 $revert[] = $messages['revdel-restore'] . ' [' .
844 $wgLang->pipeList( $restoreLinks ) . ']';
845 } else {
846 $revert[] = $skin->link(
847 SpecialPage::getTitleFor( 'Revisiondelete' ),
848 $messages['revdel-restore'],
849 array(),
850 array(
851 'target' => $title->getPrefixedText(),
852 'type' => $key,
853 'ids' => implode(',', $Ids),
854 ),
855 array( 'known', 'noclasses' )
856 );
857 }
858
859 // Pipe links
860 $revert = wfMsg( 'parentheses', $wgLang->pipeList( $revert ) );
861 }
862 return $revert;
863 }
864 }
865
866 /**
867 * Abstract base class for a list of deletable items
868 */
869 abstract class RevDel_List {
870 var $special, $title, $ids, $res, $current;
871 var $type = null; // override this
872 var $idField = null; // override this
873 var $dateField = false; // override this
874 var $authorIdField = false; // override this
875 var $authorNameField = false; // override this
876
877 /**
878 * @param $special The parent SpecialPage
879 * @param $title The target title
880 * @param $ids Array of IDs
881 */
882 public function __construct( $special, $title, $ids ) {
883 $this->special = $special;
884 $this->title = $title;
885 $this->ids = $ids;
886 }
887
888 /**
889 * Get the internal type name of this list. Equal to the table name.
890 */
891 public function getType() {
892 return $this->type;
893 }
894
895 /**
896 * Get the DB field name associated with the ID list
897 */
898 public function getIdField() {
899 return $this->idField;
900 }
901
902 /**
903 * Get the DB field name storing timestamps
904 */
905 public function getTimestampField() {
906 return $this->dateField;
907 }
908
909 /**
910 * Get the DB field name storing user ids
911 */
912 public function getAuthorIdField() {
913 return $this->authorIdField;
914 }
915
916 /**
917 * Get the DB field name storing user names
918 */
919 public function getAuthorNameField() {
920 return $this->authorNameField;
921 }
922 /**
923 * Set the visibility for the revisions in this list. Logging and
924 * transactions are done here.
925 *
926 * @param $params Associative array of parameters. Members are:
927 * value: The integer value to set the visibility to
928 * comment: The log comment.
929 * @return Status
930 */
931 public function setVisibility( $params ) {
932 $bitPars = $params['value'];
933 $comment = $params['comment'];
934
935 $this->res = false;
936 $dbw = wfGetDB( DB_MASTER );
937 $this->doQuery( $dbw );
938 $dbw->begin();
939 $status = Status::newGood();
940 $missing = array_flip( $this->ids );
941 $this->clearFileOps();
942 $idsForLog = array();
943 $authorIds = $authorIPs = array();
944
945 for ( $this->reset(); $this->current(); $this->next() ) {
946 $item = $this->current();
947 unset( $missing[ $item->getId() ] );
948
949 $oldBits = $item->getBits();
950 // Build the actual new rev_deleted bitfield
951 $newBits = SpecialRevisionDelete::extractBitfield( $bitPars, $oldBits );
952
953 if ( $oldBits == $newBits ) {
954 $status->warning( 'revdelete-no-change', $item->formatDate(), $item->formatTime() );
955 $status->failCount++;
956 continue;
957 } elseif ( $oldBits == 0 && $newBits != 0 ) {
958 $opType = 'hide';
959 } elseif ( $oldBits != 0 && $newBits == 0 ) {
960 $opType = 'show';
961 } else {
962 $opType = 'modify';
963 }
964
965 if ( $item->isHideCurrentOp( $newBits ) ) {
966 // Cannot hide current version text
967 $status->error( 'revdelete-hide-current', $item->formatDate(), $item->formatTime() );
968 $status->failCount++;
969 continue;
970 }
971 if ( !$item->canView() ) {
972 // Cannot access this revision
973 $msg = ($opType == 'show') ?
974 'revdelete-show-no-access' : 'revdelete-modify-no-access';
975 $status->error( $msg, $item->formatDate(), $item->formatTime() );
976 $status->failCount++;
977 continue;
978 }
979 // Cannot just "hide from Sysops" without hiding any fields
980 if( $newBits == Revision::DELETED_RESTRICTED ) {
981 $status->warning( 'revdelete-only-restricted', $item->formatDate(), $item->formatTime() );
982 $status->failCount++;
983 continue;
984 }
985
986 // Update the revision
987 $ok = $item->setBits( $newBits );
988
989 if ( $ok ) {
990 $idsForLog[] = $item->getId();
991 $status->successCount++;
992 if( $item->getAuthorId() > 0 ) {
993 $authorIds[] = $item->getAuthorId();
994 } else if( IP::isIPAddress( $item->getAuthorName() ) ) {
995 $authorIPs[] = $item->getAuthorName();
996 }
997 } else {
998 $status->error( 'revdelete-concurrent-change', $item->formatDate(), $item->formatTime() );
999 $status->failCount++;
1000 }
1001 }
1002
1003 // Handle missing revisions
1004 foreach ( $missing as $id => $unused ) {
1005 $status->error( 'revdelete-modify-missing', $id );
1006 $status->failCount++;
1007 }
1008
1009 if ( $status->successCount == 0 ) {
1010 $status->ok = false;
1011 $dbw->rollback();
1012 return $status;
1013 }
1014
1015 // Save success count
1016 $successCount = $status->successCount;
1017
1018 // Move files, if there are any
1019 $status->merge( $this->doPreCommitUpdates() );
1020 if ( !$status->isOK() ) {
1021 // Fatal error, such as no configured archive directory
1022 $dbw->rollback();
1023 return $status;
1024 }
1025
1026 // Log it
1027 $this->updateLog( array(
1028 'title' => $this->title,
1029 'count' => $successCount,
1030 'newBits' => $newBits,
1031 'oldBits' => $oldBits,
1032 'comment' => $comment,
1033 'ids' => $idsForLog,
1034 'authorIds' => $authorIds,
1035 'authorIPs' => $authorIPs
1036 ) );
1037 $dbw->commit();
1038
1039 // Clear caches
1040 $status->merge( $this->doPostCommitUpdates() );
1041 return $status;
1042 }
1043
1044 /**
1045 * Reload the list data from the master DB. This can be done after setVisibility()
1046 * to allow $item->getHTML() to show the new data.
1047 */
1048 function reloadFromMaster() {
1049 $dbw = wfGetDB( DB_MASTER );
1050 $this->res = $this->doQuery( $dbw );
1051 }
1052
1053 /**
1054 * Record a log entry on the action
1055 * @param $params Associative array of parameters:
1056 * newBits: The new value of the *_deleted bitfield
1057 * oldBits: The old value of the *_deleted bitfield.
1058 * title: The target title
1059 * ids: The ID list
1060 * comment: The log comment
1061 * authorsIds: The array of the user IDs of the offenders
1062 * authorsIPs: The array of the IP/anon user offenders
1063 */
1064 protected function updateLog( $params ) {
1065 // Get the URL param's corresponding DB field
1066 $field = RevisionDeleter::getRelationType( $this->getType() );
1067 if( !$field ) {
1068 throw new MWException( "Bad log URL param type!" );
1069 }
1070 // Put things hidden from sysops in the oversight log
1071 if ( ( $params['newBits'] | $params['oldBits'] ) & $this->getSuppressBit() ) {
1072 $logType = 'suppress';
1073 } else {
1074 $logType = 'delete';
1075 }
1076 // Add params for effected page and ids
1077 $logParams = $this->getLogParams( $params );
1078 // Actually add the deletion log entry
1079 $log = new LogPage( $logType );
1080 $logid = $log->addEntry( $this->getLogAction(), $params['title'],
1081 $params['comment'], $logParams );
1082 // Allow for easy searching of deletion log items for revision/log items
1083 $log->addRelations( $field, $params['ids'], $logid );
1084 $log->addRelations( 'target_author_id', $params['authorIds'], $logid );
1085 $log->addRelations( 'target_author_ip', $params['authorIPs'], $logid );
1086 }
1087
1088 /**
1089 * Get the log action for this list type
1090 */
1091 public function getLogAction() {
1092 return 'revision';
1093 }
1094
1095 /**
1096 * Get log parameter array.
1097 * @param $params Associative array of log parameters, same as updateLog()
1098 * @return array
1099 */
1100 public function getLogParams( $params ) {
1101 return array(
1102 $this->getType(),
1103 implode( ',', $params['ids'] ),
1104 "ofield={$params['oldBits']}",
1105 "nfield={$params['newBits']}"
1106 );
1107 }
1108
1109 /**
1110 * Initialise the current iteration pointer
1111 */
1112 protected function initCurrent() {
1113 $row = $this->res->current();
1114 if ( $row ) {
1115 $this->current = $this->newItem( $row );
1116 } else {
1117 $this->current = false;
1118 }
1119 }
1120
1121 /**
1122 * Start iteration. This must be called before current() or next().
1123 * @return First list item
1124 */
1125 public function reset() {
1126 if ( !$this->res ) {
1127 $this->res = $this->doQuery( wfGetDB( DB_SLAVE ) );
1128 } else {
1129 $this->res->rewind();
1130 }
1131 $this->initCurrent();
1132 return $this->current;
1133 }
1134
1135 /**
1136 * Get the current list item, or false if we are at the end
1137 */
1138 public function current() {
1139 return $this->current;
1140 }
1141
1142 /**
1143 * Move the iteration pointer to the next list item, and return it.
1144 */
1145 public function next() {
1146 $this->res->next();
1147 $this->initCurrent();
1148 return $this->current;
1149 }
1150
1151 /**
1152 * Get the number of items in the list.
1153 */
1154 public function length() {
1155 if( !$this->res ) {
1156 return 0;
1157 } else {
1158 return $this->res->numRows();
1159 }
1160 }
1161
1162 /**
1163 * Clear any data structures needed for doPreCommitUpdates() and doPostCommitUpdates()
1164 * STUB
1165 */
1166 public function clearFileOps() {
1167 }
1168
1169 /**
1170 * A hook for setVisibility(): do batch updates pre-commit.
1171 * STUB
1172 * @return Status
1173 */
1174 public function doPreCommitUpdates() {
1175 return Status::newGood();
1176 }
1177
1178 /**
1179 * A hook for setVisibility(): do any necessary updates post-commit.
1180 * STUB
1181 * @return Status
1182 */
1183 public function doPostCommitUpdates() {
1184 return Status::newGood();
1185 }
1186
1187 /**
1188 * Create an item object from a DB result row
1189 * @param $row stdclass
1190 */
1191 abstract public function newItem( $row );
1192
1193 /**
1194 * Do the DB query to iterate through the objects.
1195 * @param $db Database object to use for the query
1196 */
1197 abstract public function doQuery( $db );
1198
1199 /**
1200 * Get the integer value of the flag used for suppression
1201 */
1202 abstract public function getSuppressBit();
1203 }
1204
1205 /**
1206 * Abstract base class for deletable items
1207 */
1208 abstract class RevDel_Item {
1209 /** The parent SpecialPage */
1210 var $special;
1211
1212 /** The parent RevDel_List */
1213 var $list;
1214
1215 /** The DB result row */
1216 var $row;
1217
1218 /**
1219 * @param $list RevDel_List
1220 * @param $row DB result row
1221 */
1222 public function __construct( $list, $row ) {
1223 $this->special = $list->special;
1224 $this->list = $list;
1225 $this->row = $row;
1226 }
1227
1228 /**
1229 * Get the ID, as it would appear in the ids URL parameter
1230 */
1231 public function getId() {
1232 $field = $this->list->getIdField();
1233 return $this->row->$field;
1234 }
1235
1236 /**
1237 * Get the date, formatted with $wgLang
1238 */
1239 public function formatDate() {
1240 global $wgLang;
1241 return $wgLang->date( $this->getTimestamp() );
1242 }
1243
1244 /**
1245 * Get the time, formatted with $wgLang
1246 */
1247 public function formatTime() {
1248 global $wgLang;
1249 return $wgLang->time( $this->getTimestamp() );
1250 }
1251
1252 /**
1253 * Get the timestamp in MW 14-char form
1254 */
1255 public function getTimestamp() {
1256 $field = $this->list->getTimestampField();
1257 return wfTimestamp( TS_MW, $this->row->$field );
1258 }
1259
1260 /**
1261 * Get the author user ID
1262 */
1263 public function getAuthorId() {
1264 $field = $this->list->getAuthorIdField();
1265 return intval( $this->row->$field );
1266 }
1267
1268 /**
1269 * Get the author user name
1270 */
1271 public function getAuthorName() {
1272 $field = $this->list->getAuthorNameField();
1273 return strval( $this->row->$field );
1274 }
1275
1276 /**
1277 * Returns true if the item is "current", and the operation to set the given
1278 * bits can't be executed for that reason
1279 * STUB
1280 */
1281 public function isHideCurrentOp( $newBits ) {
1282 return false;
1283 }
1284
1285 /**
1286 * Returns true if the current user can view the item
1287 */
1288 abstract public function canView();
1289
1290 /**
1291 * Returns true if the current user can view the item text/file
1292 */
1293 abstract public function canViewContent();
1294
1295 /**
1296 * Get the current deletion bitfield value
1297 */
1298 abstract public function getBits();
1299
1300 /**
1301 * Get the HTML of the list item. Should be include <li></li> tags.
1302 * This is used to show the list in HTML form, by the special page.
1303 */
1304 abstract public function getHTML();
1305
1306 /**
1307 * Set the visibility of the item. This should do any necessary DB queries.
1308 *
1309 * The DB update query should have a condition which forces it to only update
1310 * if the value in the DB matches the value fetched earlier with the SELECT.
1311 * If the update fails because it did not match, the function should return
1312 * false. This prevents concurrency problems.
1313 *
1314 * @return boolean success
1315 */
1316 abstract public function setBits( $newBits );
1317 }
1318
1319 /**
1320 * List for revision table items
1321 */
1322 class RevDel_RevisionList extends RevDel_List {
1323 var $currentRevId;
1324 var $type = 'revision';
1325 var $idField = 'rev_id';
1326 var $dateField = 'rev_timestamp';
1327 var $authorIdField = 'rev_user';
1328 var $authorNameField = 'rev_user_text';
1329
1330 public function doQuery( $db ) {
1331 $ids = array_map( 'intval', $this->ids );
1332 return $db->select( array('revision','page'), '*',
1333 array(
1334 'rev_page' => $this->title->getArticleID(),
1335 'rev_id' => $ids,
1336 'rev_page = page_id'
1337 ),
1338 __METHOD__,
1339 array( 'ORDER BY' => 'rev_id DESC' )
1340 );
1341 }
1342
1343 public function newItem( $row ) {
1344 return new RevDel_RevisionItem( $this, $row );
1345 }
1346
1347 public function getCurrent() {
1348 if ( is_null( $this->currentRevId ) ) {
1349 $dbw = wfGetDB( DB_MASTER );
1350 $this->currentRevId = $dbw->selectField(
1351 'page', 'page_latest', $this->title->pageCond(), __METHOD__ );
1352 }
1353 return $this->currentRevId;
1354 }
1355
1356 public function getSuppressBit() {
1357 return Revision::DELETED_RESTRICTED;
1358 }
1359
1360 public function doPreCommitUpdates() {
1361 $this->title->invalidateCache();
1362 return Status::newGood();
1363 }
1364
1365 public function doPostCommitUpdates() {
1366 $this->title->purgeSquid();
1367 // Extensions that require referencing previous revisions may need this
1368 wfRunHooks( 'ArticleRevisionVisiblitySet', array( &$this->title ) );
1369 return Status::newGood();
1370 }
1371 }
1372
1373 /**
1374 * Item class for a revision table row
1375 */
1376 class RevDel_RevisionItem extends RevDel_Item {
1377 var $revision;
1378
1379 public function __construct( $list, $row ) {
1380 parent::__construct( $list, $row );
1381 $this->revision = new Revision( $row );
1382 }
1383
1384 public function canView() {
1385 return $this->revision->userCan( Revision::DELETED_RESTRICTED );
1386 }
1387
1388 public function canViewContent() {
1389 return $this->revision->userCan( Revision::DELETED_TEXT );
1390 }
1391
1392 public function getBits() {
1393 return $this->revision->mDeleted;
1394 }
1395
1396 public function setBits( $bits ) {
1397 $dbw = wfGetDB( DB_MASTER );
1398 // Update revision table
1399 $dbw->update( 'revision',
1400 array( 'rev_deleted' => $bits ),
1401 array(
1402 'rev_id' => $this->revision->getId(),
1403 'rev_page' => $this->revision->getPage(),
1404 'rev_deleted' => $this->getBits()
1405 ),
1406 __METHOD__
1407 );
1408 if ( !$dbw->affectedRows() ) {
1409 // Concurrent fail!
1410 return false;
1411 }
1412 // Update recentchanges table
1413 $dbw->update( 'recentchanges',
1414 array(
1415 'rc_deleted' => $bits,
1416 'rc_patrolled' => 1
1417 ),
1418 array(
1419 'rc_this_oldid' => $this->revision->getId(), // condition
1420 // non-unique timestamp index
1421 'rc_timestamp' => $dbw->timestamp( $this->revision->getTimestamp() ),
1422 ),
1423 __METHOD__
1424 );
1425 return true;
1426 }
1427
1428 public function isDeleted() {
1429 return $this->revision->isDeleted( Revision::DELETED_TEXT );
1430 }
1431
1432 public function isHideCurrentOp( $newBits ) {
1433 return ( $newBits & Revision::DELETED_TEXT )
1434 && $this->list->getCurrent() == $this->getId();
1435 }
1436
1437 /**
1438 * Get the HTML link to the revision text.
1439 * Overridden by RevDel_ArchiveItem.
1440 */
1441 protected function getRevisionLink() {
1442 global $wgLang;
1443 $date = $wgLang->timeanddate( $this->revision->getTimestamp(), true );
1444 if ( $this->isDeleted() && !$this->canViewContent() ) {
1445 return $date;
1446 }
1447 return $this->special->skin->link(
1448 $this->list->title,
1449 $date,
1450 array(),
1451 array(
1452 'oldid' => $this->revision->getId(),
1453 'unhide' => 1
1454 )
1455 );
1456 }
1457
1458 /**
1459 * Get the HTML link to the diff.
1460 * Overridden by RevDel_ArchiveItem
1461 */
1462 protected function getDiffLink() {
1463 if ( $this->isDeleted() && !$this->canViewContent() ) {
1464 return wfMsgHtml('diff');
1465 } else {
1466 return
1467 $this->special->skin->link(
1468 $this->list->title,
1469 wfMsgHtml('diff'),
1470 array(),
1471 array(
1472 'diff' => $this->revision->getId(),
1473 'oldid' => 'prev',
1474 'unhide' => 1
1475 ),
1476 array(
1477 'known',
1478 'noclasses'
1479 )
1480 );
1481 }
1482 }
1483
1484 public function getHTML() {
1485 $difflink = $this->getDiffLink();
1486 $revlink = $this->getRevisionLink();
1487 $userlink = $this->special->skin->revUserLink( $this->revision );
1488 $comment = $this->special->skin->revComment( $this->revision );
1489 if ( $this->isDeleted() ) {
1490 $revlink = "<span class=\"history-deleted\">$revlink</span>";
1491 }
1492 return "<li>($difflink) $revlink $userlink $comment</li>";
1493 }
1494 }
1495
1496 /**
1497 * List for archive table items, i.e. revisions deleted via action=delete
1498 */
1499 class RevDel_ArchiveList extends RevDel_RevisionList {
1500 var $type = 'archive';
1501 var $idField = 'ar_timestamp';
1502 var $dateField = 'ar_timestamp';
1503 var $authorIdField = 'ar_user';
1504 var $authorNameField = 'ar_user_text';
1505
1506 public function doQuery( $db ) {
1507 $timestamps = array();
1508 foreach ( $this->ids as $id ) {
1509 $timestamps[] = $db->timestamp( $id );
1510 }
1511 return $db->select( 'archive', '*',
1512 array(
1513 'ar_namespace' => $this->title->getNamespace(),
1514 'ar_title' => $this->title->getDBkey(),
1515 'ar_timestamp' => $timestamps
1516 ),
1517 __METHOD__,
1518 array( 'ORDER BY' => 'ar_timestamp DESC' )
1519 );
1520 }
1521
1522 public function newItem( $row ) {
1523 return new RevDel_ArchiveItem( $this, $row );
1524 }
1525
1526 public function doPreCommitUpdates() {
1527 return Status::newGood();
1528 }
1529
1530 public function doPostCommitUpdates() {
1531 return Status::newGood();
1532 }
1533 }
1534
1535 /**
1536 * Item class for a archive table row
1537 */
1538 class RevDel_ArchiveItem extends RevDel_RevisionItem {
1539 public function __construct( $list, $row ) {
1540 RevDel_Item::__construct( $list, $row );
1541 $this->revision = Revision::newFromArchiveRow( $row,
1542 array( 'page' => $this->list->title->getArticleId() ) );
1543 }
1544
1545 public function getId() {
1546 # Convert DB timestamp to MW timestamp
1547 return $this->revision->getTimestamp();
1548 }
1549
1550 public function setBits( $bits ) {
1551 $dbw = wfGetDB( DB_MASTER );
1552 $dbw->update( 'archive',
1553 array( 'ar_deleted' => $bits ),
1554 array( 'ar_namespace' => $this->list->title->getNamespace(),
1555 'ar_title' => $this->list->title->getDBkey(),
1556 // use timestamp for index
1557 'ar_timestamp' => $this->row->ar_timestamp,
1558 'ar_rev_id' => $this->row->ar_rev_id,
1559 'ar_deleted' => $this->getBits()
1560 ),
1561 __METHOD__ );
1562 return (bool)$dbw->affectedRows();
1563 }
1564
1565 protected function getRevisionLink() {
1566 global $wgLang;
1567 $undelete = SpecialPage::getTitleFor( 'Undelete' );
1568 $date = $wgLang->timeanddate( $this->revision->getTimestamp(), true );
1569 if ( $this->isDeleted() && !$this->canViewContent() ) {
1570 return $date;
1571 }
1572 return $this->special->skin->link( $undelete, $date, array(),
1573 array(
1574 'target' => $this->list->title->getPrefixedText(),
1575 'timestamp' => $this->revision->getTimestamp()
1576 ) );
1577 }
1578
1579 protected function getDiffLink() {
1580 if ( $this->isDeleted() && !$this->canViewContent() ) {
1581 return wfMsgHtml( 'diff' );
1582 }
1583 $undelete = SpecialPage::getTitleFor( 'Undelete' );
1584 return $this->special->skin->link( $undelete, wfMsgHtml('diff'), array(),
1585 array(
1586 'target' => $this->list->title->getPrefixedText(),
1587 'diff' => 'prev',
1588 'timestamp' => $this->revision->getTimestamp()
1589 ) );
1590 }
1591 }
1592
1593 /**
1594 * List for oldimage table items
1595 */
1596 class RevDel_FileList extends RevDel_List {
1597 var $type = 'oldimage';
1598 var $idField = 'oi_archive_name';
1599 var $dateField = 'oi_timestamp';
1600 var $authorIdField = 'oi_user';
1601 var $authorNameField = 'oi_user_text';
1602 var $storeBatch, $deleteBatch, $cleanupBatch;
1603
1604 public function doQuery( $db ) {
1605 $archiveName = array();
1606 foreach( $this->ids as $timestamp ) {
1607 $archiveNames[] = $timestamp . '!' . $this->title->getDBkey();
1608 }
1609 return $db->select( 'oldimage', '*',
1610 array(
1611 'oi_name' => $this->title->getDBkey(),
1612 'oi_archive_name' => $archiveNames
1613 ),
1614 __METHOD__,
1615 array( 'ORDER BY' => 'oi_timestamp DESC' )
1616 );
1617 }
1618
1619 public function newItem( $row ) {
1620 return new RevDel_FileItem( $this, $row );
1621 }
1622
1623 public function clearFileOps() {
1624 $this->deleteBatch = array();
1625 $this->storeBatch = array();
1626 $this->cleanupBatch = array();
1627 }
1628
1629 public function doPreCommitUpdates() {
1630 $status = Status::newGood();
1631 $repo = RepoGroup::singleton()->getLocalRepo();
1632 if ( $this->storeBatch ) {
1633 $status->merge( $repo->storeBatch( $this->storeBatch, FileRepo::OVERWRITE_SAME ) );
1634 }
1635 if ( !$status->isOK() ) {
1636 return $status;
1637 }
1638 if ( $this->deleteBatch ) {
1639 $status->merge( $repo->deleteBatch( $this->deleteBatch ) );
1640 }
1641 if ( !$status->isOK() ) {
1642 // Running cleanupDeletedBatch() after a failed storeBatch() with the DB already
1643 // modified (but destined for rollback) causes data loss
1644 return $status;
1645 }
1646 if ( $this->cleanupBatch ) {
1647 $status->merge( $repo->cleanupDeletedBatch( $this->cleanupBatch ) );
1648 }
1649 return $status;
1650 }
1651
1652 public function doPostCommitUpdates() {
1653 $file = wfLocalFile( $this->title );
1654 $file->purgeCache();
1655 $file->purgeDescription();
1656 return Status::newGood();
1657 }
1658
1659 public function getSuppressBit() {
1660 return File::DELETED_RESTRICTED;
1661 }
1662 }
1663
1664 /**
1665 * Item class for an oldimage table row
1666 */
1667 class RevDel_FileItem extends RevDel_Item {
1668 var $file;
1669
1670 public function __construct( $list, $row ) {
1671 parent::__construct( $list, $row );
1672 $this->file = RepoGroup::singleton()->getLocalRepo()->newFileFromRow( $row );
1673 }
1674
1675 public function getId() {
1676 $parts = explode( '!', $this->row->oi_archive_name );
1677 return $parts[0];
1678 }
1679
1680 public function canView() {
1681 return $this->file->userCan( File::DELETED_RESTRICTED );
1682 }
1683
1684 public function canViewContent() {
1685 return $this->file->userCan( File::DELETED_FILE );
1686 }
1687
1688 public function getBits() {
1689 return $this->file->getVisibility();
1690 }
1691
1692 public function setBits( $bits ) {
1693 # Queue the file op
1694 # FIXME: move to LocalFile.php
1695 if ( $this->isDeleted() ) {
1696 if ( $bits & File::DELETED_FILE ) {
1697 # Still deleted
1698 } else {
1699 # Newly undeleted
1700 $key = $this->file->getStorageKey();
1701 $srcRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1702 $this->list->storeBatch[] = array(
1703 $this->file->repo->getVirtualUrl( 'deleted' ) . '/' . $srcRel,
1704 'public',
1705 $this->file->getRel()
1706 );
1707 $this->list->cleanupBatch[] = $key;
1708 }
1709 } elseif ( $bits & File::DELETED_FILE ) {
1710 # Newly deleted
1711 $key = $this->file->getStorageKey();
1712 $dstRel = $this->file->repo->getDeletedHashPath( $key ) . $key;
1713 $this->list->deleteBatch[] = array( $this->file->getRel(), $dstRel );
1714 }
1715
1716 # Do the database operations
1717 $dbw = wfGetDB( DB_MASTER );
1718 $dbw->update( 'oldimage',
1719 array( 'oi_deleted' => $bits ),
1720 array(
1721 'oi_name' => $this->row->oi_name,
1722 'oi_timestamp' => $this->row->oi_timestamp,
1723 'oi_deleted' => $this->getBits()
1724 ),
1725 __METHOD__
1726 );
1727 return (bool)$dbw->affectedRows();
1728 }
1729
1730 public function isDeleted() {
1731 return $this->file->isDeleted( File::DELETED_FILE );
1732 }
1733
1734 /**
1735 * Get the link to the file.
1736 * Overridden by RevDel_ArchivedFileItem.
1737 */
1738 protected function getLink() {
1739 global $wgLang, $wgUser;
1740 $date = $wgLang->timeanddate( $this->file->getTimestamp(), true );
1741 if ( $this->isDeleted() ) {
1742 # Hidden files...
1743 if ( !$this->canViewContent() ) {
1744 $link = $date;
1745 } else {
1746 $link = $this->special->skin->link(
1747 $this->special->getTitle(),
1748 $date, array(),
1749 array(
1750 'target' => $this->list->title->getPrefixedText(),
1751 'file' => $this->file->getArchiveName(),
1752 'token' => $wgUser->editToken( $this->file->getArchiveName() )
1753 )
1754 );
1755 }
1756 return '<span class="history-deleted">' . $link . '</span>';
1757 } else {
1758 # Regular files...
1759 $url = $this->file->getUrl();
1760 return Xml::element( 'a', array( 'href' => $this->file->getUrl() ), $date );
1761 }
1762 }
1763 /**
1764 * Generate a user tool link cluster if the current user is allowed to view it
1765 * @return string HTML
1766 */
1767 protected function getUserTools() {
1768 if( $this->file->userCan( Revision::DELETED_USER ) ) {
1769 $link = $this->special->skin->userLink( $this->file->user, $this->file->user_text ) .
1770 $this->special->skin->userToolLinks( $this->file->user, $this->file->user_text );
1771 } else {
1772 $link = wfMsgHtml( 'rev-deleted-user' );
1773 }
1774 if( $this->file->isDeleted( Revision::DELETED_USER ) ) {
1775 return '<span class="history-deleted">' . $link . '</span>';
1776 }
1777 return $link;
1778 }
1779
1780 /**
1781 * Wrap and format the file's comment block, if the current
1782 * user is allowed to view it.
1783 *
1784 * @return string HTML
1785 */
1786 protected function getComment() {
1787 if( $this->file->userCan( File::DELETED_COMMENT ) ) {
1788 $block = $this->special->skin->commentBlock( $this->file->description );
1789 } else {
1790 $block = ' ' . wfMsgHtml( 'rev-deleted-comment' );
1791 }
1792 if( $this->file->isDeleted( File::DELETED_COMMENT ) ) {
1793 return "<span class=\"history-deleted\">$block</span>";
1794 }
1795 return $block;
1796 }
1797
1798 public function getHTML() {
1799 global $wgLang;
1800 $data =
1801 wfMsg(
1802 'widthheight',
1803 $wgLang->formatNum( $this->file->getWidth() ),
1804 $wgLang->formatNum( $this->file->getHeight() )
1805 ) .
1806 ' (' .
1807 wfMsgExt( 'nbytes', 'parsemag', $wgLang->formatNum( $this->file->getSize() ) ) .
1808 ')';
1809 $pageLink = $this->getLink();
1810
1811 return '<li>' . $this->getLink() . ' ' . $this->getUserTools() . ' ' .
1812 $data . ' ' . $this->getComment(). '</li>';
1813 }
1814 }
1815
1816 /**
1817 * List for filearchive table items
1818 */
1819 class RevDel_ArchivedFileList extends RevDel_FileList {
1820 var $type = 'filearchive';
1821 var $idField = 'fa_id';
1822 var $dateField = 'fa_timestamp';
1823 var $authorIdField = 'fa_user';
1824 var $authorNameField = 'fa_user_text';
1825
1826 public function doQuery( $db ) {
1827 $ids = array_map( 'intval', $this->ids );
1828 return $db->select( 'filearchive', '*',
1829 array(
1830 'fa_name' => $this->title->getDBkey(),
1831 'fa_id' => $ids
1832 ),
1833 __METHOD__,
1834 array( 'ORDER BY' => 'fa_id DESC' )
1835 );
1836 }
1837
1838 public function newItem( $row ) {
1839 return new RevDel_ArchivedFileItem( $this, $row );
1840 }
1841 }
1842
1843 /**
1844 * Item class for a filearchive table row
1845 */
1846 class RevDel_ArchivedFileItem extends RevDel_FileItem {
1847 public function __construct( $list, $row ) {
1848 RevDel_Item::__construct( $list, $row );
1849 $this->file = ArchivedFile::newFromRow( $row );
1850 }
1851
1852 public function getId() {
1853 return $this->row->fa_id;
1854 }
1855
1856 public function setBits( $bits ) {
1857 $dbw = wfGetDB( DB_MASTER );
1858 $dbw->update( 'filearchive',
1859 array( 'fa_deleted' => $bits ),
1860 array(
1861 'fa_id' => $this->row->fa_id,
1862 'fa_deleted' => $this->getBits(),
1863 ),
1864 __METHOD__
1865 );
1866 return (bool)$dbw->affectedRows();
1867 }
1868
1869 protected function getLink() {
1870 global $wgLang, $wgUser;
1871 $date = $wgLang->timeanddate( $this->file->getTimestamp(), true );
1872 $undelete = SpecialPage::getTitleFor( 'Undelete' );
1873 $key = $this->file->getKey();
1874 # Hidden files...
1875 if( !$this->canViewContent() ) {
1876 $link = $date;
1877 } else {
1878 $link = $this->special->skin->link( $undelete, $date, array(),
1879 array(
1880 'target' => $this->list->title->getPrefixedText(),
1881 'file' => $key,
1882 'token' => $wgUser->editToken( $key )
1883 )
1884 );
1885 }
1886 if( $this->isDeleted() ) {
1887 $link = '<span class="history-deleted">' . $link . '</span>';
1888 }
1889 return $link;
1890 }
1891 }
1892
1893 /**
1894 * List for logging table items
1895 */
1896 class RevDel_LogList extends RevDel_List {
1897 var $type = 'logging';
1898 var $idField = 'log_id';
1899 var $dateField = 'log_timestamp';
1900 var $authorIdField = 'log_user';
1901 var $authorNameField = 'log_user_text';
1902
1903 public function doQuery( $db ) {
1904 global $wgMessageCache;
1905 $wgMessageCache->loadAllMessages();
1906 $ids = array_map( 'intval', $this->ids );
1907 return $db->select( 'logging', '*',
1908 array( 'log_id' => $ids ),
1909 __METHOD__,
1910 array( 'ORDER BY' => 'log_id DESC' )
1911 );
1912 }
1913
1914 public function newItem( $row ) {
1915 return new RevDel_LogItem( $this, $row );
1916 }
1917
1918 public function getSuppressBit() {
1919 return Revision::DELETED_RESTRICTED;
1920 }
1921
1922 public function getLogAction() {
1923 return 'event';
1924 }
1925
1926 public function getLogParams( $params ) {
1927 return array(
1928 implode( ',', $params['ids'] ),
1929 "ofield={$params['oldBits']}",
1930 "nfield={$params['newBits']}"
1931 );
1932 }
1933 }
1934
1935 /**
1936 * Item class for a logging table row
1937 */
1938 class RevDel_LogItem extends RevDel_Item {
1939 public function canView() {
1940 return LogEventsList::userCan( $this->row, Revision::DELETED_RESTRICTED );
1941 }
1942
1943 public function canViewContent() {
1944 return true; // none
1945 }
1946
1947 public function getBits() {
1948 return $this->row->log_deleted;
1949 }
1950
1951 public function setBits( $bits ) {
1952 $dbw = wfGetDB( DB_MASTER );
1953 $dbw->update( 'recentchanges',
1954 array(
1955 'rc_deleted' => $bits,
1956 'rc_patrolled' => 1
1957 ),
1958 array(
1959 'rc_logid' => $this->row->log_id,
1960 'rc_timestamp' => $this->row->log_timestamp // index
1961 ),
1962 __METHOD__
1963 );
1964 $dbw->update( 'logging',
1965 array( 'log_deleted' => $bits ),
1966 array(
1967 'log_id' => $this->row->log_id,
1968 'log_deleted' => $this->getBits()
1969 ),
1970 __METHOD__
1971 );
1972 return (bool)$dbw->affectedRows();
1973 }
1974
1975 public function getHTML() {
1976 global $wgLang;
1977
1978 $date = htmlspecialchars( $wgLang->timeanddate( $this->row->log_timestamp ) );
1979 $paramArray = LogPage::extractParams( $this->row->log_params );
1980 $title = Title::makeTitle( $this->row->log_namespace, $this->row->log_title );
1981
1982 // Log link for this page
1983 $loglink = $this->special->skin->link(
1984 SpecialPage::getTitleFor( 'Log' ),
1985 wfMsgHtml( 'log' ),
1986 array(),
1987 array( 'page' => $title->getPrefixedText() )
1988 );
1989 // Action text
1990 if( !$this->canView() ) {
1991 $action = '<span class="history-deleted">' . wfMsgHtml('rev-deleted-event') . '</span>';
1992 } else {
1993 $action = LogPage::actionText( $this->row->log_type, $this->row->log_action, $title,
1994 $this->special->skin, $paramArray, true, true );
1995 if( $this->row->log_deleted & LogPage::DELETED_ACTION )
1996 $action = '<span class="history-deleted">' . $action . '</span>';
1997 }
1998 // User links
1999 $userLink = $this->special->skin->userLink( $this->row->log_user,
2000 User::WhoIs( $this->row->log_user ) );
2001 if( LogEventsList::isDeleted($this->row,LogPage::DELETED_USER) ) {
2002 $userLink = '<span class="history-deleted">' . $userLink . '</span>';
2003 }
2004 // Comment
2005 $comment = $wgLang->getDirMark() . $this->special->skin->commentBlock( $this->row->log_comment );
2006 if( LogEventsList::isDeleted($this->row,LogPage::DELETED_COMMENT) ) {
2007 $comment = '<span class="history-deleted">' . $comment . '</span>';
2008 }
2009 return "<li>($loglink) $date $userLink $action $comment</li>";
2010 }
2011 }