Fix and make some types in PHPDoc and JSDoc tags more specific
[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 * Constructor
51 *
52 * @param File $file File object we're deleting
53 */
54 public function __construct( $file ) {
55 $this->title = $file->getTitle();
56 $this->file = $file;
57 }
58
59 /**
60 * Fulfil the request; shows the form or deletes the file,
61 * pending authentication, confirmation, etc.
62 */
63 public function execute() {
64 global $wgOut, $wgRequest, $wgUser, $wgUploadMaintenance;
65
66 $permissionErrors = $this->title->getUserPermissionsErrors( 'delete', $wgUser );
67 if ( count( $permissionErrors ) ) {
68 throw new PermissionsError( 'delete', $permissionErrors );
69 }
70
71 if ( wfReadOnly() ) {
72 throw new ReadOnlyError;
73 }
74
75 if ( $wgUploadMaintenance ) {
76 throw new ErrorPageError( 'filedelete-maintenance-title', 'filedelete-maintenance' );
77 }
78
79 $this->setHeaders();
80
81 $this->oldimage = $wgRequest->getText( 'oldimage', false );
82 $token = $wgRequest->getText( 'wpEditToken' );
83 # Flag to hide all contents of the archived revisions
84 $suppress = $wgRequest->getVal( 'wpSuppress' ) && $wgUser->isAllowed( 'suppressrevision' );
85
86 if ( $this->oldimage ) {
87 $this->oldfile = RepoGroup::singleton()->getLocalRepo()->newFromArchiveName(
88 $this->title,
89 $this->oldimage
90 );
91 }
92
93 if ( !self::haveDeletableFile( $this->file, $this->oldfile, $this->oldimage ) ) {
94 $wgOut->addHTML( $this->prepareMessage( 'filedelete-nofile' ) );
95 $wgOut->addReturnTo( $this->title );
96 return;
97 }
98
99 // Perform the deletion if appropriate
100 if ( $wgRequest->wasPosted() && $wgUser->matchEditToken( $token, $this->oldimage ) ) {
101 $deleteReasonList = $wgRequest->getText( 'wpDeleteReasonList' );
102 $deleteReason = $wgRequest->getText( 'wpReason' );
103
104 if ( $deleteReasonList == 'other' ) {
105 $reason = $deleteReason;
106 } elseif ( $deleteReason != '' ) {
107 // Entry from drop down menu + additional comment
108 $reason = $deleteReasonList . wfMessage( 'colon-separator' )
109 ->inContentLanguage()->text() . $deleteReason;
110 } else {
111 $reason = $deleteReasonList;
112 }
113
114 $status = self::doDelete(
115 $this->title,
116 $this->file,
117 $this->oldimage,
118 $reason,
119 $suppress,
120 $wgUser
121 );
122
123 if ( !$status->isGood() ) {
124 $wgOut->addHTML( '<h2>' . $this->prepareMessage( 'filedeleteerror-short' ) . "</h2>\n" );
125 $wgOut->addWikiText( '<div class="error">' .
126 $status->getWikiText( 'filedeleteerror-short', 'filedeleteerror-long' )
127 . '</div>' );
128 }
129 if ( $status->isOK() ) {
130 $wgOut->setPageTitle( wfMessage( 'actioncomplete' ) );
131 $wgOut->addHTML( $this->prepareMessage( 'filedelete-success' ) );
132 // Return to the main page if we just deleted all versions of the
133 // file, otherwise go back to the description page
134 $wgOut->addReturnTo( $this->oldimage ? $this->title : Title::newMainPage() );
135
136 WatchAction::doWatchOrUnwatch( $wgRequest->getCheck( 'wpWatch' ), $this->title, $wgUser );
137 }
138 return;
139 }
140
141 $this->showForm();
142 $this->showLogEntries();
143 }
144
145 /**
146 * Really delete the file
147 *
148 * @param Title $title
149 * @param File $file
150 * @param string $oldimage Archive name
151 * @param string $reason Reason of the deletion
152 * @param bool $suppress Whether to mark all deleted versions as restricted
153 * @param User $user User object performing the request
154 * @param array $tags Tags to apply to the deletion action
155 * @throws MWException
156 * @return Status
157 */
158 public static function doDelete( &$title, &$file, &$oldimage, $reason,
159 $suppress, User $user = null, $tags = []
160 ) {
161 if ( $user === null ) {
162 global $wgUser;
163 $user = $wgUser;
164 }
165
166 if ( $oldimage ) {
167 $page = null;
168 $status = $file->deleteOld( $oldimage, $reason, $suppress, $user );
169 if ( $status->ok ) {
170 // Need to do a log item
171 $logComment = wfMessage( 'deletedrevision', $oldimage )->inContentLanguage()->text();
172 if ( trim( $reason ) != '' ) {
173 $logComment .= wfMessage( 'colon-separator' )
174 ->inContentLanguage()->text() . $reason;
175 }
176
177 $logtype = $suppress ? 'suppress' : 'delete';
178
179 $logEntry = new ManualLogEntry( $logtype, 'delete' );
180 $logEntry->setPerformer( $user );
181 $logEntry->setTarget( $title );
182 $logEntry->setComment( $logComment );
183 $logEntry->setTags( $tags );
184 $logid = $logEntry->insert();
185 $logEntry->publish( $logid );
186
187 $status->value = $logid;
188 }
189 } else {
190 $status = Status::newFatal( 'cannotdelete',
191 wfEscapeWikiText( $title->getPrefixedText() )
192 );
193 $page = WikiPage::factory( $title );
194 $dbw = wfGetDB( DB_MASTER );
195 $dbw->startAtomic( __METHOD__ );
196 // delete the associated article first
197 $error = '';
198 $deleteStatus = $page->doDeleteArticleReal( $reason, $suppress, 0, false, $error,
199 $user, $tags );
200 // doDeleteArticleReal() returns a non-fatal error status if the page
201 // or revision is missing, so check for isOK() rather than isGood()
202 if ( $deleteStatus->isOK() ) {
203 $status = $file->delete( $reason, $suppress, $user );
204 if ( $status->isOK() ) {
205 if ( $deleteStatus->value === null ) {
206 // No log ID from doDeleteArticleReal(), probably
207 // because the page/revision didn't exist, so create
208 // one here.
209 $logtype = $suppress ? 'suppress' : 'delete';
210 $logEntry = new ManualLogEntry( $logtype, 'delete' );
211 $logEntry->setPerformer( $user );
212 $logEntry->setTarget( clone $title );
213 $logEntry->setComment( $reason );
214 $logEntry->setTags( $tags );
215 $logid = $logEntry->insert();
216 $dbw->onTransactionPreCommitOrIdle(
217 function () use ( $dbw, $logEntry, $logid ) {
218 $logEntry->publish( $logid );
219 },
220 __METHOD__
221 );
222 $status->value = $logid;
223 } else {
224 $status->value = $deleteStatus->value; // log id
225 }
226 $dbw->endAtomic( __METHOD__ );
227 } else {
228 // Page deleted but file still there? rollback page delete
229 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
230 $lbFactory->rollbackMasterChanges( __METHOD__ );
231 }
232 } else {
233 // Done; nothing changed
234 $dbw->endAtomic( __METHOD__ );
235 }
236 }
237
238 if ( $status->isOK() ) {
239 Hooks::run( 'FileDeleteComplete', [ &$file, &$oldimage, &$page, &$user, &$reason ] );
240 }
241
242 return $status;
243 }
244
245 /**
246 * Show the confirmation form
247 */
248 private function showForm() {
249 global $wgOut, $wgUser, $wgRequest;
250
251 if ( $wgUser->isAllowed( 'suppressrevision' ) ) {
252 $suppress = "<tr id=\"wpDeleteSuppressRow\">
253 <td></td>
254 <td class='mw-input'><strong>" .
255 Xml::checkLabel( wfMessage( 'revdelete-suppress' )->text(),
256 'wpSuppress', 'wpSuppress', false, [ 'tabindex' => '3' ] ) .
257 "</strong></td>
258 </tr>";
259 } else {
260 $suppress = '';
261 }
262
263 $checkWatch = $wgUser->getBoolOption( 'watchdeletion' ) || $wgUser->isWatched( $this->title );
264 $form = Xml::openElement( 'form', [ 'method' => 'post', 'action' => $this->getAction(),
265 'id' => 'mw-img-deleteconfirm' ] ) .
266 Xml::openElement( 'fieldset' ) .
267 Xml::element( 'legend', null, wfMessage( 'filedelete-legend' )->text() ) .
268 Html::hidden( 'wpEditToken', $wgUser->getEditToken( $this->oldimage ) ) .
269 $this->prepareMessage( 'filedelete-intro' ) .
270 Xml::openElement( 'table', [ 'id' => 'mw-img-deleteconfirm-table' ] ) .
271 "<tr>
272 <td class='mw-label'>" .
273 Xml::label( wfMessage( 'filedelete-comment' )->text(), 'wpDeleteReasonList' ) .
274 "</td>
275 <td class='mw-input'>" .
276 Xml::listDropDown(
277 'wpDeleteReasonList',
278 wfMessage( 'filedelete-reason-dropdown' )->inContentLanguage()->text(),
279 wfMessage( 'filedelete-reason-otherlist' )->inContentLanguage()->text(),
280 '',
281 'wpReasonDropDown',
282 1
283 ) .
284 "</td>
285 </tr>
286 <tr>
287 <td class='mw-label'>" .
288 Xml::label( wfMessage( 'filedelete-otherreason' )->text(), 'wpReason' ) .
289 "</td>
290 <td class='mw-input'>" .
291 Xml::input( 'wpReason', 60, $wgRequest->getText( 'wpReason' ),
292 [ 'type' => 'text', 'maxlength' => '255', 'tabindex' => '2', 'id' => 'wpReason' ] ) .
293 "</td>
294 </tr>
295 {$suppress}";
296 if ( $wgUser->isLoggedIn() ) {
297 $form .= "
298 <tr>
299 <td></td>
300 <td class='mw-input'>" .
301 Xml::checkLabel( wfMessage( 'watchthis' )->text(),
302 'wpWatch', 'wpWatch', $checkWatch, [ 'tabindex' => '3' ] ) .
303 "</td>
304 </tr>";
305 }
306 $form .= "
307 <tr>
308 <td></td>
309 <td class='mw-submit'>" .
310 Xml::submitButton(
311 wfMessage( 'filedelete-submit' )->text(),
312 [
313 'name' => 'mw-filedelete-submit',
314 'id' => 'mw-filedelete-submit',
315 'tabindex' => '4'
316 ]
317 ) .
318 "</td>
319 </tr>" .
320 Xml::closeElement( 'table' ) .
321 Xml::closeElement( 'fieldset' ) .
322 Xml::closeElement( 'form' );
323
324 if ( $wgUser->isAllowed( 'editinterface' ) ) {
325 $title = wfMessage( 'filedelete-reason-dropdown' )->inContentLanguage()->getTitle();
326 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
327 $link = $linkRenderer->makeKnownLink(
328 $title,
329 wfMessage( 'filedelete-edit-reasonlist' )->text(),
330 [],
331 [ 'action' => 'edit' ]
332 );
333 $form .= '<p class="mw-filedelete-editreasons">' . $link . '</p>';
334 }
335
336 $wgOut->addHTML( $form );
337 }
338
339 /**
340 * Show deletion log fragments pertaining to the current file
341 */
342 private function showLogEntries() {
343 global $wgOut;
344 $deleteLogPage = new LogPage( 'delete' );
345 $wgOut->addHTML( '<h2>' . $deleteLogPage->getName()->escaped() . "</h2>\n" );
346 LogEventsList::showLogExtract( $wgOut, 'delete', $this->title );
347 }
348
349 /**
350 * Prepare a message referring to the file being deleted,
351 * showing an appropriate message depending upon whether
352 * it's a current file or an old version
353 *
354 * @param string $message Message base
355 * @return string
356 */
357 private function prepareMessage( $message ) {
358 global $wgLang;
359 if ( $this->oldimage ) {
360 # Message keys used:
361 # 'filedelete-intro-old', 'filedelete-nofile-old', 'filedelete-success-old'
362 return wfMessage(
363 "{$message}-old",
364 wfEscapeWikiText( $this->title->getText() ),
365 $wgLang->date( $this->getTimestamp(), true ),
366 $wgLang->time( $this->getTimestamp(), true ),
367 wfExpandUrl( $this->file->getArchiveUrl( $this->oldimage ), PROTO_CURRENT ) )->parseAsBlock();
368 } else {
369 return wfMessage(
370 $message,
371 wfEscapeWikiText( $this->title->getText() )
372 )->parseAsBlock();
373 }
374 }
375
376 /**
377 * Set headers, titles and other bits
378 */
379 private function setHeaders() {
380 global $wgOut;
381 $wgOut->setPageTitle( wfMessage( 'filedelete', $this->title->getText() ) );
382 $wgOut->setRobotPolicy( 'noindex,nofollow' );
383 $wgOut->addBacklinkSubtitle( $this->title );
384 }
385
386 /**
387 * Is the provided `oldimage` value valid?
388 *
389 * @param string $oldimage
390 * @return bool
391 */
392 public static function isValidOldSpec( $oldimage ) {
393 return strlen( $oldimage ) >= 16
394 && strpos( $oldimage, '/' ) === false
395 && strpos( $oldimage, '\\' ) === false;
396 }
397
398 /**
399 * Could we delete the file specified? If an `oldimage`
400 * value was provided, does it correspond to an
401 * existing, local, old version of this file?
402 *
403 * @param File $file
404 * @param File $oldfile
405 * @param File $oldimage
406 * @return bool
407 */
408 public static function haveDeletableFile( &$file, &$oldfile, $oldimage ) {
409 return $oldimage
410 ? $oldfile && $oldfile->exists() && $oldfile->isLocal()
411 : $file && $file->exists() && $file->isLocal();
412 }
413
414 /**
415 * Prepare the form action
416 *
417 * @return string
418 */
419 private function getAction() {
420 $q = [];
421 $q['action'] = 'delete';
422
423 if ( $this->oldimage ) {
424 $q['oldimage'] = $this->oldimage;
425 }
426
427 return $this->title->getLocalURL( $q );
428 }
429
430 /**
431 * Extract the timestamp of the old version
432 *
433 * @return string
434 */
435 private function getTimestamp() {
436 return $this->oldfile->getTimestamp();
437 }
438 }