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
26 * Form for handling uploads and special page.
28 * @ingroup SpecialPage
31 class SpecialUpload
extends SpecialPage
{
33 * Constructor : initialise object
34 * Get data POSTed through the form and assign them to the object
35 * @param $request WebRequest : data posted.
37 public function __construct( $request = null ) {
40 parent
::__construct( 'Upload', 'upload' );
42 $this->loadRequest( is_null( $request ) ?
$wgRequest : $request );
45 /** Misc variables **/
46 public $mRequest; // The WebRequest or FauxRequest this form is supposed to handle
58 public $mUploadClicked;
60 /** User input variables from the "description" section **/
61 public $mDesiredDestName; // The requested target file name
65 /** User input variables from the root section **/
66 public $mIgnoreWarning;
68 public $mCopyrightStatus;
69 public $mCopyrightSource;
71 /** Hidden variables **/
72 public $mDestWarningAck;
73 public $mForReUpload; // The user followed an "overwrite this file" link
74 public $mCancelUpload; // The user clicked "Cancel and return to upload form" button
76 public $mUploadSuccessful = false; // Subclasses can use this to determine whether a file was uploaded
78 /** Text injection points for hooks not using HTMLForm **/
79 public $uploadFormTextTop;
80 public $uploadFormTextAfterSummary;
85 * Initialize instance variables from request and create an Upload handler
87 * @param $request WebRequest: the request to extract variables from
89 protected function loadRequest( $request ) {
92 $this->mRequest
= $request;
93 $this->mSourceType
= $request->getVal( 'wpSourceType', 'file' );
94 $this->mUpload
= UploadBase
::createFromRequest( $request );
95 $this->mUploadClicked
= $request->wasPosted()
96 && ( $request->getCheck( 'wpUpload' )
97 ||
$request->getCheck( 'wpUploadIgnoreWarning' ) );
99 // Guess the desired name from the filename if not provided
100 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
101 if( !$this->mDesiredDestName
&& $request->getFileName( 'wpUploadFile' ) !== null ) {
102 $this->mDesiredDestName
= $request->getFileName( 'wpUploadFile' );
104 $this->mComment
= $request->getText( 'wpUploadDescription' );
105 $this->mLicense
= $request->getText( 'wpLicense' );
108 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
109 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
110 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
111 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $wgUser->isLoggedIn();
112 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
113 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
116 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
117 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
118 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
120 // If it was posted check for the token (no remote POST'ing with user credentials)
121 $token = $request->getVal( 'wpEditToken' );
122 if( $this->mSourceType
== 'file' && $token == null ) {
123 // Skip token check for file uploads as that can't be faked via JS...
124 // Some client-side tools don't expect to need to send wpEditToken
125 // with their submissions, as that's new in 1.16.
126 $this->mTokenOk
= true;
128 $this->mTokenOk
= $wgUser->matchEditToken( $token );
131 $this->uploadFormTextTop
= '';
132 $this->uploadFormTextAfterSummary
= '';
136 * This page can be shown if uploading is enabled.
137 * Handle permission checking elsewhere in order to be able to show
138 * custom error messages.
140 * @param $user User object
143 public function userCanExecute( User
$user ) {
144 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
148 * Special page entry point
150 public function execute( $par ) {
151 global $wgUser, $wgOut;
154 $this->outputHeader();
156 # Check uploading enabled
157 if( !UploadBase
::isEnabled() ) {
158 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
163 global $wgGroupPermissions;
164 $permissionRequired = UploadBase
::isAllowed( $wgUser );
165 if( $permissionRequired !== true ) {
166 if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
167 ||
$wgGroupPermissions['autoconfirmed']['upload'] ) ) {
168 // Custom message if logged-in users without any special rights can upload
169 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
171 $wgOut->permissionRequired( $permissionRequired );
177 if( $wgUser->isBlocked() ) {
178 $wgOut->blockedPage();
182 # Check whether we actually want to allow changing stuff
184 $wgOut->readOnlyPage();
188 # Unsave the temporary file in case this was a cancelled upload
189 if ( $this->mCancelUpload
) {
190 if ( !$this->unsaveUploadedFile() ) {
191 # Something went wrong, so unsaveUploadedFile showed a warning
196 # Process upload or show a form
198 $this->mTokenOk
&& !$this->mCancelUpload
&&
199 ( $this->mUpload
&& $this->mUploadClicked
)
202 $this->processUpload();
204 # Backwards compatibility hook
205 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
206 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
211 $this->showUploadForm( $this->getUploadForm() );
215 if ( $this->mUpload
) {
216 $this->mUpload
->cleanupTempFile();
221 * Show the main upload form
223 * @param $form Mixed: an HTMLForm instance or HTML string to show
225 protected function showUploadForm( $form ) {
226 # Add links if file was previously deleted
227 if ( !$this->mDesiredDestName
) {
228 $this->showViewDeletedLinks();
231 if ( $form instanceof HTMLForm
) {
235 $wgOut->addHTML( $form );
241 * Get an UploadForm instance with title and text properly set.
243 * @param $message String: HTML string to add to the form
244 * @param $sessionKey String: session key in case this is a stashed upload
245 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
248 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
252 $form = new UploadForm( array(
253 'watch' => $this->getWatchCheck(),
254 'forreupload' => $this->mForReUpload
,
255 'sessionkey' => $sessionKey,
256 'hideignorewarning' => $hideIgnoreWarning,
257 'destwarningack' => (bool)$this->mDestWarningAck
,
259 'description' => $this->mComment
,
260 'texttop' => $this->uploadFormTextTop
,
261 'textaftersummary' => $this->uploadFormTextAfterSummary
,
262 'destfile' => $this->mDesiredDestName
,
264 $form->setTitle( $this->getTitle() );
266 # Check the token, but only if necessary
268 !$this->mTokenOk
&& !$this->mCancelUpload
&&
269 ( $this->mUpload
&& $this->mUploadClicked
)
272 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
275 # Give a notice if the user is uploading a file that has been deleted or moved
276 # Note that this is independent from the message 'filewasdeleted' that requires JS
277 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
278 $delNotice = ''; // empty by default
279 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
280 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
281 $desiredTitleObj->getPrefixedText(),
282 '', array( 'lim' => 10,
283 'conds' => array( "log_action != 'revision'" ),
284 'showIfEmpty' => false,
285 'msgKey' => array( 'upload-recreate-warning' ) )
288 $form->addPreText( $delNotice );
291 $form->addPreText( '<div id="uploadtext">' .
292 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName
) ) .
294 # Add upload error message
295 $form->addPreText( $message );
298 $uploadFooter = wfMessage( 'uploadfooter' );
299 if ( !$uploadFooter->isDisabled() ) {
300 $form->addPostText( '<div id="mw-upload-footer-message">'
301 . $wgOut->parse( $uploadFooter->plain() ) . "</div>\n" );
309 * Shows the "view X deleted revivions link""
311 protected function showViewDeletedLinks() {
312 global $wgOut, $wgUser;
314 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
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 && $wgUser->isAllowed( 'deletedhistory' ) ) {
320 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
321 array( 'parse', 'replaceafter' ),
322 $wgUser->getSkin()->linkKnown(
323 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
324 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
327 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
331 // Show the relevant lines from deletion log (for still deleted files only)
332 if( $title instanceof Title
&& $title->isDeletedQuick() && !$title->exists() ) {
333 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
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 $message String: HTML message to be passed to mainUploadForm
348 protected function showRecoverableUploadError( $message ) {
349 $sessionKey = $this->mUpload
->stashSession();
350 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
351 '<div class="error">' . $message . "</div>\n";
353 $form = $this->getUploadForm( $message, $sessionKey );
354 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
355 $this->showUploadForm( $form );
358 * Stashes the upload, shows the main form, but adds an "continue anyway button".
359 * Also checks whether there are actually warnings to display.
361 * @param $warnings Array
362 * @return boolean true if warnings were displayed, false if there are no
363 * warnings and the should continue processing like there was no warning
365 protected function showUploadWarning( $warnings ) {
366 # If there are no warnings, or warnings we can ignore, return early.
367 # mDestWarningAck is set when some javascript has shown the warning
368 # to the user. mForReUpload is set when the user clicks the "upload a
370 if ( !$warnings ||
( count( $warnings ) == 1 &&
371 isset( $warnings['exists'] ) &&
372 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
377 $sessionKey = $this->mUpload
->stashSession();
379 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
380 . '<ul class="warning">';
381 foreach( $warnings as $warning => $args ) {
382 if( $warning == 'exists' ) {
383 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
384 } elseif( $warning == 'duplicate' ) {
385 $msg = self
::getDupeWarning( $args );
386 } elseif( $warning == 'duplicate-archive' ) {
387 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
388 array( Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() ) )
391 if ( $args === true ) {
393 } elseif ( !is_array( $args ) ) {
394 $args = array( $args );
396 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
398 $warningHtml .= $msg;
400 $warningHtml .= "</ul>\n";
401 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
403 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
404 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
405 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
406 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
408 $this->showUploadForm( $form );
410 # Indicate that we showed a form
415 * Show the upload form with error message, but do not stash the file.
417 * @param $message HTML string
419 protected function showUploadError( $message ) {
420 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
421 '<div class="error">' . $message . "</div>\n";
422 $this->showUploadForm( $this->getUploadForm( $message ) );
427 * Checks are made in SpecialUpload::execute()
429 protected function processUpload() {
430 global $wgUser, $wgOut;
432 // Fetch the file if required
433 $status = $this->mUpload
->fetchFile();
434 if( !$status->isOK() ) {
435 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
439 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
440 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
441 // This code path is deprecated. If you want to break upload processing
442 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
443 // and UploadBase::verifyFile.
444 // If you use this hook to break uploading, the user will be returned
445 // an empty form with no error message whatsoever.
449 // Upload verification
450 $details = $this->mUpload
->verifyUpload();
451 if ( $details['status'] != UploadBase
::OK
) {
452 $this->processVerificationError( $details );
456 // Verify permissions for this title
457 $permErrors = $this->mUpload
->verifyTitlePermissions( $wgUser );
458 if( $permErrors !== true ) {
459 $code = array_shift( $permErrors[0] );
460 $this->showRecoverableUploadError( wfMsgExt( $code,
461 'parseinline', $permErrors[0] ) );
465 $this->mLocalFile
= $this->mUpload
->getLocalFile();
467 // Check warnings if necessary
468 if( !$this->mIgnoreWarning
) {
469 $warnings = $this->mUpload
->checkWarnings();
470 if( $this->showUploadWarning( $warnings ) ) {
475 // Get the page text if this is not a reupload
476 if( !$this->mForReUpload
) {
477 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
478 $this->mCopyrightStatus
, $this->mCopyrightSource
);
482 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $wgUser );
483 if ( !$status->isGood() ) {
484 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
488 // Success, redirect to description page
489 $this->mUploadSuccessful
= true;
490 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
491 $wgOut->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
495 * Get the initial image page text based on a comment and optional file status information
497 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
498 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
499 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
501 /* These messages are transcluded into the actual text of the description page.
502 * Thus, forcing them as content messages makes the upload to produce an int: template
503 * instead of hardcoding it there in the uploader language.
505 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
506 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
507 $msg[$msgName] = "{{int:$msgName}}";
509 $msg[$msgName] = wfMsgForContent( $msgName );
513 if ( $wgUseCopyrightUpload ) {
515 if ( $license != '' ) {
516 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
518 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
519 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
521 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
523 if ( $license != '' ) {
524 $filedesc = $comment == '' ?
'' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
525 $pageText = $filedesc .
526 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
528 $pageText = $comment;
535 * See if we should check the 'watch this page' checkbox on the form
536 * based on the user's preferences and whether we're being asked
537 * to create a new file or update an existing one.
539 * In the case where 'watch edits' is off but 'watch creations' is on,
540 * we'll leave the box unchecked.
542 * Note that the page target can be changed *on the form*, so our check
543 * state can get out of sync.
545 protected function getWatchCheck() {
547 if( $wgUser->getOption( 'watchdefault' ) ) {
552 $local = wfLocalFile( $this->mDesiredDestName
);
553 if( $local && $local->exists() ) {
554 // We're uploading a new version of an existing file.
555 // No creation, so don't watch it if we're not already.
556 return $local->getTitle()->userIsWatching();
558 // New page should get watched if that's our option.
559 return $wgUser->getOption( 'watchcreations' );
565 * Provides output to the user for a result of UploadBase::verifyUpload
567 * @param $details Array: result of UploadBase::verifyUpload
569 protected function processVerificationError( $details ) {
570 global $wgFileExtensions, $wgLang;
572 switch( $details['status'] ) {
574 /** Statuses that only require name changing **/
575 case UploadBase
::MIN_LENGTH_PARTNAME
:
576 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
578 case UploadBase
::ILLEGAL_FILENAME
:
579 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
580 'parseinline', $details['filtered'] ) );
582 case UploadBase
::FILETYPE_MISSING
:
583 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
586 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
587 $this->showRecoverableUploadError( wfMsgExt( 'windows-nonascii-filename',
591 /** Statuses that require reuploading **/
592 case UploadBase
::EMPTY_FILE
:
593 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
595 case UploadBase
::FILE_TOO_LARGE
:
596 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
598 case UploadBase
::FILETYPE_BADTYPE
:
599 $msg = wfMessage( 'filetype-banned-type' );
600 if ( isset( $details['blacklistedExt'] ) ) {
601 $msg->params( $wgLang->commaList( $details['blacklistedExt'] ) );
603 $msg->params( $details['finalExt'] );
605 $msg->params( $wgLang->commaList( $wgFileExtensions ),
606 count( $wgFileExtensions ) );
608 // Add PLURAL support for the first parameter. This results
609 // in a bit unlogical parameter sequence, but does not break
611 if ( isset( $details['blacklistedExt'] ) ) {
612 $msg->params( count( $details['blacklistedExt'] ) );
617 $this->showUploadError( $msg->parse() );
619 case UploadBase
::VERIFICATION_ERROR
:
620 unset( $details['status'] );
621 $code = array_shift( $details['details'] );
622 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
624 case UploadBase
::HOOK_ABORTED
:
625 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
626 $args = $details['error'];
627 $error = array_shift( $args );
629 $error = $details['error'];
633 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
636 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
641 * Remove a temporarily kept file stashed by saveTempUploadedFile().
643 * @return Boolean: success
645 protected function unsaveUploadedFile() {
647 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
650 $success = $this->mUpload
->unsaveUploadedFile();
652 $wgOut->showFileDeleteError( $this->mUpload
->getTempPath() );
659 /*** Functions for formatting warnings ***/
662 * Formats a result of UploadBase::getExistsWarning as HTML
663 * This check is static and can be done pre-upload via AJAX
665 * @param $exists Array: the result of UploadBase::getExistsWarning
666 * @return String: empty string if there is no warning or an HTML fragment
668 public static function getExistsWarning( $exists ) {
675 $file = $exists['file'];
676 $filename = $file->getTitle()->getPrefixedText();
679 $sk = $wgUser->getSkin();
681 if( $exists['warning'] == 'exists' ) {
683 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
684 } elseif( $exists['warning'] == 'page-exists' ) {
685 // Page exists but file does not
686 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
687 } elseif ( $exists['warning'] == 'exists-normalized' ) {
688 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
689 $exists['normalizedFile']->getTitle()->getPrefixedText() );
690 } elseif ( $exists['warning'] == 'thumb' ) {
691 // Swapped argument order compared with other messages for backwards compatibility
692 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
693 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
694 } elseif ( $exists['warning'] == 'thumb-name' ) {
695 // Image w/o '180px-' does not exists, but we do not like these filenames
696 $name = $file->getName();
697 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
698 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
699 } elseif ( $exists['warning'] == 'bad-prefix' ) {
700 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
701 } elseif ( $exists['warning'] == 'was-deleted' ) {
702 # If the file existed before and was deleted, warn the user of this
703 $ltitle = SpecialPage
::getTitleFor( 'Log' );
704 $llink = $sk->linkKnown(
706 wfMsgHtml( 'deletionlog' ),
713 $warning = wfMsgExt( 'filewasdeleted', array( 'parse', 'replaceafter' ), $llink );
720 * Get a list of warnings
722 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
723 * @return Array: list of warning messages
725 public static function ajaxGetExistsWarning( $filename ) {
726 $file = wfFindFile( $filename );
728 // Force local file so we have an object to do further checks against
729 // if there isn't an exact match...
730 $file = wfLocalFile( $filename );
734 $exists = UploadBase
::getExistsWarning( $file );
735 $warning = self
::getExistsWarning( $exists );
736 if ( $warning !== '' ) {
737 $s = "<div>$warning</div>";
744 * Construct a warning and a gallery from an array of duplicate files.
746 public static function getDupeWarning( $dupes ) {
750 foreach( $dupes as $file ) {
751 $title = $file->getTitle();
752 $msg .= $title->getPrefixedText() .
753 '|' . $title->getText() . "\n";
755 $msg .= '</gallery>';
757 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
758 $wgOut->parse( $msg ) .
768 * Sub class of HTMLForm that provides the form section of SpecialUpload
770 class UploadForm
extends HTMLForm
{
772 protected $mForReUpload;
773 protected $mSessionKey;
774 protected $mHideIgnoreWarning;
775 protected $mDestWarningAck;
776 protected $mDestFile;
780 protected $mTextAfterSummary;
782 protected $mSourceIds;
784 protected $mMaxFileSize = array();
786 public function __construct( $options = array() ) {
787 $this->mWatch
= !empty( $options['watch'] );
788 $this->mForReUpload
= !empty( $options['forreupload'] );
789 $this->mSessionKey
= isset( $options['sessionkey'] )
790 ?
$options['sessionkey'] : '';
791 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
792 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
793 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
795 $this->mComment
= isset( $options['description'] ) ?
796 $options['description'] : '';
798 $this->mTextTop
= isset( $options['texttop'] )
799 ?
$options['texttop'] : '';
801 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
802 ?
$options['textaftersummary'] : '';
804 $sourceDescriptor = $this->getSourceSection();
805 $descriptor = $sourceDescriptor
806 +
$this->getDescriptionSection()
807 +
$this->getOptionsSection();
809 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
810 parent
::__construct( $descriptor, 'upload' );
812 # Set some form properties
813 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
814 $this->setSubmitName( 'wpUpload' );
815 # Used message keys: 'accesskey-upload', 'tooltip-upload'
816 $this->setSubmitTooltip( 'upload' );
817 $this->setId( 'mw-upload-form' );
819 # Build a list of IDs for javascript insertion
820 $this->mSourceIds
= array();
821 foreach ( $sourceDescriptor as $field ) {
822 if ( !empty( $field['id'] ) ) {
823 $this->mSourceIds
[] = $field['id'];
830 * Get the descriptor of the fieldset that contains the file source
831 * selection. The section is 'source'
833 * @return Array: descriptor array
835 protected function getSourceSection() {
836 global $wgLang, $wgUser, $wgRequest;
838 if ( $this->mSessionKey
) {
840 'SessionKey' => array(
842 'default' => $this->mSessionKey
,
844 'SourceType' => array(
846 'default' => 'Stash',
851 $canUploadByUrl = UploadFromUrl
::isEnabled() && $wgUser->isAllowed( 'upload_by_url' );
852 $radio = $canUploadByUrl;
853 $selectedSourceType = strtolower( $wgRequest->getText( 'wpSourceType', 'File' ) );
855 $descriptor = array();
856 if ( $this->mTextTop
) {
857 $descriptor['UploadFormTextTop'] = array(
859 'section' => 'source',
860 'default' => $this->mTextTop
,
865 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
866 # Limit to upload_max_filesize unless we are running under HipHop and
867 # that setting doesn't exist
868 if ( !wfIsHipHop() ) {
869 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
870 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ) );
873 $descriptor['UploadFile'] = array(
874 'class' => 'UploadSourceField',
875 'section' => 'source',
877 'id' => 'wpUploadFile',
878 'label-message' => 'sourcefilename',
879 'upload-type' => 'File',
881 'help' => wfMsgExt( 'upload-maxfilesize',
882 array( 'parseinline', 'escapenoentities' ),
883 $wgLang->formatSize( $this->mMaxUploadSize
['file'] )
884 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
885 'checked' => $selectedSourceType == 'file',
887 if ( $canUploadByUrl ) {
888 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
889 $descriptor['UploadFileURL'] = array(
890 'class' => 'UploadSourceField',
891 'section' => 'source',
892 'id' => 'wpUploadFileURL',
893 'label-message' => 'sourceurl',
894 'upload-type' => 'url',
896 'help' => wfMsgExt( 'upload-maxfilesize',
897 array( 'parseinline', 'escapenoentities' ),
898 $wgLang->formatSize( $this->mMaxUploadSize
['url'] )
899 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
900 'checked' => $selectedSourceType == 'url',
903 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
905 $descriptor['Extensions'] = array(
907 'section' => 'source',
908 'default' => $this->getExtensionsMessage(),
915 * Get the messages indicating which extensions are preferred and prohibitted.
917 * @return String: HTML string containing the message
919 protected function getExtensionsMessage() {
920 # Print a list of allowed file extensions, if so configured. We ignore
921 # MIME type here, it's incomprehensible to most people and too long.
922 global $wgLang, $wgCheckFileExtensions, $wgStrictFileExtensions,
923 $wgFileExtensions, $wgFileBlacklist;
925 if( $wgCheckFileExtensions ) {
926 if( $wgStrictFileExtensions ) {
927 # Everything not permitted is banned
929 '<div id="mw-upload-permitted">' .
930 wfMsgExt( 'upload-permitted', 'parse', $wgLang->commaList( $wgFileExtensions ) ) .
933 # We have to list both preferred and prohibited
935 '<div id="mw-upload-preferred">' .
936 wfMsgExt( 'upload-preferred', 'parse', $wgLang->commaList( $wgFileExtensions ) ) .
938 '<div id="mw-upload-prohibited">' .
939 wfMsgExt( 'upload-prohibited', 'parse', $wgLang->commaList( $wgFileBlacklist ) ) .
943 # Everything is permitted.
944 $extensionsList = '';
946 return $extensionsList;
950 * Get the descriptor of the fieldset that contains the file description
951 * input. The section is 'description'
953 * @return Array: descriptor array
955 protected function getDescriptionSection() {
958 if ( $this->mSessionKey
) {
959 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
961 $file = $stash->getFile( $this->mSessionKey
);
962 } catch ( MWException
$e ) {
968 $mto = $file->transform( array( 'width' => 120 ) );
969 $this->addHeaderText(
970 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
971 Html
::element( 'img', array(
972 'src' => $mto->getUrl(),
973 'class' => 'thumbimage',
974 ) ) . '</div>', 'description' );
981 'section' => 'description',
982 'id' => 'wpDestFile',
983 'label-message' => 'destfilename',
985 'default' => $this->mDestFile
,
986 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
987 'nodata' => strval( $this->mDestFile
) !== '',
989 'UploadDescription' => array(
990 'type' => 'textarea',
991 'section' => 'description',
992 'id' => 'wpUploadDescription',
993 'label-message' => $this->mForReUpload
994 ?
'filereuploadsummary'
995 : 'fileuploadsummary',
996 'default' => $this->mComment
,
997 'cols' => intval( $wgUser->getOption( 'cols' ) ),
1001 if ( $this->mTextAfterSummary
) {
1002 $descriptor['UploadFormTextAfterSummary'] = array(
1004 'section' => 'description',
1005 'default' => $this->mTextAfterSummary
,
1010 $descriptor +
= array(
1011 'EditTools' => array(
1012 'type' => 'edittools',
1013 'section' => 'description',
1014 'message' => 'edittools-upload',
1018 if ( $this->mForReUpload
) {
1019 $descriptor['DestFile']['readonly'] = true;
1021 $descriptor['License'] = array(
1023 'class' => 'Licenses',
1024 'section' => 'description',
1025 'id' => 'wpLicense',
1026 'label-message' => 'license',
1030 global $wgUseCopyrightUpload;
1031 if ( $wgUseCopyrightUpload ) {
1032 $descriptor['UploadCopyStatus'] = array(
1034 'section' => 'description',
1035 'id' => 'wpUploadCopyStatus',
1036 'label-message' => 'filestatus',
1038 $descriptor['UploadSource'] = array(
1040 'section' => 'description',
1041 'id' => 'wpUploadSource',
1042 'label-message' => 'filesource',
1050 * Get the descriptor of the fieldset that contains the upload options,
1051 * such as "watch this file". The section is 'options'
1053 * @return Array: descriptor array
1055 protected function getOptionsSection() {
1058 if ( $wgUser->isLoggedIn() ) {
1059 $descriptor = array(
1060 'Watchthis' => array(
1062 'id' => 'wpWatchthis',
1063 'label-message' => 'watchthisupload',
1064 'section' => 'options',
1065 'default' => $wgUser->getOption( 'watchcreations' ),
1069 if ( !$this->mHideIgnoreWarning
) {
1070 $descriptor['IgnoreWarning'] = array(
1072 'id' => 'wpIgnoreWarning',
1073 'label-message' => 'ignorewarnings',
1074 'section' => 'options',
1078 $descriptor['DestFileWarningAck'] = array(
1080 'id' => 'wpDestFileWarningAck',
1081 'default' => $this->mDestWarningAck ?
'1' : '',
1084 if ( $this->mForReUpload
) {
1085 $descriptor['ForReUpload'] = array(
1087 'id' => 'wpForReUpload',
1096 * Add the upload JS and show the form.
1098 public function show() {
1099 $this->addUploadJS();
1104 * Add upload JS to $wgOut
1106 protected function addUploadJS() {
1107 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1110 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1111 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1112 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1114 $scriptVars = array(
1115 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1116 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1117 'wgUploadAutoFill' => !$this->mForReUpload
&&
1118 // If we received mDestFile from the request, don't autofill
1119 // the wpDestFile textbox
1120 $this->mDestFile
=== '',
1121 'wgUploadSourceIds' => $this->mSourceIds
,
1122 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1123 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1124 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1127 $wgOut->addScript( Skin
::makeVariablesScript( $scriptVars ) );
1130 $wgOut->addModules( array(
1131 'mediawiki.legacy.edit', // For <charinsert> support
1132 'mediawiki.legacy.upload', // Old form stuff...
1133 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1138 * Empty function; submission is handled elsewhere.
1140 * @return bool false
1142 function trySubmit() {
1149 * A form field that contains a radio box in the label
1151 class UploadSourceField
extends HTMLTextField
{
1152 function getLabelHtml( $cellAttributes = array() ) {
1153 $id = "wpSourceType{$this->mParams['upload-type']}";
1154 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1156 if ( !empty( $this->mParams
['radio'] ) ) {
1158 'name' => 'wpSourceType',
1161 'value' => $this->mParams
['upload-type'],
1163 if ( !empty( $this->mParams
['checked'] ) ) {
1164 $attribs['checked'] = 'checked';
1166 $label .= Html
::element( 'input', $attribs );
1169 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1172 function getSize() {
1173 return isset( $this->mParams
['size'] )
1174 ?
$this->mParams
['size']