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