Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[lhc/web/wiklou.git] / includes / FileDeleteForm.php
1 <?php
2 /**
3 * File deletion user interface.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @author Rob Church <robchur@gmail.com>
22 * @ingroup Media
23 */
24 use MediaWiki\MediaWikiServices;
25
26 /**
27 * File deletion user interface
28 *
29 * @ingroup Media
30 */
31 class FileDeleteForm {
32
33 /**
34 * @var Title
35 */
36 private $title = null;
37
38 /**
39 * @var File
40 */
41 private $file = null;
42
43 /**
44 * @var File
45 */
46 private $oldfile = null;
47 private $oldimage = '';
48
49 /**
50 * @param File $file File object we're deleting
51 */
52 public function __construct( $file ) {
53 $this->title = $file->getTitle();
54 $this->file = $file;
55 }
56
57 /**
58 * Fulfil the request; shows the form or deletes the file,
59 * pending authentication, confirmation, etc.
60 */
61 public function execute() {
62 global $wgOut, $wgRequest, $wgUser, $wgUploadMaintenance;
63
64 $permissionErrors = $this->title->getUserPermissionsErrors( 'delete', $wgUser );
65 if ( count( $permissionErrors ) ) {
66 throw new PermissionsError( 'delete', $permissionErrors );
67 }
68
69 if ( wfReadOnly() ) {
70 throw new ReadOnlyError;
71 }
72
73 if ( $wgUploadMaintenance ) {
74 throw new ErrorPageError( 'filedelete-maintenance-title', 'filedelete-maintenance' );
75 }
76
77 $this->setHeaders();
78
79 $this->oldimage = $wgRequest->getText( 'oldimage', false );
80 $token = $wgRequest->getText( 'wpEditToken' );
81 # Flag to hide all contents of the archived revisions
82 $suppress = $wgRequest->getCheck( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
83
84 if ( $this->oldimage ) {
85 $this->oldfile = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName(
86 $this->title,
87 $this->oldimage
88 );
89 }
90
91 if ( !self::haveDeletableFile( $this->file, $this->oldfile, $this->oldimage ) ) {
92 $wgOut->addHTML( $this->prepareMessage( 'filedelete-nofile' ) );
93 $wgOut->addReturnTo( $this->title );
94 return;
95 }
96
97 // Perform the deletion if appropriate
98 if ( $wgRequest->wasPosted() && $wgUser->matchEditToken( $token, $this->oldimage ) ) {
99 $deleteReasonList = $wgRequest->getText( 'wpDeleteReasonList' );
100 $deleteReason = $wgRequest->getText( 'wpReason' );
101
102 if ( $deleteReasonList == 'other' ) {
103 $reason = $deleteReason;
104 } elseif ( $deleteReason != '' ) {
105 // Entry from drop down menu + additional comment
106 $reason = $deleteReasonList . wfMessage( 'colon-separator' )
107 ->inContentLanguage()->text() . $deleteReason;
108 } else {
109 $reason = $deleteReasonList;
110 }
111
112 $status = self::doDelete(
113 $this->title,
114 $this->file,
115 $this->oldimage,
116 $reason,
117 $suppress,
118 $wgUser
119 );
120
121 if ( !$status->isGood() ) {
122 $wgOut->addHTML( '<h2>' . $this->prepareMessage( 'filedeleteerror-short' ) . "</h2>\n" );
123 $wgOut->wrapWikiTextAsInterface(
124 'error',
125 $status->getWikiText( 'filedeleteerror-short', 'filedeleteerror-long' )
126 );
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
144 /**
145 * Really delete the file
146 *
147 * @param Title &$title
148 * @param File &$file
149 * @param string &$oldimage Archive name
150 * @param string $reason Reason of the deletion
151 * @param bool $suppress Whether to mark all deleted versions as restricted
152 * @param User|null $user User object performing the request
153 * @param array $tags Tags to apply to the deletion action
154 * @throws MWException
155 * @return Status
156 */
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',
190 wfEscapeWikiText( $title->getPrefixedText() )
191 );
192 $page = WikiPage::factory( $title );
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 if ( $deleteStatus->value === null ) {
205 // No log ID from doDeleteArticleReal(), probably
206 // because the page/revision didn't exist, so create
207 // one here.
208 $logtype = $suppress ? 'suppress' : 'delete';
209 $logEntry = new ManualLogEntry( $logtype, 'delete' );
210 $logEntry->setPerformer( $user );
211 $logEntry->setTarget( clone $title );
212 $logEntry->setComment( $reason );
213 $logEntry->setTags( $tags );
214 $logid = $logEntry->insert();
215 $dbw->onTransactionPreCommitOrIdle(
216 function () use ( $logEntry, $logid ) {
217 $logEntry->publish( $logid );
218 },
219 __METHOD__
220 );
221 $status->value = $logid;
222 } else {
223 $status->value = $deleteStatus->value; // log id
224 }
225 $dbw->endAtomic( __METHOD__ );
226 } else {
227 // Page deleted but file still there? rollback page delete
228 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
229 $lbFactory->rollbackMasterChanges( __METHOD__ );
230 }
231 } else {
232 $dbw->endAtomic( __METHOD__ );
233 }
234 }
235
236 if ( $status->isOK() ) {
237 Hooks::run( 'FileDeleteComplete', [ &$file, &$oldimage, &$page, &$user, &$reason ] );
238 }
239
240 return $status;
241 }
242
243 /**
244 * Show the confirmation form
245 */
246 private function showForm() {
247 global $wgOut, $wgUser, $wgRequest;
248
249 $wgOut->addModules( 'mediawiki.action.delete.file' );
250
251 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $wgUser->isWatched( $this->title );
252
253 $wgOut->enableOOUI();
254
255 $options = Xml::listDropDownOptions(
256 $wgOut->msg( 'filedelete-reason-dropdown' )->inContentLanguage()->text(),
257 [ 'other' => $wgOut->msg( 'filedelete-reason-otherlist' )->inContentLanguage()->text() ]
258 );
259 $options = Xml::listDropDownOptionsOoui( $options );
260
261 $fields[] = new OOUI\LabelWidget( [ 'label' => new OOUI\HtmlSnippet(
262 $this->prepareMessage( 'filedelete-intro' ) ) ]
263 );
264
265 $fields[] = new OOUI\FieldLayout(
266 new OOUI\DropdownInputWidget( [
267 'name' => 'wpDeleteReasonList',
268 'inputId' => 'wpDeleteReasonList',
269 'tabIndex' => 1,
270 'infusable' => true,
271 'value' => '',
272 'options' => $options,
273 ] ),
274 [
275 'label' => $wgOut->msg( 'filedelete-comment' )->text(),
276 'align' => 'top',
277 ]
278 );
279
280 // HTML maxlength uses "UTF-16 code units", which means that characters outside BMP
281 // (e.g. emojis) count for two each. This limit is overridden in JS to instead count
282 // Unicode codepoints.
283 $fields[] = new OOUI\FieldLayout(
284 new OOUI\TextInputWidget( [
285 'name' => 'wpReason',
286 'inputId' => 'wpReason',
287 'tabIndex' => 2,
288 'maxLength' => CommentStore::COMMENT_CHARACTER_LIMIT,
289 'infusable' => true,
290 'value' => $wgRequest->getText( 'wpReason' ),
291 'autofocus' => true,
292 ] ),
293 [
294 'label' => $wgOut->msg( 'filedelete-otherreason' )->text(),
295 'align' => 'top',
296 ]
297 );
298
299 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
300 $fields[] = new OOUI\FieldLayout(
301 new OOUI\CheckboxInputWidget( [
302 'name' => 'wpSuppress',
303 'inputId' => 'wpSuppress',
304 'tabIndex' => 3,
305 'selected' => false,
306 ] ),
307 [
308 'label' => $wgOut->msg( 'revdelete-suppress' )->text(),
309 'align' => 'inline',
310 'infusable' => true,
311 ]
312 );
313 }
314
315 if ( $wgUser->isLoggedIn() ) {
316 $fields[] = new OOUI\FieldLayout(
317 new OOUI\CheckboxInputWidget( [
318 'name' => 'wpWatch',
319 'inputId' => 'wpWatch',
320 'tabIndex' => 3,
321 'selected' => $checkWatch,
322 ] ),
323 [
324 'label' => $wgOut->msg( 'watchthis' )->text(),
325 'align' => 'inline',
326 'infusable' => true,
327 ]
328 );
329 }
330
331 $fields[] = new OOUI\FieldLayout(
332 new OOUI\ButtonInputWidget( [
333 'name' => 'mw-filedelete-submit',
334 'inputId' => 'mw-filedelete-submit',
335 'tabIndex' => 4,
336 'value' => $wgOut->msg( 'filedelete-submit' )->text(),
337 'label' => $wgOut->msg( 'filedelete-submit' )->text(),
338 'flags' => [ 'primary', 'destructive' ],
339 'type' => 'submit',
340 ] ),
341 [
342 'align' => 'top',
343 ]
344 );
345
346 $fieldset = new OOUI\FieldsetLayout( [
347 'label' => $wgOut->msg( 'filedelete-legend' )->text(),
348 'items' => $fields,
349 ] );
350
351 $form = new OOUI\FormLayout( [
352 'method' => 'post',
353 'action' => $this->getAction(),
354 'id' => 'mw-img-deleteconfirm',
355 ] );
356 $form->appendContent(
357 $fieldset,
358 new OOUI\HtmlSnippet(
359 Html::hidden( 'wpEditToken', $wgUser->getEditToken( $this->oldimage ) )
360 )
361 );
362
363 $wgOut->addHTML(
364 new OOUI\PanelLayout( [
365 'classes' => [ 'deletepage-wrapper' ],
366 'expanded' => false,
367 'padded' => true,
368 'framed' => true,
369 'content' => $form,
370 ] )
371 );
372
373 if ( $wgUser->isAllowed( 'editinterface' ) ) {
374 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
375 $link = $linkRenderer->makeKnownLink(
376 $wgOut->msg( 'filedelete-reason-dropdown' )->inContentLanguage()->getTitle(),
377 wfMessage( 'filedelete-edit-reasonlist' )->text(),
378 [],
379 [ 'action' => 'edit' ]
380 );
381 $wgOut->addHTML( '<p class="mw-filedelete-editreasons">' . $link . '</p>' );
382 }
383 }
384
385 /**
386 * Show deletion log fragments pertaining to the current file
387 */
388 private function showLogEntries() {
389 global $wgOut;
390 $deleteLogPage = new LogPage( 'delete' );
391 $wgOut->addHTML( '<h2>' . $deleteLogPage->getName()->escaped() . "</h2>\n" );
392 LogEventsList::showLogExtract( $wgOut, 'delete', $this->title );
393 }
394
395 /**
396 * Prepare a message referring to the file being deleted,
397 * showing an appropriate message depending upon whether
398 * it's a current file or an old version
399 *
400 * @param string $message Message base
401 * @return string
402 */
403 private function prepareMessage( $message ) {
404 global $wgLang;
405 if ( $this->oldimage ) {
406 # Message keys used:
407 # 'filedelete-intro-old', 'filedelete-nofile-old', 'filedelete-success-old'
408 return wfMessage(
409 "{$message}-old",
410 wfEscapeWikiText( $this->title->getText() ),
411 $wgLang->date( $this->getTimestamp(), true ),
412 $wgLang->time( $this->getTimestamp(), true ),
413 wfExpandUrl( $this->file->getArchiveUrl( $this->oldimage ), PROTO_CURRENT ) )->parseAsBlock();
414 } else {
415 return wfMessage(
416 $message,
417 wfEscapeWikiText( $this->title->getText() )
418 )->parseAsBlock();
419 }
420 }
421
422 /**
423 * Set headers, titles and other bits
424 */
425 private function setHeaders() {
426 global $wgOut;
427 $wgOut->setPageTitle( wfMessage( 'filedelete', $this->title->getText() ) );
428 $wgOut->setRobotPolicy( 'noindex,nofollow' );
429 $wgOut->addBacklinkSubtitle( $this->title );
430 }
431
432 /**
433 * Is the provided `oldimage` value valid?
434 *
435 * @param string $oldimage
436 * @return bool
437 */
438 public static function isValidOldSpec( $oldimage ) {
439 return strlen( $oldimage ) >= 16
440 && strpos( $oldimage, '/' ) === false
441 && strpos( $oldimage, '\\' ) === false;
442 }
443
444 /**
445 * Could we delete the file specified? If an `oldimage`
446 * value was provided, does it correspond to an
447 * existing, local, old version of this file?
448 *
449 * @param File &$file
450 * @param File &$oldfile
451 * @param File $oldimage
452 * @return bool
453 */
454 public static function haveDeletableFile( &$file, &$oldfile, $oldimage ) {
455 return $oldimage
456 ? $oldfile && $oldfile->exists() && $oldfile->isLocal()
457 : $file && $file->exists() && $file->isLocal();
458 }
459
460 /**
461 * Prepare the form action
462 *
463 * @return string
464 */
465 private function getAction() {
466 $q = [];
467 $q['action'] = 'delete';
468
469 if ( $this->oldimage ) {
470 $q['oldimage'] = $this->oldimage;
471 }
472
473 return $this->title->getLocalURL( $q );
474 }
475
476 /**
477 * Extract the timestamp of the old version
478 *
479 * @return string
480 */
481 private function getTimestamp() {
482 return $this->oldfile->getTimestamp();
483 }
484 }