MediaWiki  1.28.1
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->isOK() ) {
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 
157  public static function doDelete( &$title, &$file, &$oldimage, $reason,
158  $suppress, User $user = null, $tags = []
159  ) {
160  if ( $user === null ) {
161  global $wgUser;
162  $user = $wgUser;
163  }
164 
165  if ( $oldimage ) {
166  $page = null;
167  $status = $file->deleteOld( $oldimage, $reason, $suppress, $user );
168  if ( $status->ok ) {
169  // Need to do a log item
170  $logComment = wfMessage( 'deletedrevision', $oldimage )->inContentLanguage()->text();
171  if ( trim( $reason ) != '' ) {
172  $logComment .= wfMessage( 'colon-separator' )
173  ->inContentLanguage()->text() . $reason;
174  }
175 
176  $logtype = $suppress ? 'suppress' : 'delete';
177 
178  $logEntry = new ManualLogEntry( $logtype, 'delete' );
179  $logEntry->setPerformer( $user );
180  $logEntry->setTarget( $title );
181  $logEntry->setComment( $logComment );
182  $logEntry->setTags( $tags );
183  $logid = $logEntry->insert();
184  $logEntry->publish( $logid );
185 
186  $status->value = $logid;
187  }
188  } else {
189  $status = Status::newFatal( 'cannotdelete',
191  );
193  $dbw = wfGetDB( DB_MASTER );
194  $dbw->startAtomic( __METHOD__ );
195  // delete the associated article first
196  $error = '';
197  $deleteStatus = $page->doDeleteArticleReal( $reason, $suppress, 0, false, $error,
198  $user, $tags );
199  // doDeleteArticleReal() returns a non-fatal error status if the page
200  // or revision is missing, so check for isOK() rather than isGood()
201  if ( $deleteStatus->isOK() ) {
202  $status = $file->delete( $reason, $suppress, $user );
203  if ( $status->isOK() ) {
204  $status->value = $deleteStatus->value; // log id
205  $dbw->endAtomic( __METHOD__ );
206  } else {
207  // Page deleted but file still there? rollback page delete
208  wfGetLBFactory()->rollbackMasterChanges( __METHOD__ );
209  }
210  } else {
211  // Done; nothing changed
212  $dbw->endAtomic( __METHOD__ );
213  }
214  }
215 
216  if ( $status->isOK() ) {
217  Hooks::run( 'FileDeleteComplete', [ &$file, &$oldimage, &$page, &$user, &$reason ] );
218  }
219 
220  return $status;
221  }
222 
226  private function showForm() {
228 
229  if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
230  $suppress = "<tr id=\"wpDeleteSuppressRow\">
231  <td></td>
232  <td class='mw-input'><strong>" .
233  Xml::checkLabel( wfMessage( 'revdelete-suppress' )->text(),
234  'wpSuppress', 'wpSuppress', false, [ 'tabindex' => '3' ] ) .
235  "</strong></td>
236  </tr>";
237  } else {
238  $suppress = '';
239  }
240 
241  $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $wgUser->isWatched( $this->title );
242  $form = Xml::openElement( 'form', [ 'method' => 'post', 'action' => $this->getAction(),
243  'id' => 'mw-img-deleteconfirm' ] ) .
244  Xml::openElement( 'fieldset' ) .
245  Xml::element( 'legend', null, wfMessage( 'filedelete-legend' )->text() ) .
246  Html::hidden( 'wpEditToken', $wgUser->getEditToken( $this->oldimage ) ) .
247  $this->prepareMessage( 'filedelete-intro' ) .
248  Xml::openElement( 'table', [ 'id' => 'mw-img-deleteconfirm-table' ] ) .
249  "<tr>
250  <td class='mw-label'>" .
251  Xml::label( wfMessage( 'filedelete-comment' )->text(), 'wpDeleteReasonList' ) .
252  "</td>
253  <td class='mw-input'>" .
255  'wpDeleteReasonList',
256  wfMessage( 'filedelete-reason-dropdown' )->inContentLanguage()->text(),
257  wfMessage( 'filedelete-reason-otherlist' )->inContentLanguage()->text(),
258  '',
259  'wpReasonDropDown',
260  1
261  ) .
262  "</td>
263  </tr>
264  <tr>
265  <td class='mw-label'>" .
266  Xml::label( wfMessage( 'filedelete-otherreason' )->text(), 'wpReason' ) .
267  "</td>
268  <td class='mw-input'>" .
269  Xml::input( 'wpReason', 60, $wgRequest->getText( 'wpReason' ),
270  [ 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ] ) .
271  "</td>
272  </tr>
273  {$suppress}";
274  if ( $wgUser->isLoggedIn() ) {
275  $form .= "
276  <tr>
277  <td></td>
278  <td class='mw-input'>" .
279  Xml::checkLabel( wfMessage( 'watchthis' )->text(),
280  'wpWatch', 'wpWatch', $checkWatch, [ 'tabindex' => '3' ] ) .
281  "</td>
282  </tr>";
283  }
284  $form .= "
285  <tr>
286  <td></td>
287  <td class='mw-submit'>" .
289  wfMessage( 'filedelete-submit' )->text(),
290  [
291  'name' => 'mw-filedelete-submit',
292  'id' => 'mw-filedelete-submit',
293  'tabindex' => '4'
294  ]
295  ) .
296  "</td>
297  </tr>" .
298  Xml::closeElement( 'table' ) .
299  Xml::closeElement( 'fieldset' ) .
300  Xml::closeElement( 'form' );
301 
302  if ( $wgUser->isAllowed( 'editinterface' ) ) {
303  $title = wfMessage( 'filedelete-reason-dropdown' )->inContentLanguage()->getTitle();
305  $title,
306  wfMessage( 'filedelete-edit-reasonlist' )->escaped(),
307  [],
308  [ 'action' => 'edit' ]
309  );
310  $form .= '<p class="mw-filedelete-editreasons">' . $link . '</p>';
311  }
312 
313  $wgOut->addHTML( $form );
314  }
315 
319  private function showLogEntries() {
320  global $wgOut;
321  $deleteLogPage = new LogPage( 'delete' );
322  $wgOut->addHTML( '<h2>' . $deleteLogPage->getName()->escaped() . "</h2>\n" );
323  LogEventsList::showLogExtract( $wgOut, 'delete', $this->title );
324  }
325 
334  private function prepareMessage( $message ) {
335  global $wgLang;
336  if ( $this->oldimage ) {
337  # Message keys used:
338  # 'filedelete-intro-old', 'filedelete-nofile-old', 'filedelete-success-old'
339  return wfMessage(
340  "{$message}-old",
341  wfEscapeWikiText( $this->title->getText() ),
342  $wgLang->date( $this->getTimestamp(), true ),
343  $wgLang->time( $this->getTimestamp(), true ),
344  wfExpandUrl( $this->file->getArchiveUrl( $this->oldimage ), PROTO_CURRENT ) )->parseAsBlock();
345  } else {
346  return wfMessage(
347  $message,
348  wfEscapeWikiText( $this->title->getText() )
349  )->parseAsBlock();
350  }
351  }
352 
356  private function setHeaders() {
357  global $wgOut;
358  $wgOut->setPageTitle( wfMessage( 'filedelete', $this->title->getText() ) );
359  $wgOut->setRobotPolicy( 'noindex,nofollow' );
360  $wgOut->addBacklinkSubtitle( $this->title );
361  }
362 
369  public static function isValidOldSpec( $oldimage ) {
370  return strlen( $oldimage ) >= 16
371  && strpos( $oldimage, '/' ) === false
372  && strpos( $oldimage, '\\' ) === false;
373  }
374 
385  public static function haveDeletableFile( &$file, &$oldfile, $oldimage ) {
386  return $oldimage
387  ? $oldfile && $oldfile->exists() && $oldfile->isLocal()
388  : $file && $file->exists() && $file->isLocal();
389  }
390 
396  private function getAction() {
397  $q = [];
398  $q['action'] = 'delete';
399 
400  if ( $this->oldimage ) {
401  $q['oldimage'] = $this->oldimage;
402  }
403 
404  return $this->title->getLocalURL( $q );
405  }
406 
412  private function getTimestamp() {
413  return $this->oldfile->getTimestamp();
414  }
415 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:115
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 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:556
Show an error when the wiki is locked/read-only and the user tries to do something that requires writ...
if(!$wgDBerrorLogTZ) $wgRequest
Definition: Setup.php:664
static newFatal($message)
Factory function for fatal errors.
Definition: StatusValue.php:63
static hidden($name, $value, array $attribs=[])
Convenience function to produce an input element with type=hidden.
Definition: Html.php:758
const PROTO_CURRENT
Definition: Defines.php:226
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:1455
isLocal()
Returns true if the file comes from the local file repository.
Definition: File.php:1835
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.
title
getTitle()
Return the associated title object.
Definition: File.php:325
const DB_MASTER
Definition: defines.php:23
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
Class to simplify the use of log pages.
Definition: LogPage.php:32
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:2889
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:1936
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.
either a unescaped string or a HtmlArmor object 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
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:1929
static openElement($element, $attribs=null)
This opens an XML element.
Definition: Xml.php:109
setHeaders()
Set headers, titles and other bits.
static doDelete(&$title, &$file, &$oldimage, $reason, $suppress, User $user=null, $tags=[])
Really delete the file.
static linkKnown($target, $html=null, $customAttribs=[], $query=[], $options=[ 'known'])
Identical to link(), except $options defaults to 'known'.
Definition: Linker.php:255
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...
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
wfGetLBFactory()
Get the load balancer factory object.
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:1046
static checkLabel($label, $name, $id, $checked=false, $attribs=[])
Convenience function to build an HTML checkbox with a label.
Definition: Xml.php:420
$wgOut
Definition: Setup.php:816
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:84
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.
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:2491
$wgUser
Definition: Setup.php:806