MediaWiki  1.27.2
FileDeleteForm.php
Go to the documentation of this file.
1 <?php
31 
35  private $title = null;
36 
40  private $file = null;
41 
45  private $oldfile = null;
46  private $oldimage = '';
47 
53  public function __construct( $file ) {
54  $this->title = $file->getTitle();
55  $this->file = $file;
56  }
57 
62  public function execute() {
63  global $wgOut, $wgRequest, $wgUser, $wgUploadMaintenance;
64 
65  $permissionErrors = $this->title->getUserPermissionsErrors( 'delete', $wgUser );
66  if ( count( $permissionErrors ) ) {
67  throw new PermissionsError( 'delete', $permissionErrors );
68  }
69 
70  if ( wfReadOnly() ) {
71  throw new ReadOnlyError;
72  }
73 
74  if ( $wgUploadMaintenance ) {
75  throw new ErrorPageError( 'filedelete-maintenance-title', 'filedelete-maintenance' );
76  }
77 
78  $this->setHeaders();
79 
80  $this->oldimage = $wgRequest->getText( 'oldimage', false );
81  $token = $wgRequest->getText( 'wpEditToken' );
82  # Flag to hide all contents of the archived revisions
83  $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
84 
85  if ( $this->oldimage ) {
86  $this->oldfile = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName(
87  $this->title,
88  $this->oldimage
89  );
90  }
91 
92  if ( !self::haveDeletableFile( $this->file, $this->oldfile, $this->oldimage ) ) {
93  $wgOut->addHTML( $this->prepareMessage( 'filedelete-nofile' ) );
94  $wgOut->addReturnTo( $this->title );
95  return;
96  }
97 
98  // Perform the deletion if appropriate
99  if ( $wgRequest->wasPosted() && $wgUser->matchEditToken( $token, $this->oldimage ) ) {
100  $deleteReasonList = $wgRequest->getText( 'wpDeleteReasonList' );
101  $deleteReason = $wgRequest->getText( 'wpReason' );
102 
103  if ( $deleteReasonList == 'other' ) {
104  $reason = $deleteReason;
105  } elseif ( $deleteReason != '' ) {
106  // Entry from drop down menu + additional comment
107  $reason = $deleteReasonList . wfMessage( 'colon-separator' )
108  ->inContentLanguage()->text() . $deleteReason;
109  } else {
110  $reason = $deleteReasonList;
111  }
112 
113  $status = self::doDelete(
114  $this->title,
115  $this->file,
116  $this->oldimage,
117  $reason,
118  $suppress,
119  $wgUser
120  );
121 
122  if ( !$status->isGood() ) {
123  $wgOut->addHTML( '<h2>' . $this->prepareMessage( 'filedeleteerror-short' ) . "</h2>\n" );
124  $wgOut->addWikiText( '<div class="error">' .
125  $status->getWikiText( 'filedeleteerror-short', 'filedeleteerror-long' )
126  . '</div>' );
127  }
128  if ( $status->ok ) {
129  $wgOut->setPageTitle( wfMessage( 'actioncomplete' ) );
130  $wgOut->addHTML( $this->prepareMessage( 'filedelete-success' ) );
131  // Return to the main page if we just deleted all versions of the
132  // file, otherwise go back to the description page
133  $wgOut->addReturnTo( $this->oldimage ? $this->title : Title::newMainPage() );
134 
135  WatchAction::doWatchOrUnwatch( $wgRequest->getCheck( 'wpWatch' ), $this->title, $wgUser );
136  }
137  return;
138  }
139 
140  $this->showForm();
141  $this->showLogEntries();
142  }
143 
156  public static function doDelete( &$title, &$file, &$oldimage, $reason,
157  $suppress, User $user = null
158  ) {
159  if ( $user === null ) {
160  global $wgUser;
161  $user = $wgUser;
162  }
163 
164  if ( $oldimage ) {
165  $page = null;
166  $status = $file->deleteOld( $oldimage, $reason, $suppress, $user );
167  if ( $status->ok ) {
168  // Need to do a log item
169  $logComment = wfMessage( 'deletedrevision', $oldimage )->inContentLanguage()->text();
170  if ( trim( $reason ) != '' ) {
171  $logComment .= wfMessage( 'colon-separator' )
172  ->inContentLanguage()->text() . $reason;
173  }
174 
175  $logtype = $suppress ? 'suppress' : 'delete';
176 
177  $logEntry = new ManualLogEntry( $logtype, 'delete' );
178  $logEntry->setPerformer( $user );
179  $logEntry->setTarget( $title );
180  $logEntry->setComment( $logComment );
181  $logid = $logEntry->insert();
182  $logEntry->publish( $logid );
183 
184  $status->value = $logid;
185  }
186  } else {
187  $status = Status::newFatal( 'cannotdelete',
189  );
191  $dbw = wfGetDB( DB_MASTER );
192  try {
193  $dbw->startAtomic( __METHOD__ );
194  // delete the associated article first
195  $error = '';
196  $deleteStatus = $page->doDeleteArticleReal( $reason, $suppress, 0, false, $error, $user );
197  // doDeleteArticleReal() returns a non-fatal error status if the page
198  // or revision is missing, so check for isOK() rather than isGood()
199  if ( $deleteStatus->isOK() ) {
200  $status = $file->delete( $reason, $suppress, $user );
201  if ( $status->isOK() ) {
202  $status->value = $deleteStatus->value; // log id
203  $dbw->endAtomic( __METHOD__ );
204  } else {
205  // Page deleted but file still there? rollback page delete
206  $dbw->rollback( __METHOD__ );
207  }
208  } else {
209  // Done; nothing changed
210  $dbw->endAtomic( __METHOD__ );
211  }
212  } catch ( Exception $e ) {
213  // Rollback before returning to prevent UI from displaying
214  // incorrect "View or restore N deleted edits?"
215  $dbw->rollback( __METHOD__ );
216  throw $e;
217  }
218  }
219 
220  if ( $status->isOK() ) {
221  Hooks::run( 'FileDeleteComplete', [ &$file, &$oldimage, &$page, &$user, &$reason ] );
222  }
223 
224  return $status;
225  }
226 
230  private function showForm() {
232 
233  if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
234  $suppress = "<tr id=\"wpDeleteSuppressRow\">
235  <td></td>
236  <td class='mw-input'><strong>" .
237  Xml::checkLabel( wfMessage( 'revdelete-suppress' )->text(),
238  'wpSuppress', 'wpSuppress', false, [ 'tabindex' => '3' ] ) .
239  "</strong></td>
240  </tr>";
241  } else {
242  $suppress = '';
243  }
244 
245  $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $wgUser->isWatched( $this->title );
246  $form = Xml::openElement( 'form', [ 'method' => 'post', 'action' => $this->getAction(),
247  'id' => 'mw-img-deleteconfirm' ] ) .
248  Xml::openElement( 'fieldset' ) .
249  Xml::element( 'legend', null, wfMessage( 'filedelete-legend' )->text() ) .
250  Html::hidden( 'wpEditToken', $wgUser->getEditToken( $this->oldimage ) ) .
251  $this->prepareMessage( 'filedelete-intro' ) .
252  Xml::openElement( 'table', [ 'id' => 'mw-img-deleteconfirm-table' ] ) .
253  "<tr>
254  <td class='mw-label'>" .
255  Xml::label( wfMessage( 'filedelete-comment' )->text(), 'wpDeleteReasonList' ) .
256  "</td>
257  <td class='mw-input'>" .
259  'wpDeleteReasonList',
260  wfMessage( 'filedelete-reason-dropdown' )->inContentLanguage()->text(),
261  wfMessage( 'filedelete-reason-otherlist' )->inContentLanguage()->text(),
262  '',
263  'wpReasonDropDown',
264  1
265  ) .
266  "</td>
267  </tr>
268  <tr>
269  <td class='mw-label'>" .
270  Xml::label( wfMessage( 'filedelete-otherreason' )->text(), 'wpReason' ) .
271  "</td>
272  <td class='mw-input'>" .
273  Xml::input( 'wpReason', 60, $wgRequest->getText( 'wpReason' ),
274  [ 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ] ) .
275  "</td>
276  </tr>
277  {$suppress}";
278  if ( $wgUser->isLoggedIn() ) {
279  $form .= "
280  <tr>
281  <td></td>
282  <td class='mw-input'>" .
283  Xml::checkLabel( wfMessage( 'watchthis' )->text(),
284  'wpWatch', 'wpWatch', $checkWatch, [ 'tabindex' => '3' ] ) .
285  "</td>
286  </tr>";
287  }
288  $form .= "
289  <tr>
290  <td></td>
291  <td class='mw-submit'>" .
293  wfMessage( 'filedelete-submit' )->text(),
294  [
295  'name' => 'mw-filedelete-submit',
296  'id' => 'mw-filedelete-submit',
297  'tabindex' => '4'
298  ]
299  ) .
300  "</td>
301  </tr>" .
302  Xml::closeElement( 'table' ) .
303  Xml::closeElement( 'fieldset' ) .
304  Xml::closeElement( 'form' );
305 
306  if ( $wgUser->isAllowed( 'editinterface' ) ) {
307  $title = wfMessage( 'filedelete-reason-dropdown' )->inContentLanguage()->getTitle();
309  $title,
310  wfMessage( 'filedelete-edit-reasonlist' )->escaped(),
311  [],
312  [ 'action' => 'edit' ]
313  );
314  $form .= '<p class="mw-filedelete-editreasons">' . $link . '</p>';
315  }
316 
317  $wgOut->addHTML( $form );
318  }
319 
323  private function showLogEntries() {
324  global $wgOut;
325  $deleteLogPage = new LogPage( 'delete' );
326  $wgOut->addHTML( '<h2>' . $deleteLogPage->getName()->escaped() . "</h2>\n" );
327  LogEventsList::showLogExtract( $wgOut, 'delete', $this->title );
328  }
329 
338  private function prepareMessage( $message ) {
339  global $wgLang;
340  if ( $this->oldimage ) {
341  # Message keys used:
342  # 'filedelete-intro-old', 'filedelete-nofile-old', 'filedelete-success-old'
343  return wfMessage(
344  "{$message}-old",
345  wfEscapeWikiText( $this->title->getText() ),
346  $wgLang->date( $this->getTimestamp(), true ),
347  $wgLang->time( $this->getTimestamp(), true ),
348  wfExpandUrl( $this->file->getArchiveUrl( $this->oldimage ), PROTO_CURRENT ) )->parseAsBlock();
349  } else {
350  return wfMessage(
351  $message,
352  wfEscapeWikiText( $this->title->getText() )
353  )->parseAsBlock();
354  }
355  }
356 
360  private function setHeaders() {
361  global $wgOut;
362  $wgOut->setPageTitle( wfMessage( 'filedelete', $this->title->getText() ) );
363  $wgOut->setRobotPolicy( 'noindex,nofollow' );
364  $wgOut->addBacklinkSubtitle( $this->title );
365  }
366 
373  public static function isValidOldSpec( $oldimage ) {
374  return strlen( $oldimage ) >= 16
375  && strpos( $oldimage, '/' ) === false
376  && strpos( $oldimage, '\\' ) === false;
377  }
378 
389  public static function haveDeletableFile( &$file, &$oldfile, $oldimage ) {
390  return $oldimage
391  ? $oldfile && $oldfile->exists() && $oldfile->isLocal()
392  : $file && $file->exists() && $file->isLocal();
393  }
394 
400  private function getAction() {
401  $q = [];
402  $q['action'] = 'delete';
403 
404  if ( $this->oldimage ) {
405  $q['oldimage'] = $this->oldimage;
406  }
407 
408  return $this->title->getLocalURL( $q );
409  }
410 
416  private function getTimestamp() {
417  return $this->oldfile->getTimestamp();
418  }
419 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:99
prepareMessage($message)
Prepare a message referring to the file being deleted, showing an appropriate message depending upon ...
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
static linkKnown($target, $html=null, $customAttribs=[], $query=[], $options=[ 'known', 'noclasses'])
Identical to link(), except $options defaults to 'known'.
Definition: Linker.php:264
static element($element, $attribs=null, $contents= '', $allowShortTag=true)
Format an XML element with given attributes and, optionally, text content.
Definition: Xml.php:39
static newMainPage()
Create a new Title for the Main Page.
Definition: Title.php:569
Show an error when the wiki is locked/read-only and the user tries to do something that requires writ...
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException'returning false will NOT prevent logging $e
Definition: hooks.txt:1932
static hidden($name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:759
const PROTO_CURRENT
Definition: Defines.php:264
static input($name, $size=false, $value=false, $attribs=[])
Convenience function to build an HTML text input field.
Definition: Xml.php:275
getTimestamp()
Extract the timestamp of the old version.
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1449
isLocal()
Returns true if the file comes from the local file repository.
Definition: File.php:1836
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
wfExpandUrl($url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
static newFatal($message)
Factory function for fatal errors.
Definition: Status.php:89
getTitle()
Return the associated title object.
Definition: File.php:325
static submitButton($value, $attribs=[])
Convenience function to build an HTML submit button When $wgUseMediaWikiUIEverywhere is true it will ...
Definition: Xml.php:460
static label($label, $id, $attribs=[])
Convenience function to build an HTML form label.
Definition: Xml.php:359
static showLogExtract(&$out, $types=[], $page= '', $user= '', $param=[])
Show log extract.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
Definition: design.txt:56
the value to return A Title object or null for latest to be modified or replaced by the hook handler or if authentication is not possible after cache objects are set for highlighting & $link
Definition: hooks.txt:2581
Class to simplify the use of log pages.
Definition: LogPage.php:32
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition: hooks.txt:1798
static closeElement($element)
Shortcut to close an XML element.
Definition: Xml.php:118
wfEscapeWikiText($text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
wfReadOnly()
Check whether the wiki is in read-only mode.
We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing we can concentrate it all in an extension file
Definition: hooks.txt:93
An error page which can definitely be safely rendered using the OutputPage.
getAction()
Prepare the form action.
static singleton()
Get a RepoGroup instance.
Definition: RepoGroup.php:59
delete($reason, $suppress=false, $user=null)
Delete all versions of the file.
Definition: File.php:1930
static openElement($element, $attribs=null)
This opens an XML element.
Definition: Xml.php:109
setHeaders()
Set headers, titles and other bits.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock()-offset Set to overwrite offset parameter in $wgRequest set to ''to unsetoffset-wrap String Wrap the message in html(usually something like"&lt
title
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
static haveDeletableFile(&$file, &$oldfile, $oldimage)
Could we delete the file specified? If an oldimage value was provided, does it correspond to an exist...
static doDelete(&$title, &$file, &$oldimage, $reason, $suppress, User $user=null)
Really delete the file.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:242
showLogEntries()
Show deletion log fragments pertaining to the current file.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Class for creating log entries manually, to inject them into the database.
Definition: LogEntry.php:394
exists()
Returns true if file exists in the repository.
Definition: File.php:876
Show an error when a user tries to do something they do not have the necessary permissions for...
execute()
Fulfil the request; shows the form or deletes the file, pending authentication, confirmation, etc.
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set $status
Definition: hooks.txt:1004
static checkLabel($label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition: Xml.php:420
const DB_MASTER
Definition: Defines.php:47
$wgOut
Definition: Setup.php:804
showForm()
Show the confirmation form.
static isValidOldSpec($oldimage)
Is the provided oldimage value valid?
static doWatchOrUnwatch($watch, Title $title, User $user)
Watch or unwatch a page.
Definition: WatchAction.php:83
static listDropDown($name= '', $list= '', $other= '', $selected= '', $class= '', $tabindex=null)
Build a drop-down box from a textual list.
Definition: Xml.php:508
__construct($file)
Constructor.
File deletion user interface.
if(is_null($wgLocalTZoffset)) if(!$wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:657
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2338
$wgUser
Definition: Setup.php:794