3 * Implements Special:Upload
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.
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.
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
21 * @ingroup SpecialPage
25 use MediaWiki\MediaWikiServices
;
28 * Form for handling uploads and special page.
30 * @ingroup SpecialPage
33 class SpecialUpload
extends SpecialPage
{
35 * Get data POSTed through the form and assign them to the object
36 * @param WebRequest|null $request Data posted.
38 public function __construct( $request = null ) {
39 parent
::__construct( 'Upload', 'upload' );
42 public function doesWrites() {
48 /** @var WebRequest|FauxRequest The request this form is supposed to handle */
52 /** @var UploadBase */
57 public $mUploadClicked;
59 /** User input variables from the "description" section */
61 /** @var string The requested target file name */
62 public $mDesiredDestName;
66 /** User input variables from the root section */
68 public $mIgnoreWarning;
70 public $mCopyrightStatus;
71 public $mCopyrightSource;
73 /** Hidden variables */
75 public $mDestWarningAck;
77 /** @var bool The user followed an "overwrite this file" link */
80 /** @var bool The user clicked "Cancel and return to upload form" button */
81 public $mCancelUpload;
84 /** @var bool Subclasses can use this to determine whether a file was uploaded */
85 public $mUploadSuccessful = false;
87 /** Text injection points for hooks not using HTMLForm */
88 public $uploadFormTextTop;
89 public $uploadFormTextAfterSummary;
92 * Initialize instance variables from request and create an Upload handler
94 protected function loadRequest() {
95 $this->mRequest
= $request = $this->getRequest();
96 $this->mSourceType
= $request->getVal( 'wpSourceType', 'file' );
97 $this->mUpload
= UploadBase
::createFromRequest( $request );
98 $this->mUploadClicked
= $request->wasPosted()
99 && ( $request->getCheck( 'wpUpload' )
100 ||
$request->getCheck( 'wpUploadIgnoreWarning' ) );
102 // Guess the desired name from the filename if not provided
103 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
104 if ( !$this->mDesiredDestName
&& $request->getFileName( 'wpUploadFile' ) !== null ) {
105 $this->mDesiredDestName
= $request->getFileName( 'wpUploadFile' );
107 $this->mLicense
= $request->getText( 'wpLicense' );
109 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
110 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
111 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
112 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
113 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
114 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
116 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
118 $commentDefault = '';
119 $commentMsg = $this->msg( 'upload-default-description' )->inContentLanguage();
120 if ( !$this->mForReUpload
&& !$commentMsg->isDisabled() ) {
121 $commentDefault = $commentMsg->plain();
123 $this->mComment
= $request->getText( 'wpUploadDescription', $commentDefault );
125 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
126 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
128 // If it was posted check for the token (no remote POST'ing with user credentials)
129 $token = $request->getVal( 'wpEditToken' );
130 $this->mTokenOk
= $this->getUser()->matchEditToken( $token );
132 $this->uploadFormTextTop
= '';
133 $this->uploadFormTextAfterSummary
= '';
137 * This page can be shown if uploading is enabled.
138 * Handle permission checking elsewhere in order to be able to show
139 * custom error messages.
144 public function userCanExecute( User
$user ) {
145 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
149 * @param string|null $par
150 * @throws ErrorPageError
153 * @throws MWException
154 * @throws PermissionsError
155 * @throws ReadOnlyError
156 * @throws UserBlockedError
158 public function execute( $par ) {
159 $this->useTransactionalTimeLimit();
162 $this->outputHeader();
164 # Check uploading enabled
165 if ( !UploadBase
::isEnabled() ) {
166 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
169 $this->addHelpLink( 'Help:Managing files' );
172 $user = $this->getUser();
173 $permissionRequired = UploadBase
::isAllowed( $user );
174 if ( $permissionRequired !== true ) {
175 throw new PermissionsError( $permissionRequired );
179 if ( $user->isBlockedFromUpload() ) {
180 throw new UserBlockedError( $user->getBlock() );
184 if ( $user->isBlockedGlobally() ) {
185 throw new UserBlockedError( $user->getGlobalBlock() );
188 # Check whether we actually want to allow changing stuff
189 $this->checkReadOnly();
191 $this->loadRequest();
193 # Unsave the temporary file in case this was a cancelled upload
194 if ( $this->mCancelUpload
&& !$this->unsaveUploadedFile() ) {
195 # Something went wrong, so unsaveUploadedFile showed a warning
199 # Process upload or show a form
201 $this->mTokenOk
&& !$this->mCancelUpload
&&
202 ( $this->mUpload
&& $this->mUploadClicked
)
204 $this->processUpload();
206 # Backwards compatibility hook
207 // Avoid PHP 7.1 warning of passing $this by reference
209 if ( !Hooks
::run( 'UploadForm:initial', [ &$upload ] ) ) {
210 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
214 $this->showUploadForm( $this->getUploadForm() );
218 if ( $this->mUpload
) {
219 $this->mUpload
->cleanupTempFile();
224 * Show the main upload form
226 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
228 protected function showUploadForm( $form ) {
229 # Add links if file was previously deleted
230 if ( $this->mDesiredDestName
) {
231 $this->showViewDeletedLinks();
234 if ( $form instanceof HTMLForm
) {
237 $this->getOutput()->addHTML( $form );
242 * Get an UploadForm instance with title and text properly set.
244 * @param string $message HTML string to add to the form
245 * @param string $sessionKey Session key in case this is a stashed upload
246 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
249 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
251 $context = new DerivativeContext( $this->getContext() );
252 $context->setTitle( $this->getPageTitle() ); // Remove subpage
253 $form = new UploadForm( [
254 'watch' => $this->getWatchCheck(),
255 'forreupload' => $this->mForReUpload
,
256 'sessionkey' => $sessionKey,
257 'hideignorewarning' => $hideIgnoreWarning,
258 'destwarningack' => (bool)$this->mDestWarningAck
,
260 'description' => $this->mComment
,
261 'texttop' => $this->uploadFormTextTop
,
262 'textaftersummary' => $this->uploadFormTextAfterSummary
,
263 'destfile' => $this->mDesiredDestName
,
264 ], $context, $this->getLinkRenderer() );
266 # Check the token, but only if necessary
268 !$this->mTokenOk
&& !$this->mCancelUpload
&&
269 ( $this->mUpload
&& $this->mUploadClicked
)
271 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
274 # Give a notice if the user is uploading a file that has been deleted or moved
275 # Note that this is independent from the message 'filewasdeleted'
276 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
277 $delNotice = ''; // empty by default
278 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
279 $dbr = wfGetDB( DB_REPLICA
);
281 LogEventsList
::showLogExtract( $delNotice, [ 'delete', 'move' ],
284 'conds' => [ 'log_action != ' . $dbr->addQuotes( 'revision' ) ],
285 'showIfEmpty' => false,
286 'msgKey' => [ 'upload-recreate-warning' ] ]
289 $form->addPreText( $delNotice );
292 $form->addPreText( '<div id="uploadtext">' .
293 $this->msg( 'uploadtext', [ $this->mDesiredDestName
] )->parseAsBlock() .
295 # Add upload error message
296 $form->addPreText( $message );
299 $uploadFooter = $this->msg( 'uploadfooter' );
300 if ( !$uploadFooter->isDisabled() ) {
301 $form->addPostText( '<div id="mw-upload-footer-message">'
302 . $uploadFooter->parseAsBlock() . "</div>\n" );
309 * Shows the "view X deleted revivions link""
311 protected function showViewDeletedLinks() {
312 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
313 $user = $this->getUser();
314 $permissionManager = MediaWikiServices
::getInstance()->getPermissionManager();
315 // Show a subtitle link to deleted revisions (to sysops et al only)
316 if ( $title instanceof Title
) {
317 $count = $title->isDeleted();
318 if ( $count > 0 && $permissionManager->userHasRight( $user, 'deletedhistory' ) ) {
319 $restorelink = $this->getLinkRenderer()->makeKnownLink(
320 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
321 $this->msg( 'restorelink' )->numParams( $count )->text()
324 $permissionManager->userHasRight( $user, 'delete' ) ?
'thisisdeleted' : 'viewdeleted'
325 )->rawParams( $restorelink )->parseAsBlock();
326 $this->getOutput()->addHTML(
329 [ 'id' => 'contentSub2' ],
338 * Stashes the upload and shows the main upload form.
340 * Note: only errors that can be handled by changing the name or
341 * description should be redirected here. It should be assumed that the
342 * file itself is sane and has passed UploadBase::verifyFile. This
343 * essentially means that UploadBase::VERIFICATION_ERROR and
344 * UploadBase::EMPTY_FILE should not be passed here.
346 * @param string $message HTML message to be passed to mainUploadForm
348 protected function showRecoverableUploadError( $message ) {
349 $stashStatus = $this->mUpload
->tryStashFile( $this->getUser() );
350 if ( $stashStatus->isGood() ) {
351 $sessionKey = $stashStatus->getValue()->getFileKey();
352 $uploadWarning = 'upload-tryagain';
355 $uploadWarning = 'upload-tryagain-nostash';
357 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
358 '<div class="error">' . $message . "</div>\n";
360 $form = $this->getUploadForm( $message, $sessionKey );
361 $form->setSubmitText( $this->msg( $uploadWarning )->escaped() );
362 $this->showUploadForm( $form );
366 * Stashes the upload, shows the main form, but adds a "continue anyway button".
367 * Also checks whether there are actually warnings to display.
369 * @param array $warnings
370 * @return bool True if warnings were displayed, false if there are no
371 * warnings and it should continue processing
373 protected function showUploadWarning( $warnings ) {
374 # If there are no warnings, or warnings we can ignore, return early.
375 # mDestWarningAck is set when some javascript has shown the warning
376 # to the user. mForReUpload is set when the user clicks the "upload a
378 if ( !$warnings ||
( count( $warnings ) == 1
379 && isset( $warnings['exists'] )
380 && ( $this->mDestWarningAck ||
$this->mForReUpload
) )
385 $stashStatus = $this->mUpload
->tryStashFile( $this->getUser() );
386 if ( $stashStatus->isGood() ) {
387 $sessionKey = $stashStatus->getValue()->getFileKey();
388 $uploadWarning = 'uploadwarning-text';
391 $uploadWarning = 'uploadwarning-text-nostash';
394 // Add styles for the warning, reused from the live preview
395 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
397 $linkRenderer = $this->getLinkRenderer();
398 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
399 . '<div class="mw-destfile-warning"><ul>';
400 foreach ( $warnings as $warning => $args ) {
401 if ( $warning == 'badfilename' ) {
402 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
404 if ( $warning == 'exists' ) {
405 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
406 } elseif ( $warning == 'no-change' ) {
408 $filename = $file->getTitle()->getPrefixedText();
409 $msg = "\t<li>" . $this->msg( 'fileexists-no-change', $filename )->parse() . "</li>\n";
410 } elseif ( $warning == 'duplicate-version' ) {
412 $count = count( $args );
413 $filename = $file->getTitle()->getPrefixedText();
414 $message = $this->msg( 'fileexists-duplicate-version' )
415 ->params( $filename )
416 ->numParams( $count );
417 $msg = "\t<li>" . $message->parse() . "</li>\n";
418 } elseif ( $warning == 'was-deleted' ) {
419 # If the file existed before and was deleted, warn the user of this
420 $ltitle = SpecialPage
::getTitleFor( 'Log' );
421 $llink = $linkRenderer->makeKnownLink(
423 $this->msg( 'deletionlog' )->text(),
427 'page' => Title
::makeTitle( NS_FILE
, $args )->getPrefixedText(),
430 $msg = "\t<li>" . $this->msg( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
431 } elseif ( $warning == 'duplicate' ) {
432 $msg = $this->getDupeWarning( $args );
433 } elseif ( $warning == 'duplicate-archive' ) {
434 if ( $args === '' ) {
435 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
438 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
439 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
443 if ( $args === true ) {
445 } elseif ( !is_array( $args ) ) {
448 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
450 $warningHtml .= $msg;
452 $warningHtml .= "</ul></div>\n";
453 $warningHtml .= $this->msg( $uploadWarning )->parseAsBlock();
455 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
456 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
458 'name' => 'wpUploadIgnoreWarning',
459 'value' => $this->msg( 'ignorewarning' )->text()
462 'name' => 'wpCancelUpload',
463 'value' => $this->msg( 'reuploaddesc' )->text()
466 $this->showUploadForm( $form );
468 # Indicate that we showed a form
473 * Show the upload form with error message, but do not stash the file.
475 * @param string $message HTML string
477 protected function showUploadError( $message ) {
478 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
479 '<div class="error">' . $message . "</div>\n";
480 $this->showUploadForm( $this->getUploadForm( $message ) );
485 * Checks are made in SpecialUpload::execute()
487 protected function processUpload() {
488 // Fetch the file if required
489 $status = $this->mUpload
->fetchFile();
490 if ( !$status->isOK() ) {
491 $this->showUploadError( $this->getOutput()->parseAsInterface(
492 $status->getWikiText( false, false, $this->getLanguage() )
497 // Avoid PHP 7.1 warning of passing $this by reference
499 if ( !Hooks
::run( 'UploadForm:BeforeProcessing', [ &$upload ] ) ) {
500 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
501 // This code path is deprecated. If you want to break upload processing
502 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
503 // and UploadBase::verifyFile.
504 // If you use this hook to break uploading, the user will be returned
505 // an empty form with no error message whatsoever.
509 // Upload verification
510 $details = $this->mUpload
->verifyUpload();
511 if ( $details['status'] != UploadBase
::OK
) {
512 $this->processVerificationError( $details );
517 // Verify permissions for this title
518 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
519 if ( $permErrors !== true ) {
520 $code = array_shift( $permErrors[0] );
521 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
526 $this->mLocalFile
= $this->mUpload
->getLocalFile();
528 // Check warnings if necessary
529 if ( !$this->mIgnoreWarning
) {
530 $warnings = $this->mUpload
->checkWarnings();
531 if ( $this->showUploadWarning( $warnings ) ) {
536 // This is as late as we can throttle, after expected issues have been handled
537 if ( UploadBase
::isThrottled( $this->getUser() ) ) {
538 $this->showRecoverableUploadError(
539 $this->msg( 'actionthrottledtext' )->escaped()
544 // Get the page text if this is not a reupload
545 if ( !$this->mForReUpload
) {
546 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
547 $this->mCopyrightStatus
, $this->mCopyrightSource
, $this->getConfig() );
552 $changeTags = $this->getRequest()->getVal( 'wpChangeTags' );
553 if ( is_null( $changeTags ) ||
$changeTags === '' ) {
556 $changeTags = array_filter( array_map( 'trim', explode( ',', $changeTags ) ) );
560 $changeTagsStatus = ChangeTags
::canAddTagsAccompanyingChange(
561 $changeTags, $this->getUser() );
562 if ( !$changeTagsStatus->isOK() ) {
563 $this->showUploadError( $this->getOutput()->parseAsInterface(
564 $changeTagsStatus->getWikiText( false, false, $this->getLanguage() )
571 $status = $this->mUpload
->performUpload(
579 if ( !$status->isGood() ) {
580 $this->showRecoverableUploadError(
581 $this->getOutput()->parseAsInterface(
582 $status->getWikiText( false, false, $this->getLanguage() )
589 // Success, redirect to description page
590 $this->mUploadSuccessful
= true;
591 // Avoid PHP 7.1 warning of passing $this by reference
593 Hooks
::run( 'SpecialUploadComplete', [ &$upload ] );
594 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
598 * Get the initial image page text based on a comment and optional file status information
599 * @param string $comment
600 * @param string $license
601 * @param string $copyStatus
602 * @param string $source
603 * @param Config|null $config Configuration object to load data from
606 public static function getInitialPageText( $comment = '', $license = '',
607 $copyStatus = '', $source = '', Config
$config = null
609 if ( $config === null ) {
610 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
611 $config = MediaWikiServices
::getInstance()->getMainConfig();
615 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
616 /* These messages are transcluded into the actual text of the description page.
617 * Thus, forcing them as content messages makes the upload to produce an int: template
618 * instead of hardcoding it there in the uploader language.
620 foreach ( [ 'license-header', 'filedesc', 'filestatus', 'filesource' ] as $msgName ) {
621 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
622 $msg[$msgName] = "{{int:$msgName}}";
624 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
629 if ( $license !== '' ) {
630 $licenseText = '== ' . $msg['license-header'] . " ==\n{{" . $license . "}}\n";
633 $pageText = $comment . "\n";
634 $headerText = '== ' . $msg['filedesc'] . ' ==';
635 if ( $comment !== '' && strpos( $comment, $headerText ) === false ) {
636 // prepend header to page text unless it's already there (or there is no content)
637 $pageText = $headerText . "\n" . $pageText;
640 if ( $config->get( 'UseCopyrightUpload' ) ) {
641 $pageText .= '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n";
642 $pageText .= $licenseText;
643 $pageText .= '== ' . $msg['filesource'] . " ==\n" . $source;
645 $pageText .= $licenseText;
648 // allow extensions to modify the content
649 Hooks
::run( 'UploadForm:getInitialPageText', [ &$pageText, $msg, $config ] );
655 * See if we should check the 'watch this page' checkbox on the form
656 * based on the user's preferences and whether we're being asked
657 * to create a new file or update an existing one.
659 * In the case where 'watch edits' is off but 'watch creations' is on,
660 * we'll leave the box unchecked.
662 * Note that the page target can be changed *on the form*, so our check
663 * state can get out of sync.
664 * @return bool|string
666 protected function getWatchCheck() {
667 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
672 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
673 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
674 // Already watched, don't change that
678 $local = MediaWikiServices
::getInstance()->getRepoGroup()->getLocalRepo()
679 ->newFile( $this->mDesiredDestName
);
680 if ( $local && $local->exists() ) {
681 // We're uploading a new version of an existing file.
682 // No creation, so don't watch it if we're not already.
685 // New page should get watched if that's our option.
686 return $this->getUser()->getOption( 'watchcreations' ) ||
687 $this->getUser()->getOption( 'watchuploads' );
692 * Provides output to the user for a result of UploadBase::verifyUpload
694 * @param array $details Result of UploadBase::verifyUpload
695 * @throws MWException
697 protected function processVerificationError( $details ) {
698 switch ( $details['status'] ) {
699 /** Statuses that only require name changing */
700 case UploadBase
::MIN_LENGTH_PARTNAME
:
701 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
703 case UploadBase
::ILLEGAL_FILENAME
:
704 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
705 $details['filtered'] )->parse() );
707 case UploadBase
::FILENAME_TOO_LONG
:
708 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
710 case UploadBase
::FILETYPE_MISSING
:
711 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
713 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
714 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
717 /** Statuses that require reuploading */
718 case UploadBase
::EMPTY_FILE
:
719 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
721 case UploadBase
::FILE_TOO_LARGE
:
722 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
724 case UploadBase
::FILETYPE_BADTYPE
:
725 $msg = $this->msg( 'filetype-banned-type' );
726 if ( isset( $details['blacklistedExt'] ) ) {
727 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
729 $msg->params( $details['finalExt'] );
731 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
732 $msg->params( $this->getLanguage()->commaList( $extensions ),
733 count( $extensions ) );
735 // Add PLURAL support for the first parameter. This results
736 // in a bit unlogical parameter sequence, but does not break
738 if ( isset( $details['blacklistedExt'] ) ) {
739 $msg->params( count( $details['blacklistedExt'] ) );
744 $this->showUploadError( $msg->parse() );
746 case UploadBase
::VERIFICATION_ERROR
:
747 unset( $details['status'] );
748 $code = array_shift( $details['details'] );
749 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
751 case UploadBase
::HOOK_ABORTED
:
752 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
753 $args = $details['error'];
754 $error = array_shift( $args );
756 $error = $details['error'];
760 $this->showUploadError( $this->msg( $error, $args )->parse() );
763 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
768 * Remove a temporarily kept file stashed by saveTempUploadedFile().
770 * @return bool Success
772 protected function unsaveUploadedFile() {
773 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
776 $success = $this->mUpload
->unsaveUploadedFile();
778 $this->getOutput()->showFatalError(
779 $this->msg( 'filedeleteerror' )
780 ->params( $this->mUpload
->getTempPath() )
790 /** Functions for formatting warnings */
793 * Formats a result of UploadBase::getExistsWarning as HTML
794 * This check is static and can be done pre-upload via AJAX
796 * @param array $exists The result of UploadBase::getExistsWarning
797 * @return string Empty string if there is no warning or an HTML fragment
799 public static function getExistsWarning( $exists ) {
804 $file = $exists['file'];
805 $filename = $file->getTitle()->getPrefixedText();
808 if ( $exists['warning'] == 'exists' ) {
810 $warnMsg = wfMessage( 'fileexists', $filename );
811 } elseif ( $exists['warning'] == 'page-exists' ) {
812 // Page exists but file does not
813 $warnMsg = wfMessage( 'filepageexists', $filename );
814 } elseif ( $exists['warning'] == 'exists-normalized' ) {
815 $warnMsg = wfMessage( 'fileexists-extension', $filename,
816 $exists['normalizedFile']->getTitle()->getPrefixedText() );
817 } elseif ( $exists['warning'] == 'thumb' ) {
818 // Swapped argument order compared with other messages for backwards compatibility
819 $warnMsg = wfMessage( 'fileexists-thumbnail-yes',
820 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
821 } elseif ( $exists['warning'] == 'thumb-name' ) {
822 // Image w/o '180px-' does not exists, but we do not like these filenames
823 $name = $file->getName();
824 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
825 $warnMsg = wfMessage( 'file-thumbnail-no', $badPart );
826 } elseif ( $exists['warning'] == 'bad-prefix' ) {
827 $warnMsg = wfMessage( 'filename-bad-prefix', $exists['prefix'] );
830 return $warnMsg ?
$warnMsg->title( $file->getTitle() )->parse() : '';
834 * Construct a warning and a gallery from an array of duplicate files.
835 * @param array $dupes
838 public function getDupeWarning( $dupes ) {
843 $gallery = ImageGalleryBase
::factory( false, $this->getContext() );
844 $gallery->setShowBytes( false );
845 $gallery->setShowDimensions( false );
846 foreach ( $dupes as $file ) {
847 $gallery->add( $file->getTitle() );
851 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
852 $gallery->toHTML() . "</li>\n";
855 protected function getGroupName() {
860 * Should we rotate images in the preview on Special:Upload.
862 * This controls js: mw.config.get( 'wgFileCanRotate' )
864 * @todo What about non-BitmapHandler handled files?
867 public static function rotationEnabled() {
868 $bitmapHandler = new BitmapHandler();
869 return $bitmapHandler->autoRotateEnabled();