Instruct stashed upload failures to reupload file
[lhc/web/wiklou.git] / includes / specials / SpecialUpload.php
1 <?php
2 /**
3 * Implements Special:Upload
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 * @ingroup SpecialPage
22 * @ingroup Upload
23 */
24
25 use MediaWiki\Linker\LinkRenderer;
26 use MediaWiki\MediaWikiServices;
27
28 /**
29 * Form for handling uploads and special page.
30 *
31 * @ingroup SpecialPage
32 * @ingroup Upload
33 */
34 class SpecialUpload extends SpecialPage {
35 /**
36 * Get data POSTed through the form and assign them to the object
37 * @param WebRequest $request Data posted.
38 */
39 public function __construct( $request = null ) {
40 parent::__construct( 'Upload', 'upload' );
41 }
42
43 public function doesWrites() {
44 return true;
45 }
46
47 /** Misc variables **/
48
49 /** @var WebRequest|FauxRequest The request this form is supposed to handle */
50 public $mRequest;
51 public $mSourceType;
52
53 /** @var UploadBase */
54 public $mUpload;
55
56 /** @var LocalFile */
57 public $mLocalFile;
58 public $mUploadClicked;
59
60 /** User input variables from the "description" section **/
61
62 /** @var string The requested target file name */
63 public $mDesiredDestName;
64 public $mComment;
65 public $mLicense;
66
67 /** User input variables from the root section **/
68
69 public $mIgnoreWarning;
70 public $mWatchthis;
71 public $mCopyrightStatus;
72 public $mCopyrightSource;
73
74 /** Hidden variables **/
75
76 public $mDestWarningAck;
77
78 /** @var bool The user followed an "overwrite this file" link */
79 public $mForReUpload;
80
81 /** @var bool The user clicked "Cancel and return to upload form" button */
82 public $mCancelUpload;
83 public $mTokenOk;
84
85 /** @var bool Subclasses can use this to determine whether a file was uploaded */
86 public $mUploadSuccessful = false;
87
88 /** Text injection points for hooks not using HTMLForm **/
89 public $uploadFormTextTop;
90 public $uploadFormTextAfterSummary;
91
92 /**
93 * Initialize instance variables from request and create an Upload handler
94 */
95 protected function loadRequest() {
96 $this->mRequest = $request = $this->getRequest();
97 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
98 $this->mUpload = UploadBase::createFromRequest( $request );
99 $this->mUploadClicked = $request->wasPosted()
100 && ( $request->getCheck( 'wpUpload' )
101 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
102
103 // Guess the desired name from the filename if not provided
104 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
105 if ( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
106 $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
107 }
108 $this->mLicense = $request->getText( 'wpLicense' );
109
110 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
111 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
112 || $request->getCheck( 'wpUploadIgnoreWarning' );
113 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
114 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
115 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
116
117 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
118
119 $commentDefault = '';
120 $commentMsg = wfMessage( 'upload-default-description' )->inContentLanguage();
121 if ( !$this->mForReUpload && !$commentMsg->isDisabled() ) {
122 $commentDefault = $commentMsg->plain();
123 }
124 $this->mComment = $request->getText( 'wpUploadDescription', $commentDefault );
125
126 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
127 || $request->getCheck( 'wpReUpload' ); // b/w compat
128
129 // If it was posted check for the token (no remote POST'ing with user credentials)
130 $token = $request->getVal( 'wpEditToken' );
131 $this->mTokenOk = $this->getUser()->matchEditToken( $token );
132
133 $this->uploadFormTextTop = '';
134 $this->uploadFormTextAfterSummary = '';
135 }
136
137 /**
138 * This page can be shown if uploading is enabled.
139 * Handle permission checking elsewhere in order to be able to show
140 * custom error messages.
141 *
142 * @param User $user
143 * @return bool
144 */
145 public function userCanExecute( User $user ) {
146 return UploadBase::isEnabled() && parent::userCanExecute( $user );
147 }
148
149 /**
150 * Special page entry point
151 * @param string $par
152 * @throws ErrorPageError
153 * @throws Exception
154 * @throws FatalError
155 * @throws MWException
156 * @throws PermissionsError
157 * @throws ReadOnlyError
158 * @throws UserBlockedError
159 */
160 public function execute( $par ) {
161 $this->useTransactionalTimeLimit();
162
163 $this->setHeaders();
164 $this->outputHeader();
165
166 # Check uploading enabled
167 if ( !UploadBase::isEnabled() ) {
168 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
169 }
170
171 $this->addHelpLink( 'Help:Managing files' );
172
173 # Check permissions
174 $user = $this->getUser();
175 $permissionRequired = UploadBase::isAllowed( $user );
176 if ( $permissionRequired !== true ) {
177 throw new PermissionsError( $permissionRequired );
178 }
179
180 # Check blocks
181 if ( $user->isBlocked() ) {
182 throw new UserBlockedError( $user->getBlock() );
183 }
184
185 // Global blocks
186 if ( $user->isBlockedGlobally() ) {
187 throw new UserBlockedError( $user->getGlobalBlock() );
188 }
189
190 # Check whether we actually want to allow changing stuff
191 $this->checkReadOnly();
192
193 $this->loadRequest();
194
195 # Unsave the temporary file in case this was a cancelled upload
196 if ( $this->mCancelUpload ) {
197 if ( !$this->unsaveUploadedFile() ) {
198 # Something went wrong, so unsaveUploadedFile showed a warning
199 return;
200 }
201 }
202
203 # Process upload or show a form
204 if (
205 $this->mTokenOk && !$this->mCancelUpload &&
206 ( $this->mUpload && $this->mUploadClicked )
207 ) {
208 $this->processUpload();
209 } else {
210 # Backwards compatibility hook
211 // Avoid PHP 7.1 warning of passing $this by reference
212 $upload = $this;
213 if ( !Hooks::run( 'UploadForm:initial', [ &$upload ] ) ) {
214 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
215
216 return;
217 }
218 $this->showUploadForm( $this->getUploadForm() );
219 }
220
221 # Cleanup
222 if ( $this->mUpload ) {
223 $this->mUpload->cleanupTempFile();
224 }
225 }
226
227 /**
228 * Show the main upload form
229 *
230 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
231 */
232 protected function showUploadForm( $form ) {
233 # Add links if file was previously deleted
234 if ( $this->mDesiredDestName ) {
235 $this->showViewDeletedLinks();
236 }
237
238 if ( $form instanceof HTMLForm ) {
239 $form->show();
240 } else {
241 $this->getOutput()->addHTML( $form );
242 }
243 }
244
245 /**
246 * Get an UploadForm instance with title and text properly set.
247 *
248 * @param string $message HTML string to add to the form
249 * @param string $sessionKey Session key in case this is a stashed upload
250 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
251 * @return UploadForm
252 */
253 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
254 # Initialize form
255 $context = new DerivativeContext( $this->getContext() );
256 $context->setTitle( $this->getPageTitle() ); // Remove subpage
257 $form = new UploadForm( [
258 'watch' => $this->getWatchCheck(),
259 'forreupload' => $this->mForReUpload,
260 'sessionkey' => $sessionKey,
261 'hideignorewarning' => $hideIgnoreWarning,
262 'destwarningack' => (bool)$this->mDestWarningAck,
263
264 'description' => $this->mComment,
265 'texttop' => $this->uploadFormTextTop,
266 'textaftersummary' => $this->uploadFormTextAfterSummary,
267 'destfile' => $this->mDesiredDestName,
268 ], $context, $this->getLinkRenderer() );
269
270 # Check the token, but only if necessary
271 if (
272 !$this->mTokenOk && !$this->mCancelUpload &&
273 ( $this->mUpload && $this->mUploadClicked )
274 ) {
275 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
276 }
277
278 # Give a notice if the user is uploading a file that has been deleted or moved
279 # Note that this is independent from the message 'filewasdeleted'
280 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
281 $delNotice = ''; // empty by default
282 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
283 $dbr = wfGetDB( DB_REPLICA );
284
285 LogEventsList::showLogExtract( $delNotice, [ 'delete', 'move' ],
286 $desiredTitleObj,
287 '', [ 'lim' => 10,
288 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
289 'showIfEmpty' => false,
290 'msgKey' => [ 'upload-recreate-warning' ] ]
291 );
292 }
293 $form->addPreText( $delNotice );
294
295 # Add text to form
296 $form->addPreText( '<div id="uploadtext">' .
297 $this->msg( 'uploadtext', [ $this->mDesiredDestName ] )->parseAsBlock() .
298 '</div>' );
299 # Add upload error message
300 $form->addPreText( $message );
301
302 # Add footer to form
303 $uploadFooter = $this->msg( 'uploadfooter' );
304 if ( !$uploadFooter->isDisabled() ) {
305 $form->addPostText( '<div id="mw-upload-footer-message">'
306 . $uploadFooter->parseAsBlock() . "</div>\n" );
307 }
308
309 return $form;
310 }
311
312 /**
313 * Shows the "view X deleted revivions link""
314 */
315 protected function showViewDeletedLinks() {
316 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
317 $user = $this->getUser();
318 // Show a subtitle link to deleted revisions (to sysops et al only)
319 if ( $title instanceof Title ) {
320 $count = $title->isDeleted();
321 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
322 $restorelink = $this->getLinkRenderer()->makeKnownLink(
323 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
324 $this->msg( 'restorelink' )->numParams( $count )->text()
325 );
326 $link = $this->msg( $user->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted' )
327 ->rawParams( $restorelink )->parseAsBlock();
328 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
329 }
330 }
331 }
332
333 /**
334 * Stashes the upload and shows the main upload form.
335 *
336 * Note: only errors that can be handled by changing the name or
337 * description should be redirected here. It should be assumed that the
338 * file itself is sane and has passed UploadBase::verifyFile. This
339 * essentially means that UploadBase::VERIFICATION_ERROR and
340 * UploadBase::EMPTY_FILE should not be passed here.
341 *
342 * @param string $message HTML message to be passed to mainUploadForm
343 */
344 protected function showRecoverableUploadError( $message ) {
345 $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
346 if ( $stashStatus->isGood() ) {
347 $sessionKey = $stashStatus->getValue()->getFileKey();
348 $uploadWarning = 'upload-tryagain';
349 } else {
350 $sessionKey = null;
351 $uploadWarning = 'upload-tryagain-nostash';
352 }
353 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
354 '<div class="error">' . $message . "</div>\n";
355
356 $form = $this->getUploadForm( $message, $sessionKey );
357 $form->setSubmitText( $this->msg( $uploadWarning )->escaped() );
358 $this->showUploadForm( $form );
359 }
360
361 /**
362 * Stashes the upload, shows the main form, but adds a "continue anyway button".
363 * Also checks whether there are actually warnings to display.
364 *
365 * @param array $warnings
366 * @return bool True if warnings were displayed, false if there are no
367 * warnings and it should continue processing
368 */
369 protected function showUploadWarning( $warnings ) {
370 # If there are no warnings, or warnings we can ignore, return early.
371 # mDestWarningAck is set when some javascript has shown the warning
372 # to the user. mForReUpload is set when the user clicks the "upload a
373 # new version" link.
374 if ( !$warnings || ( count( $warnings ) == 1
375 && isset( $warnings['exists'] )
376 && ( $this->mDestWarningAck || $this->mForReUpload ) )
377 ) {
378 return false;
379 }
380
381 $stashStatus = $this->mUpload->tryStashFile( $this->getUser() );
382 if ( $stashStatus->isGood() ) {
383 $sessionKey = $stashStatus->getValue()->getFileKey();
384 $uploadWarning = 'uploadwarning-text';
385 } else {
386 $sessionKey = null;
387 $uploadWarning = 'uploadwarning-text-nostash';
388 }
389
390 // Add styles for the warning, reused from the live preview
391 $this->getOutput()->addModuleStyles( 'mediawiki.special.upload.styles' );
392
393 $linkRenderer = $this->getLinkRenderer();
394 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
395 . '<div class="mw-destfile-warning"><ul>';
396 foreach ( $warnings as $warning => $args ) {
397 if ( $warning == 'badfilename' ) {
398 $this->mDesiredDestName = Title::makeTitle( NS_FILE, $args )->getText();
399 }
400 if ( $warning == 'exists' ) {
401 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
402 } elseif ( $warning == 'no-change' ) {
403 $file = $args;
404 $filename = $file->getTitle()->getPrefixedText();
405 $msg = "\t<li>" . wfMessage( 'fileexists-no-change', $filename )->parse() . "</li>\n";
406 } elseif ( $warning == 'duplicate-version' ) {
407 $file = $args[0];
408 $count = count( $args );
409 $filename = $file->getTitle()->getPrefixedText();
410 $message = wfMessage( 'fileexists-duplicate-version' )
411 ->params( $filename )
412 ->numParams( $count );
413 $msg = "\t<li>" . $message->parse() . "</li>\n";
414 } elseif ( $warning == 'was-deleted' ) {
415 # If the file existed before and was deleted, warn the user of this
416 $ltitle = SpecialPage::getTitleFor( 'Log' );
417 $llink = $linkRenderer->makeKnownLink(
418 $ltitle,
419 wfMessage( 'deletionlog' )->text(),
420 [],
421 [
422 'type' => 'delete',
423 'page' => Title::makeTitle( NS_FILE, $args )->getPrefixedText(),
424 ]
425 );
426 $msg = "\t<li>" . wfMessage( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
427 } elseif ( $warning == 'duplicate' ) {
428 $msg = $this->getDupeWarning( $args );
429 } elseif ( $warning == 'duplicate-archive' ) {
430 if ( $args === '' ) {
431 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
432 . "</li>\n";
433 } else {
434 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
435 Title::makeTitle( NS_FILE, $args )->getPrefixedText() )->parse()
436 . "</li>\n";
437 }
438 } else {
439 if ( $args === true ) {
440 $args = [];
441 } elseif ( !is_array( $args ) ) {
442 $args = [ $args ];
443 }
444 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
445 }
446 $warningHtml .= $msg;
447 }
448 $warningHtml .= "</ul></div>\n";
449 $warningHtml .= $this->msg( $uploadWarning )->parseAsBlock();
450
451 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
452 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
453 $form->addButton( [
454 'name' => 'wpUploadIgnoreWarning',
455 'value' => $this->msg( 'ignorewarning' )->text()
456 ] );
457 $form->addButton( [
458 'name' => 'wpCancelUpload',
459 'value' => $this->msg( 'reuploaddesc' )->text()
460 ] );
461
462 $this->showUploadForm( $form );
463
464 # Indicate that we showed a form
465 return true;
466 }
467
468 /**
469 * Show the upload form with error message, but do not stash the file.
470 *
471 * @param string $message HTML string
472 */
473 protected function showUploadError( $message ) {
474 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
475 '<div class="error">' . $message . "</div>\n";
476 $this->showUploadForm( $this->getUploadForm( $message ) );
477 }
478
479 /**
480 * Do the upload.
481 * Checks are made in SpecialUpload::execute()
482 */
483 protected function processUpload() {
484 // Fetch the file if required
485 $status = $this->mUpload->fetchFile();
486 if ( !$status->isOK() ) {
487 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
488
489 return;
490 }
491 // Avoid PHP 7.1 warning of passing $this by reference
492 $upload = $this;
493 if ( !Hooks::run( 'UploadForm:BeforeProcessing', [ &$upload ] ) ) {
494 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
495 // This code path is deprecated. If you want to break upload processing
496 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
497 // and UploadBase::verifyFile.
498 // If you use this hook to break uploading, the user will be returned
499 // an empty form with no error message whatsoever.
500 return;
501 }
502
503 // Upload verification
504 $details = $this->mUpload->verifyUpload();
505 if ( $details['status'] != UploadBase::OK ) {
506 $this->processVerificationError( $details );
507
508 return;
509 }
510
511 // Verify permissions for this title
512 $permErrors = $this->mUpload->verifyTitlePermissions( $this->getUser() );
513 if ( $permErrors !== true ) {
514 $code = array_shift( $permErrors[0] );
515 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
516
517 return;
518 }
519
520 $this->mLocalFile = $this->mUpload->getLocalFile();
521
522 // Check warnings if necessary
523 if ( !$this->mIgnoreWarning ) {
524 $warnings = $this->mUpload->checkWarnings();
525 if ( $this->showUploadWarning( $warnings ) ) {
526 return;
527 }
528 }
529
530 // This is as late as we can throttle, after expected issues have been handled
531 if ( UploadBase::isThrottled( $this->getUser() ) ) {
532 $this->showRecoverableUploadError(
533 $this->msg( 'actionthrottledtext' )->escaped()
534 );
535 return;
536 }
537
538 // Get the page text if this is not a reupload
539 if ( !$this->mForReUpload ) {
540 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
541 $this->mCopyrightStatus, $this->mCopyrightSource, $this->getConfig() );
542 } else {
543 $pageText = false;
544 }
545
546 $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
547 if ( is_null( $changeTags ) || $changeTags === '' ) {
548 $changeTags = [];
549 } else {
550 $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
551 }
552
553 if ( $changeTags ) {
554 $changeTagsStatus = ChangeTags::canAddTagsAccompanyingChange(
555 $changeTags, $this->getUser() );
556 if ( !$changeTagsStatus->isOK() ) {
557 $this->showUploadError( $this->getOutput()->parse( $changeTagsStatus->getWikiText() ) );
558
559 return;
560 }
561 }
562
563 $status = $this->mUpload->performUpload(
564 $this->mComment,
565 $pageText,
566 $this->mWatchthis,
567 $this->getUser(),
568 $changeTags
569 );
570
571 if ( !$status->isGood() ) {
572 $this->showRecoverableUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
573
574 return;
575 }
576
577 // Success, redirect to description page
578 $this->mUploadSuccessful = true;
579 // Avoid PHP 7.1 warning of passing $this by reference
580 $upload = $this;
581 Hooks::run( 'SpecialUploadComplete', [ &$upload ] );
582 $this->getOutput()->redirect( $this->mLocalFile->getTitle()->getFullURL() );
583 }
584
585 /**
586 * Get the initial image page text based on a comment and optional file status information
587 * @param string $comment
588 * @param string $license
589 * @param string $copyStatus
590 * @param string $source
591 * @param Config $config Configuration object to load data from
592 * @return string
593 */
594 public static function getInitialPageText( $comment = '', $license = '',
595 $copyStatus = '', $source = '', Config $config = null
596 ) {
597 if ( $config === null ) {
598 wfDebug( __METHOD__ . ' called without a Config instance passed to it' );
599 $config = MediaWikiServices::getInstance()->getMainConfig();
600 }
601
602 $msg = [];
603 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
604 /* These messages are transcluded into the actual text of the description page.
605 * Thus, forcing them as content messages makes the upload to produce an int: template
606 * instead of hardcoding it there in the uploader language.
607 */
608 foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
609 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
610 $msg[$msgName] = "{{int:$msgName}}";
611 } else {
612 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
613 }
614 }
615
616 if ( $config->get( 'UseCopyrightUpload' ) ) {
617 $licensetxt = '';
618 if ( $license != '' ) {
619 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
620 }
621 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
622 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
623 "$licensetxt" .
624 '== ' . $msg['filesource'] . " ==\n" . $source;
625 } else {
626 if ( $license != '' ) {
627 $filedesc = $comment == '' ? '' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
628 $pageText = $filedesc .
629 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
630 } else {
631 $pageText = $comment;
632 }
633 }
634
635 return $pageText;
636 }
637
638 /**
639 * See if we should check the 'watch this page' checkbox on the form
640 * based on the user's preferences and whether we're being asked
641 * to create a new file or update an existing one.
642 *
643 * In the case where 'watch edits' is off but 'watch creations' is on,
644 * we'll leave the box unchecked.
645 *
646 * Note that the page target can be changed *on the form*, so our check
647 * state can get out of sync.
648 * @return bool|string
649 */
650 protected function getWatchCheck() {
651 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
652 // Watch all edits!
653 return true;
654 }
655
656 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
657 if ( $desiredTitleObj instanceof Title && $this->getUser()->isWatched( $desiredTitleObj ) ) {
658 // Already watched, don't change that
659 return true;
660 }
661
662 $local = wfLocalFile( $this->mDesiredDestName );
663 if ( $local && $local->exists() ) {
664 // We're uploading a new version of an existing file.
665 // No creation, so don't watch it if we're not already.
666 return false;
667 } else {
668 // New page should get watched if that's our option.
669 return $this->getUser()->getOption( 'watchcreations' ) ||
670 $this->getUser()->getOption( 'watchuploads' );
671 }
672 }
673
674 /**
675 * Provides output to the user for a result of UploadBase::verifyUpload
676 *
677 * @param array $details Result of UploadBase::verifyUpload
678 * @throws MWException
679 */
680 protected function processVerificationError( $details ) {
681 switch ( $details['status'] ) {
682 /** Statuses that only require name changing **/
683 case UploadBase::MIN_LENGTH_PARTNAME:
684 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
685 break;
686 case UploadBase::ILLEGAL_FILENAME:
687 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
688 $details['filtered'] )->parse() );
689 break;
690 case UploadBase::FILENAME_TOO_LONG:
691 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
692 break;
693 case UploadBase::FILETYPE_MISSING:
694 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
695 break;
696 case UploadBase::WINDOWS_NONASCII_FILENAME:
697 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
698 break;
699
700 /** Statuses that require reuploading **/
701 case UploadBase::EMPTY_FILE:
702 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
703 break;
704 case UploadBase::FILE_TOO_LARGE:
705 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
706 break;
707 case UploadBase::FILETYPE_BADTYPE:
708 $msg = $this->msg( 'filetype-banned-type' );
709 if ( isset( $details['blacklistedExt'] ) ) {
710 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
711 } else {
712 $msg->params( $details['finalExt'] );
713 }
714 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
715 $msg->params( $this->getLanguage()->commaList( $extensions ),
716 count( $extensions ) );
717
718 // Add PLURAL support for the first parameter. This results
719 // in a bit unlogical parameter sequence, but does not break
720 // old translations
721 if ( isset( $details['blacklistedExt'] ) ) {
722 $msg->params( count( $details['blacklistedExt'] ) );
723 } else {
724 $msg->params( 1 );
725 }
726
727 $this->showUploadError( $msg->parse() );
728 break;
729 case UploadBase::VERIFICATION_ERROR:
730 unset( $details['status'] );
731 $code = array_shift( $details['details'] );
732 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
733 break;
734 case UploadBase::HOOK_ABORTED:
735 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
736 $args = $details['error'];
737 $error = array_shift( $args );
738 } else {
739 $error = $details['error'];
740 $args = null;
741 }
742
743 $this->showUploadError( $this->msg( $error, $args )->parse() );
744 break;
745 default:
746 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
747 }
748 }
749
750 /**
751 * Remove a temporarily kept file stashed by saveTempUploadedFile().
752 *
753 * @return bool Success
754 */
755 protected function unsaveUploadedFile() {
756 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
757 return true;
758 }
759 $success = $this->mUpload->unsaveUploadedFile();
760 if ( !$success ) {
761 $this->getOutput()->showFileDeleteError( $this->mUpload->getTempPath() );
762
763 return false;
764 } else {
765 return true;
766 }
767 }
768
769 /*** Functions for formatting warnings ***/
770
771 /**
772 * Formats a result of UploadBase::getExistsWarning as HTML
773 * This check is static and can be done pre-upload via AJAX
774 *
775 * @param array $exists The result of UploadBase::getExistsWarning
776 * @return string Empty string if there is no warning or an HTML fragment
777 */
778 public static function getExistsWarning( $exists ) {
779 if ( !$exists ) {
780 return '';
781 }
782
783 $file = $exists['file'];
784 $filename = $file->getTitle()->getPrefixedText();
785 $warnMsg = null;
786
787 if ( $exists['warning'] == 'exists' ) {
788 // Exact match
789 $warnMsg = wfMessage( 'fileexists', $filename );
790 } elseif ( $exists['warning'] == 'page-exists' ) {
791 // Page exists but file does not
792 $warnMsg = wfMessage( 'filepageexists', $filename );
793 } elseif ( $exists['warning'] == 'exists-normalized' ) {
794 $warnMsg = wfMessage( 'fileexists-extension', $filename,
795 $exists['normalizedFile']->getTitle()->getPrefixedText() );
796 } elseif ( $exists['warning'] == 'thumb' ) {
797 // Swapped argument order compared with other messages for backwards compatibility
798 $warnMsg = wfMessage( 'fileexists-thumbnail-yes',
799 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
800 } elseif ( $exists['warning'] == 'thumb-name' ) {
801 // Image w/o '180px-' does not exists, but we do not like these filenames
802 $name = $file->getName();
803 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
804 $warnMsg = wfMessage( 'file-thumbnail-no', $badPart );
805 } elseif ( $exists['warning'] == 'bad-prefix' ) {
806 $warnMsg = wfMessage( 'filename-bad-prefix', $exists['prefix'] );
807 }
808
809 return $warnMsg ? $warnMsg->title( $file->getTitle() )->parse() : '';
810 }
811
812 /**
813 * Construct a warning and a gallery from an array of duplicate files.
814 * @param array $dupes
815 * @return string
816 */
817 public function getDupeWarning( $dupes ) {
818 if ( !$dupes ) {
819 return '';
820 }
821
822 $gallery = ImageGalleryBase::factory( false, $this->getContext() );
823 $gallery->setShowBytes( false );
824 $gallery->setShowDimensions( false );
825 foreach ( $dupes as $file ) {
826 $gallery->add( $file->getTitle() );
827 }
828
829 return '<li>' .
830 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
831 $gallery->toHTML() . "</li>\n";
832 }
833
834 protected function getGroupName() {
835 return 'media';
836 }
837
838 /**
839 * Should we rotate images in the preview on Special:Upload.
840 *
841 * This controls js: mw.config.get( 'wgFileCanRotate' )
842 *
843 * @todo What about non-BitmapHandler handled files?
844 */
845 public static function rotationEnabled() {
846 $bitmapHandler = new BitmapHandler();
847 return $bitmapHandler->autoRotateEnabled();
848 }
849 }
850
851 /**
852 * Sub class of HTMLForm that provides the form section of SpecialUpload
853 */
854 class UploadForm extends HTMLForm {
855 protected $mWatch;
856 protected $mForReUpload;
857 protected $mSessionKey;
858 protected $mHideIgnoreWarning;
859 protected $mDestWarningAck;
860 protected $mDestFile;
861
862 protected $mComment;
863 protected $mTextTop;
864 protected $mTextAfterSummary;
865
866 protected $mSourceIds;
867
868 protected $mMaxFileSize = [];
869
870 protected $mMaxUploadSize = [];
871
872 public function __construct( array $options = [], IContextSource $context = null,
873 LinkRenderer $linkRenderer = null
874 ) {
875 if ( $context instanceof IContextSource ) {
876 $this->setContext( $context );
877 }
878
879 if ( !$linkRenderer ) {
880 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
881 }
882
883 $this->mWatch = !empty( $options['watch'] );
884 $this->mForReUpload = !empty( $options['forreupload'] );
885 $this->mSessionKey = isset( $options['sessionkey'] ) ? $options['sessionkey'] : '';
886 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
887 $this->mDestWarningAck = !empty( $options['destwarningack'] );
888 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
889
890 $this->mComment = isset( $options['description'] ) ?
891 $options['description'] : '';
892
893 $this->mTextTop = isset( $options['texttop'] )
894 ? $options['texttop'] : '';
895
896 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
897 ? $options['textaftersummary'] : '';
898
899 $sourceDescriptor = $this->getSourceSection();
900 $descriptor = $sourceDescriptor
901 + $this->getDescriptionSection()
902 + $this->getOptionsSection();
903
904 Hooks::run( 'UploadFormInitDescriptor', [ &$descriptor ] );
905 parent::__construct( $descriptor, $context, 'upload' );
906
907 # Add a link to edit MediaWiki:Licenses
908 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
909 $this->getOutput()->addModuleStyles( 'mediawiki.special.upload.styles' );
910 $licensesLink = $linkRenderer->makeKnownLink(
911 $this->msg( 'licenses' )->inContentLanguage()->getTitle(),
912 $this->msg( 'licenses-edit' )->text(),
913 [],
914 [ 'action' => 'edit' ]
915 );
916 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
917 $this->addFooterText( $editLicenses, 'description' );
918 }
919
920 # Set some form properties
921 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
922 $this->setSubmitName( 'wpUpload' );
923 # Used message keys: 'accesskey-upload', 'tooltip-upload'
924 $this->setSubmitTooltip( 'upload' );
925 $this->setId( 'mw-upload-form' );
926
927 # Build a list of IDs for javascript insertion
928 $this->mSourceIds = [];
929 foreach ( $sourceDescriptor as $field ) {
930 if ( !empty( $field['id'] ) ) {
931 $this->mSourceIds[] = $field['id'];
932 }
933 }
934 }
935
936 /**
937 * Get the descriptor of the fieldset that contains the file source
938 * selection. The section is 'source'
939 *
940 * @return array Descriptor array
941 */
942 protected function getSourceSection() {
943 if ( $this->mSessionKey ) {
944 return [
945 'SessionKey' => [
946 'type' => 'hidden',
947 'default' => $this->mSessionKey,
948 ],
949 'SourceType' => [
950 'type' => 'hidden',
951 'default' => 'Stash',
952 ],
953 ];
954 }
955
956 $canUploadByUrl = UploadFromUrl::isEnabled()
957 && ( UploadFromUrl::isAllowed( $this->getUser() ) === true )
958 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
959 $radio = $canUploadByUrl;
960 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
961
962 $descriptor = [];
963 if ( $this->mTextTop ) {
964 $descriptor['UploadFormTextTop'] = [
965 'type' => 'info',
966 'section' => 'source',
967 'default' => $this->mTextTop,
968 'raw' => true,
969 ];
970 }
971
972 $this->mMaxUploadSize['file'] = min(
973 UploadBase::getMaxUploadSize( 'file' ),
974 UploadBase::getMaxPhpUploadSize()
975 );
976
977 $help = $this->msg( 'upload-maxfilesize',
978 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['file'] )
979 )->parse();
980
981 // If the user can also upload by URL, there are 2 different file size limits.
982 // This extra message helps stress which limit corresponds to what.
983 if ( $canUploadByUrl ) {
984 $help .= $this->msg( 'word-separator' )->escaped();
985 $help .= $this->msg( 'upload_source_file' )->parse();
986 }
987
988 $descriptor['UploadFile'] = [
989 'class' => 'UploadSourceField',
990 'section' => 'source',
991 'type' => 'file',
992 'id' => 'wpUploadFile',
993 'radio-id' => 'wpSourceTypeFile',
994 'label-message' => 'sourcefilename',
995 'upload-type' => 'File',
996 'radio' => &$radio,
997 'help' => $help,
998 'checked' => $selectedSourceType == 'file',
999 ];
1000
1001 if ( $canUploadByUrl ) {
1002 $this->mMaxUploadSize['url'] = UploadBase::getMaxUploadSize( 'url' );
1003 $descriptor['UploadFileURL'] = [
1004 'class' => 'UploadSourceField',
1005 'section' => 'source',
1006 'id' => 'wpUploadFileURL',
1007 'radio-id' => 'wpSourceTypeurl',
1008 'label-message' => 'sourceurl',
1009 'upload-type' => 'url',
1010 'radio' => &$radio,
1011 'help' => $this->msg( 'upload-maxfilesize',
1012 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize['url'] )
1013 )->parse() .
1014 $this->msg( 'word-separator' )->escaped() .
1015 $this->msg( 'upload_source_url' )->parse(),
1016 'checked' => $selectedSourceType == 'url',
1017 ];
1018 }
1019 Hooks::run( 'UploadFormSourceDescriptors', [ &$descriptor, &$radio, $selectedSourceType ] );
1020
1021 $descriptor['Extensions'] = [
1022 'type' => 'info',
1023 'section' => 'source',
1024 'default' => $this->getExtensionsMessage(),
1025 'raw' => true,
1026 ];
1027
1028 return $descriptor;
1029 }
1030
1031 /**
1032 * Get the messages indicating which extensions are preferred and prohibitted.
1033 *
1034 * @return string HTML string containing the message
1035 */
1036 protected function getExtensionsMessage() {
1037 # Print a list of allowed file extensions, if so configured. We ignore
1038 # MIME type here, it's incomprehensible to most people and too long.
1039 $config = $this->getConfig();
1040
1041 if ( $config->get( 'CheckFileExtensions' ) ) {
1042 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
1043 if ( $config->get( 'StrictFileExtensions' ) ) {
1044 # Everything not permitted is banned
1045 $extensionsList =
1046 '<div id="mw-upload-permitted">' .
1047 $this->msg( 'upload-permitted' )
1048 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1049 ->numParams( count( $fileExtensions ) )
1050 ->parseAsBlock() .
1051 "</div>\n";
1052 } else {
1053 # We have to list both preferred and prohibited
1054 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
1055 $extensionsList =
1056 '<div id="mw-upload-preferred">' .
1057 $this->msg( 'upload-preferred' )
1058 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
1059 ->numParams( count( $fileExtensions ) )
1060 ->parseAsBlock() .
1061 "</div>\n" .
1062 '<div id="mw-upload-prohibited">' .
1063 $this->msg( 'upload-prohibited' )
1064 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
1065 ->numParams( count( $fileBlacklist ) )
1066 ->parseAsBlock() .
1067 "</div>\n";
1068 }
1069 } else {
1070 # Everything is permitted.
1071 $extensionsList = '';
1072 }
1073
1074 return $extensionsList;
1075 }
1076
1077 /**
1078 * Get the descriptor of the fieldset that contains the file description
1079 * input. The section is 'description'
1080 *
1081 * @return array Descriptor array
1082 */
1083 protected function getDescriptionSection() {
1084 $config = $this->getConfig();
1085 if ( $this->mSessionKey ) {
1086 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1087 try {
1088 $file = $stash->getFile( $this->mSessionKey );
1089 } catch ( Exception $e ) {
1090 $file = null;
1091 }
1092 if ( $file ) {
1093 global $wgContLang;
1094
1095 $mto = $file->transform( [ 'width' => 120 ] );
1096 if ( $mto ) {
1097 $this->addHeaderText(
1098 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1099 Html::element( 'img', [
1100 'src' => $mto->getUrl(),
1101 'class' => 'thumbimage',
1102 ] ) . '</div>', 'description' );
1103 }
1104 }
1105 }
1106
1107 $descriptor = [
1108 'DestFile' => [
1109 'type' => 'text',
1110 'section' => 'description',
1111 'id' => 'wpDestFile',
1112 'label-message' => 'destfilename',
1113 'size' => 60,
1114 'default' => $this->mDestFile,
1115 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1116 'nodata' => strval( $this->mDestFile ) !== '',
1117 ],
1118 'UploadDescription' => [
1119 'type' => 'textarea',
1120 'section' => 'description',
1121 'id' => 'wpUploadDescription',
1122 'label-message' => $this->mForReUpload
1123 ? 'filereuploadsummary'
1124 : 'fileuploadsummary',
1125 'default' => $this->mComment,
1126 'cols' => 80,
1127 'rows' => 8,
1128 ]
1129 ];
1130 if ( $this->mTextAfterSummary ) {
1131 $descriptor['UploadFormTextAfterSummary'] = [
1132 'type' => 'info',
1133 'section' => 'description',
1134 'default' => $this->mTextAfterSummary,
1135 'raw' => true,
1136 ];
1137 }
1138
1139 $descriptor += [
1140 'EditTools' => [
1141 'type' => 'edittools',
1142 'section' => 'description',
1143 'message' => 'edittools-upload',
1144 ]
1145 ];
1146
1147 if ( $this->mForReUpload ) {
1148 $descriptor['DestFile']['readonly'] = true;
1149 } else {
1150 $descriptor['License'] = [
1151 'type' => 'select',
1152 'class' => 'Licenses',
1153 'section' => 'description',
1154 'id' => 'wpLicense',
1155 'label-message' => 'license',
1156 ];
1157 }
1158
1159 if ( $config->get( 'UseCopyrightUpload' ) ) {
1160 $descriptor['UploadCopyStatus'] = [
1161 'type' => 'text',
1162 'section' => 'description',
1163 'id' => 'wpUploadCopyStatus',
1164 'label-message' => 'filestatus',
1165 ];
1166 $descriptor['UploadSource'] = [
1167 'type' => 'text',
1168 'section' => 'description',
1169 'id' => 'wpUploadSource',
1170 'label-message' => 'filesource',
1171 ];
1172 }
1173
1174 return $descriptor;
1175 }
1176
1177 /**
1178 * Get the descriptor of the fieldset that contains the upload options,
1179 * such as "watch this file". The section is 'options'
1180 *
1181 * @return array Descriptor array
1182 */
1183 protected function getOptionsSection() {
1184 $user = $this->getUser();
1185 if ( $user->isLoggedIn() ) {
1186 $descriptor = [
1187 'Watchthis' => [
1188 'type' => 'check',
1189 'id' => 'wpWatchthis',
1190 'label-message' => 'watchthisupload',
1191 'section' => 'options',
1192 'default' => $this->mWatch,
1193 ]
1194 ];
1195 }
1196 if ( !$this->mHideIgnoreWarning ) {
1197 $descriptor['IgnoreWarning'] = [
1198 'type' => 'check',
1199 'id' => 'wpIgnoreWarning',
1200 'label-message' => 'ignorewarnings',
1201 'section' => 'options',
1202 ];
1203 }
1204
1205 $descriptor['DestFileWarningAck'] = [
1206 'type' => 'hidden',
1207 'id' => 'wpDestFileWarningAck',
1208 'default' => $this->mDestWarningAck ? '1' : '',
1209 ];
1210
1211 if ( $this->mForReUpload ) {
1212 $descriptor['ForReUpload'] = [
1213 'type' => 'hidden',
1214 'id' => 'wpForReUpload',
1215 'default' => '1',
1216 ];
1217 }
1218
1219 return $descriptor;
1220 }
1221
1222 /**
1223 * Add the upload JS and show the form.
1224 */
1225 public function show() {
1226 $this->addUploadJS();
1227 parent::show();
1228 }
1229
1230 /**
1231 * Add upload JS to the OutputPage
1232 */
1233 protected function addUploadJS() {
1234 $config = $this->getConfig();
1235
1236 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1237 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1238 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1239 $this->mMaxUploadSize['*'] = UploadBase::getMaxUploadSize();
1240
1241 $scriptVars = [
1242 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1243 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1244 'wgUploadAutoFill' => !$this->mForReUpload &&
1245 // If we received mDestFile from the request, don't autofill
1246 // the wpDestFile textbox
1247 $this->mDestFile === '',
1248 'wgUploadSourceIds' => $this->mSourceIds,
1249 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1250 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1251 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1252 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1253 'wgMaxUploadSize' => $this->mMaxUploadSize,
1254 'wgFileCanRotate' => SpecialUpload::rotationEnabled(),
1255 ];
1256
1257 $out = $this->getOutput();
1258 $out->addJsConfigVars( $scriptVars );
1259
1260 $out->addModules( [
1261 'mediawiki.action.edit', // For <charinsert> support
1262 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1263 ] );
1264 }
1265
1266 /**
1267 * Empty function; submission is handled elsewhere.
1268 *
1269 * @return bool False
1270 */
1271 function trySubmit() {
1272 return false;
1273 }
1274 }
1275
1276 /**
1277 * A form field that contains a radio box in the label
1278 */
1279 class UploadSourceField extends HTMLTextField {
1280
1281 /**
1282 * @param array $cellAttributes
1283 * @return string
1284 */
1285 function getLabelHtml( $cellAttributes = [] ) {
1286 $id = $this->mParams['id'];
1287 $label = Html::rawElement( 'label', [ 'for' => $id ], $this->mLabel );
1288
1289 if ( !empty( $this->mParams['radio'] ) ) {
1290 if ( isset( $this->mParams['radio-id'] ) ) {
1291 $radioId = $this->mParams['radio-id'];
1292 } else {
1293 // Old way. For the benefit of extensions that do not define
1294 // the 'radio-id' key.
1295 $radioId = 'wpSourceType' . $this->mParams['upload-type'];
1296 }
1297
1298 $attribs = [
1299 'name' => 'wpSourceType',
1300 'type' => 'radio',
1301 'id' => $radioId,
1302 'value' => $this->mParams['upload-type'],
1303 ];
1304
1305 if ( !empty( $this->mParams['checked'] ) ) {
1306 $attribs['checked'] = 'checked';
1307 }
1308
1309 $label .= Html::element( 'input', $attribs );
1310 }
1311
1312 return Html::rawElement( 'td', [ 'class' => 'mw-label' ] + $cellAttributes, $label );
1313 }
1314
1315 /**
1316 * @return int
1317 */
1318 function getSize() {
1319 return isset( $this->mParams['size'] )
1320 ? $this->mParams['size']
1321 : 60;
1322 }
1323 }