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 ) {
38 parent
::__construct( 'Upload', 'upload' );
41 /** Misc variables **/
42 public $mRequest; // The WebRequest or FauxRequest this form is supposed to handle
54 public $mUploadClicked;
56 /** User input variables from the "description" section **/
57 public $mDesiredDestName; // The requested target file name
61 /** User input variables from the root section **/
62 public $mIgnoreWarning;
64 public $mCopyrightStatus;
65 public $mCopyrightSource;
67 /** Hidden variables **/
68 public $mDestWarningAck;
69 public $mForReUpload; // The user followed an "overwrite this file" link
70 public $mCancelUpload; // The user clicked "Cancel and return to upload form" button
72 public $mUploadSuccessful = false; // Subclasses can use this to determine whether a file was uploaded
74 /** Text injection points for hooks not using HTMLForm **/
75 public $uploadFormTextTop;
76 public $uploadFormTextAfterSummary;
81 * Initialize instance variables from request and create an Upload handler
83 protected function loadRequest() {
84 $this->mRequest
= $request = $this->getRequest();
85 $this->mSourceType
= $request->getVal( 'wpSourceType', 'file' );
86 $this->mUpload
= UploadBase
::createFromRequest( $request );
87 $this->mUploadClicked
= $request->wasPosted()
88 && ( $request->getCheck( 'wpUpload' )
89 ||
$request->getCheck( 'wpUploadIgnoreWarning' ) );
91 // Guess the desired name from the filename if not provided
92 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
93 if( !$this->mDesiredDestName
&& $request->getFileName( 'wpUploadFile' ) !== null ) {
94 $this->mDesiredDestName
= $request->getFileName( 'wpUploadFile' );
96 $this->mComment
= $request->getText( 'wpUploadDescription' );
97 $this->mLicense
= $request->getText( 'wpLicense' );
100 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
101 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
102 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
103 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
104 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
105 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
108 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
109 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
110 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
112 // If it was posted check for the token (no remote POST'ing with user credentials)
113 $token = $request->getVal( 'wpEditToken' );
114 $this->mTokenOk
= $this->getUser()->matchEditToken( $token );
116 $this->uploadFormTextTop
= '';
117 $this->uploadFormTextAfterSummary
= '';
121 * This page can be shown if uploading is enabled.
122 * Handle permission checking elsewhere in order to be able to show
123 * custom error messages.
125 * @param $user User object
128 public function userCanExecute( User
$user ) {
129 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
133 * Special page entry point
135 public function execute( $par ) {
137 $this->outputHeader();
139 # Check uploading enabled
140 if( !UploadBase
::isEnabled() ) {
141 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
145 $user = $this->getUser();
146 $permissionRequired = UploadBase
::isAllowed( $user );
147 if( $permissionRequired !== true ) {
148 throw new PermissionsError( $permissionRequired );
152 if( $user->isBlocked() ) {
153 throw new UserBlockedError( $user->getBlock() );
156 # Check whether we actually want to allow changing stuff
157 $this->checkReadOnly();
159 $this->loadRequest();
161 # Unsave the temporary file in case this was a cancelled upload
162 if ( $this->mCancelUpload
) {
163 if ( !$this->unsaveUploadedFile() ) {
164 # Something went wrong, so unsaveUploadedFile showed a warning
169 # Process upload or show a form
171 $this->mTokenOk
&& !$this->mCancelUpload
&&
172 ( $this->mUpload
&& $this->mUploadClicked
)
174 $this->processUpload();
176 # Backwards compatibility hook
177 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
178 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
181 $this->showUploadForm( $this->getUploadForm() );
185 if ( $this->mUpload
) {
186 $this->mUpload
->cleanupTempFile();
191 * Show the main upload form
193 * @param $form Mixed: an HTMLForm instance or HTML string to show
195 protected function showUploadForm( $form ) {
196 # Add links if file was previously deleted
197 if ( $this->mDesiredDestName
) {
198 $this->showViewDeletedLinks();
201 if ( $form instanceof HTMLForm
) {
204 $this->getOutput()->addHTML( $form );
210 * Get an UploadForm instance with title and text properly set.
212 * @param $message String: HTML string to add to the form
213 * @param $sessionKey String: session key in case this is a stashed upload
214 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
217 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
219 $form = new UploadForm( array(
220 'watch' => $this->getWatchCheck(),
221 'forreupload' => $this->mForReUpload
,
222 'sessionkey' => $sessionKey,
223 'hideignorewarning' => $hideIgnoreWarning,
224 'destwarningack' => (bool)$this->mDestWarningAck
,
226 'description' => $this->mComment
,
227 'texttop' => $this->uploadFormTextTop
,
228 'textaftersummary' => $this->uploadFormTextAfterSummary
,
229 'destfile' => $this->mDesiredDestName
,
230 ), $this->getContext() );
231 $form->setTitle( $this->getTitle() );
233 # Check the token, but only if necessary
235 !$this->mTokenOk
&& !$this->mCancelUpload
&&
236 ( $this->mUpload
&& $this->mUploadClicked
)
238 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
241 # Give a notice if the user is uploading a file that has been deleted or moved
242 # Note that this is independent from the message 'filewasdeleted' that requires JS
243 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
244 $delNotice = ''; // empty by default
245 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
246 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
248 '', array( 'lim' => 10,
249 'conds' => array( "log_action != 'revision'" ),
250 'showIfEmpty' => false,
251 'msgKey' => array( 'upload-recreate-warning' ) )
254 $form->addPreText( $delNotice );
257 $form->addPreText( '<div id="uploadtext">' .
258 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName
) ) .
260 # Add upload error message
261 $form->addPreText( $message );
264 $uploadFooter = wfMessage( 'uploadfooter' );
265 if ( !$uploadFooter->isDisabled() ) {
266 $form->addPostText( '<div id="mw-upload-footer-message">'
267 . $this->getOutput()->parse( $uploadFooter->plain() ) . "</div>\n" );
274 * Shows the "view X deleted revivions link""
276 protected function showViewDeletedLinks() {
277 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
278 $user = $this->getUser();
279 // Show a subtitle link to deleted revisions (to sysops et al only)
280 if( $title instanceof Title
) {
281 $count = $title->isDeleted();
282 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
284 $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
285 array( 'parse', 'replaceafter' ),
287 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
288 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
291 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
297 * Stashes the upload and shows the main upload form.
299 * Note: only errors that can be handled by changing the name or
300 * description should be redirected here. It should be assumed that the
301 * file itself is sane and has passed UploadBase::verifyFile. This
302 * essentially means that UploadBase::VERIFICATION_ERROR and
303 * UploadBase::EMPTY_FILE should not be passed here.
305 * @param $message String: HTML message to be passed to mainUploadForm
307 protected function showRecoverableUploadError( $message ) {
308 $sessionKey = $this->mUpload
->stashSession();
309 $message = '<h2>' . wfMsgHtml( 'uploaderror' ) . "</h2>\n" .
310 '<div class="error">' . $message . "</div>\n";
312 $form = $this->getUploadForm( $message, $sessionKey );
313 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
314 $this->showUploadForm( $form );
317 * Stashes the upload, shows the main form, but adds an "continue anyway button".
318 * Also checks whether there are actually warnings to display.
320 * @param $warnings Array
321 * @return boolean true if warnings were displayed, false if there are no
322 * warnings and the should continue processing like there was no warning
324 protected function showUploadWarning( $warnings ) {
325 # If there are no warnings, or warnings we can ignore, return early.
326 # mDestWarningAck is set when some javascript has shown the warning
327 # to the user. mForReUpload is set when the user clicks the "upload a
329 if ( !$warnings ||
( count( $warnings ) == 1 &&
330 isset( $warnings['exists'] ) &&
331 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
336 $sessionKey = $this->mUpload
->stashSession();
338 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
339 . '<ul class="warning">';
340 foreach( $warnings as $warning => $args ) {
341 if( $warning == 'exists' ) {
342 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
343 } elseif( $warning == 'duplicate' ) {
344 $msg = self
::getDupeWarning( $args );
345 } elseif( $warning == 'duplicate-archive' ) {
346 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
347 array( Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() ) )
350 if ( $args === true ) {
352 } elseif ( !is_array( $args ) ) {
353 $args = array( $args );
355 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
357 $warningHtml .= $msg;
359 $warningHtml .= "</ul>\n";
360 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
362 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
363 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
364 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
365 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
367 $this->showUploadForm( $form );
369 # Indicate that we showed a form
374 * Show the upload form with error message, but do not stash the file.
376 * @param $message string HTML string
378 protected function showUploadError( $message ) {
379 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
380 '<div class="error">' . $message . "</div>\n";
381 $this->showUploadForm( $this->getUploadForm( $message ) );
386 * Checks are made in SpecialUpload::execute()
388 protected function processUpload() {
389 // Fetch the file if required
390 $status = $this->mUpload
->fetchFile();
391 if( !$status->isOK() ) {
392 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
396 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
397 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
398 // This code path is deprecated. If you want to break upload processing
399 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
400 // and UploadBase::verifyFile.
401 // If you use this hook to break uploading, the user will be returned
402 // an empty form with no error message whatsoever.
406 // Upload verification
407 $details = $this->mUpload
->verifyUpload();
408 if ( $details['status'] != UploadBase
::OK
) {
409 $this->processVerificationError( $details );
413 // Verify permissions for this title
414 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
415 if( $permErrors !== true ) {
416 $code = array_shift( $permErrors[0] );
417 $this->showRecoverableUploadError( wfMsgExt( $code,
418 'parseinline', $permErrors[0] ) );
422 $this->mLocalFile
= $this->mUpload
->getLocalFile();
424 // Check warnings if necessary
425 if( !$this->mIgnoreWarning
) {
426 $warnings = $this->mUpload
->checkWarnings();
427 if( $this->showUploadWarning( $warnings ) ) {
432 // Get the page text if this is not a reupload
433 if( !$this->mForReUpload
) {
434 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
435 $this->mCopyrightStatus
, $this->mCopyrightSource
);
439 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $this->getUser() );
440 if ( !$status->isGood() ) {
441 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
445 // Success, redirect to description page
446 $this->mUploadSuccessful
= true;
447 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
448 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
452 * Get the initial image page text based on a comment and optional file status information
453 * @param $comment string
454 * @param $license string
455 * @param $copyStatus string
456 * @param $source string
459 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
460 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
461 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
464 /* These messages are transcluded into the actual text of the description page.
465 * Thus, forcing them as content messages makes the upload to produce an int: template
466 * instead of hardcoding it there in the uploader language.
468 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
469 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
470 $msg[$msgName] = "{{int:$msgName}}";
472 $msg[$msgName] = wfMsgForContent( $msgName );
476 if ( $wgUseCopyrightUpload ) {
478 if ( $license != '' ) {
479 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
481 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
482 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
484 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
486 if ( $license != '' ) {
487 $filedesc = $comment == '' ?
'' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
488 $pageText = $filedesc .
489 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
491 $pageText = $comment;
498 * See if we should check the 'watch this page' checkbox on the form
499 * based on the user's preferences and whether we're being asked
500 * to create a new file or update an existing one.
502 * In the case where 'watch edits' is off but 'watch creations' is on,
503 * we'll leave the box unchecked.
505 * Note that the page target can be changed *on the form*, so our check
506 * state can get out of sync.
507 * @return Bool|String
509 protected function getWatchCheck() {
510 if( $this->getUser()->getOption( 'watchdefault' ) ) {
515 $local = wfLocalFile( $this->mDesiredDestName
);
516 if( $local && $local->exists() ) {
517 // We're uploading a new version of an existing file.
518 // No creation, so don't watch it if we're not already.
519 return $local->getTitle()->userIsWatching();
521 // New page should get watched if that's our option.
522 return $this->getUser()->getOption( 'watchcreations' );
528 * Provides output to the user for a result of UploadBase::verifyUpload
530 * @param $details Array: result of UploadBase::verifyUpload
532 protected function processVerificationError( $details ) {
533 global $wgFileExtensions;
535 switch( $details['status'] ) {
537 /** Statuses that only require name changing **/
538 case UploadBase
::MIN_LENGTH_PARTNAME
:
539 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
541 case UploadBase
::ILLEGAL_FILENAME
:
542 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
543 'parseinline', $details['filtered'] ) );
545 case UploadBase
::FILENAME_TOO_LONG
:
546 $this->showRecoverableUploadError( wfMsgHtml( 'filename-toolong' ) );
548 case UploadBase
::FILETYPE_MISSING
:
549 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
552 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
553 $this->showRecoverableUploadError( wfMsgExt( 'windows-nonascii-filename',
557 /** Statuses that require reuploading **/
558 case UploadBase
::EMPTY_FILE
:
559 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
561 case UploadBase
::FILE_TOO_LARGE
:
562 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
564 case UploadBase
::FILETYPE_BADTYPE
:
565 $msg = wfMessage( 'filetype-banned-type' );
566 if ( isset( $details['blacklistedExt'] ) ) {
567 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
569 $msg->params( $details['finalExt'] );
571 $msg->params( $this->getLanguage()->commaList( $wgFileExtensions ),
572 count( $wgFileExtensions ) );
574 // Add PLURAL support for the first parameter. This results
575 // in a bit unlogical parameter sequence, but does not break
577 if ( isset( $details['blacklistedExt'] ) ) {
578 $msg->params( count( $details['blacklistedExt'] ) );
583 $this->showUploadError( $msg->parse() );
585 case UploadBase
::VERIFICATION_ERROR
:
586 unset( $details['status'] );
587 $code = array_shift( $details['details'] );
588 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
590 case UploadBase
::HOOK_ABORTED
:
591 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
592 $args = $details['error'];
593 $error = array_shift( $args );
595 $error = $details['error'];
599 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
602 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
607 * Remove a temporarily kept file stashed by saveTempUploadedFile().
609 * @return Boolean: success
611 protected function unsaveUploadedFile() {
612 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
615 $success = $this->mUpload
->unsaveUploadedFile();
617 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
624 /*** Functions for formatting warnings ***/
627 * Formats a result of UploadBase::getExistsWarning as HTML
628 * This check is static and can be done pre-upload via AJAX
630 * @param $exists Array: the result of UploadBase::getExistsWarning
631 * @return String: empty string if there is no warning or an HTML fragment
633 public static function getExistsWarning( $exists ) {
638 $file = $exists['file'];
639 $filename = $file->getTitle()->getPrefixedText();
642 if( $exists['warning'] == 'exists' ) {
644 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
645 } elseif( $exists['warning'] == 'page-exists' ) {
646 // Page exists but file does not
647 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
648 } elseif ( $exists['warning'] == 'exists-normalized' ) {
649 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
650 $exists['normalizedFile']->getTitle()->getPrefixedText() );
651 } elseif ( $exists['warning'] == 'thumb' ) {
652 // Swapped argument order compared with other messages for backwards compatibility
653 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
654 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
655 } elseif ( $exists['warning'] == 'thumb-name' ) {
656 // Image w/o '180px-' does not exists, but we do not like these filenames
657 $name = $file->getName();
658 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
659 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
660 } elseif ( $exists['warning'] == 'bad-prefix' ) {
661 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
662 } elseif ( $exists['warning'] == 'was-deleted' ) {
663 # If the file existed before and was deleted, warn the user of this
664 $ltitle = SpecialPage
::getTitleFor( 'Log' );
665 $llink = Linker
::linkKnown(
667 wfMsgHtml( 'deletionlog' ),
674 $warning = wfMsgExt( 'filewasdeleted', array( 'parse', 'replaceafter' ), $llink );
681 * Get a list of warnings
683 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
684 * @return Array: list of warning messages
686 public static function ajaxGetExistsWarning( $filename ) {
687 $file = wfFindFile( $filename );
689 // Force local file so we have an object to do further checks against
690 // if there isn't an exact match...
691 $file = wfLocalFile( $filename );
695 $exists = UploadBase
::getExistsWarning( $file );
696 $warning = self
::getExistsWarning( $exists );
697 if ( $warning !== '' ) {
698 $s = "<div>$warning</div>";
705 * Construct a warning and a gallery from an array of duplicate files.
706 * @param $dupes array
709 public static function getDupeWarning( $dupes ) {
713 foreach( $dupes as $file ) {
714 $title = $file->getTitle();
715 $msg .= $title->getPrefixedText() .
716 '|' . $title->getText() . "\n";
718 $msg .= '</gallery>';
720 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
721 $wgOut->parse( $msg ) .
731 * Sub class of HTMLForm that provides the form section of SpecialUpload
733 class UploadForm
extends HTMLForm
{
735 protected $mForReUpload;
736 protected $mSessionKey;
737 protected $mHideIgnoreWarning;
738 protected $mDestWarningAck;
739 protected $mDestFile;
743 protected $mTextAfterSummary;
745 protected $mSourceIds;
747 protected $mMaxFileSize = array();
749 protected $mMaxUploadSize = array();
751 public function __construct( array $options = array(), IContextSource
$context = null ) {
752 $this->mWatch
= !empty( $options['watch'] );
753 $this->mForReUpload
= !empty( $options['forreupload'] );
754 $this->mSessionKey
= isset( $options['sessionkey'] )
755 ?
$options['sessionkey'] : '';
756 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
757 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
758 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
760 $this->mComment
= isset( $options['description'] ) ?
761 $options['description'] : '';
763 $this->mTextTop
= isset( $options['texttop'] )
764 ?
$options['texttop'] : '';
766 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
767 ?
$options['textaftersummary'] : '';
769 $sourceDescriptor = $this->getSourceSection();
770 $descriptor = $sourceDescriptor
771 +
$this->getDescriptionSection()
772 +
$this->getOptionsSection();
774 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
775 parent
::__construct( $descriptor, $context, 'upload' );
777 # Set some form properties
778 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
779 $this->setSubmitName( 'wpUpload' );
780 # Used message keys: 'accesskey-upload', 'tooltip-upload'
781 $this->setSubmitTooltip( 'upload' );
782 $this->setId( 'mw-upload-form' );
784 # Build a list of IDs for javascript insertion
785 $this->mSourceIds
= array();
786 foreach ( $sourceDescriptor as $field ) {
787 if ( !empty( $field['id'] ) ) {
788 $this->mSourceIds
[] = $field['id'];
795 * Get the descriptor of the fieldset that contains the file source
796 * selection. The section is 'source'
798 * @return Array: descriptor array
800 protected function getSourceSection() {
801 if ( $this->mSessionKey
) {
803 'SessionKey' => array(
805 'default' => $this->mSessionKey
,
807 'SourceType' => array(
809 'default' => 'Stash',
814 $canUploadByUrl = UploadFromUrl
::isEnabled() && UploadFromUrl
::isAllowed( $this->getUser() );
815 $radio = $canUploadByUrl;
816 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
818 $descriptor = array();
819 if ( $this->mTextTop
) {
820 $descriptor['UploadFormTextTop'] = array(
822 'section' => 'source',
823 'default' => $this->mTextTop
,
828 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
829 # Limit to upload_max_filesize unless we are running under HipHop and
830 # that setting doesn't exist
831 if ( !wfIsHipHop() ) {
832 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
833 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
834 wfShorthandToInteger( ini_get( 'post_max_size' ) )
838 $descriptor['UploadFile'] = array(
839 'class' => 'UploadSourceField',
840 'section' => 'source',
842 'id' => 'wpUploadFile',
843 'label-message' => 'sourcefilename',
844 'upload-type' => 'File',
846 'help' => wfMsgExt( 'upload-maxfilesize',
847 array( 'parseinline', 'escapenoentities' ),
848 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
849 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
850 'checked' => $selectedSourceType == 'file',
852 if ( $canUploadByUrl ) {
853 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
854 $descriptor['UploadFileURL'] = array(
855 'class' => 'UploadSourceField',
856 'section' => 'source',
857 'id' => 'wpUploadFileURL',
858 'label-message' => 'sourceurl',
859 'upload-type' => 'url',
861 'help' => wfMsgExt( 'upload-maxfilesize',
862 array( 'parseinline', 'escapenoentities' ),
863 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
864 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
865 'checked' => $selectedSourceType == 'url',
868 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
870 $descriptor['Extensions'] = array(
872 'section' => 'source',
873 'default' => $this->getExtensionsMessage(),
880 * Get the messages indicating which extensions are preferred and prohibitted.
882 * @return String: HTML string containing the message
884 protected function getExtensionsMessage() {
885 # Print a list of allowed file extensions, if so configured. We ignore
886 # MIME type here, it's incomprehensible to most people and too long.
887 global $wgCheckFileExtensions, $wgStrictFileExtensions,
888 $wgFileExtensions, $wgFileBlacklist;
890 if( $wgCheckFileExtensions ) {
891 if( $wgStrictFileExtensions ) {
892 # Everything not permitted is banned
894 '<div id="mw-upload-permitted">' .
895 wfMsgExt( 'upload-permitted', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) ) .
898 # We have to list both preferred and prohibited
900 '<div id="mw-upload-preferred">' .
901 wfMsgExt( 'upload-preferred', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) ) .
903 '<div id="mw-upload-prohibited">' .
904 wfMsgExt( 'upload-prohibited', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileBlacklist ) ) .
908 # Everything is permitted.
909 $extensionsList = '';
911 return $extensionsList;
915 * Get the descriptor of the fieldset that contains the file description
916 * input. The section is 'description'
918 * @return Array: descriptor array
920 protected function getDescriptionSection() {
921 if ( $this->mSessionKey
) {
922 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
924 $file = $stash->getFile( $this->mSessionKey
);
925 } catch ( MWException
$e ) {
931 $mto = $file->transform( array( 'width' => 120 ) );
932 $this->addHeaderText(
933 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
934 Html
::element( 'img', array(
935 'src' => $mto->getUrl(),
936 'class' => 'thumbimage',
937 ) ) . '</div>', 'description' );
944 'section' => 'description',
945 'id' => 'wpDestFile',
946 'label-message' => 'destfilename',
948 'default' => $this->mDestFile
,
949 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
950 'nodata' => strval( $this->mDestFile
) !== '',
952 'UploadDescription' => array(
953 'type' => 'textarea',
954 'section' => 'description',
955 'id' => 'wpUploadDescription',
956 'label-message' => $this->mForReUpload
957 ?
'filereuploadsummary'
958 : 'fileuploadsummary',
959 'default' => $this->mComment
,
960 'cols' => intval( $this->getUser()->getOption( 'cols' ) ),
964 if ( $this->mTextAfterSummary
) {
965 $descriptor['UploadFormTextAfterSummary'] = array(
967 'section' => 'description',
968 'default' => $this->mTextAfterSummary
,
973 $descriptor +
= array(
974 'EditTools' => array(
975 'type' => 'edittools',
976 'section' => 'description',
977 'message' => 'edittools-upload',
981 if ( $this->mForReUpload
) {
982 $descriptor['DestFile']['readonly'] = true;
984 $descriptor['License'] = array(
986 'class' => 'Licenses',
987 'section' => 'description',
989 'label-message' => 'license',
993 global $wgUseCopyrightUpload;
994 if ( $wgUseCopyrightUpload ) {
995 $descriptor['UploadCopyStatus'] = array(
997 'section' => 'description',
998 'id' => 'wpUploadCopyStatus',
999 'label-message' => 'filestatus',
1001 $descriptor['UploadSource'] = array(
1003 'section' => 'description',
1004 'id' => 'wpUploadSource',
1005 'label-message' => 'filesource',
1013 * Get the descriptor of the fieldset that contains the upload options,
1014 * such as "watch this file". The section is 'options'
1016 * @return Array: descriptor array
1018 protected function getOptionsSection() {
1019 $user = $this->getUser();
1020 if ( $user->isLoggedIn() ) {
1021 $descriptor = array(
1022 'Watchthis' => array(
1024 'id' => 'wpWatchthis',
1025 'label-message' => 'watchthisupload',
1026 'section' => 'options',
1027 'default' => $user->getOption( 'watchcreations' ),
1031 if ( !$this->mHideIgnoreWarning
) {
1032 $descriptor['IgnoreWarning'] = array(
1034 'id' => 'wpIgnoreWarning',
1035 'label-message' => 'ignorewarnings',
1036 'section' => 'options',
1040 $descriptor['DestFileWarningAck'] = array(
1042 'id' => 'wpDestFileWarningAck',
1043 'default' => $this->mDestWarningAck ?
'1' : '',
1046 if ( $this->mForReUpload
) {
1047 $descriptor['ForReUpload'] = array(
1049 'id' => 'wpForReUpload',
1058 * Add the upload JS and show the form.
1060 public function show() {
1061 $this->addUploadJS();
1066 * Add upload JS to the OutputPage
1068 protected function addUploadJS() {
1069 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1071 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1072 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1073 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1075 $scriptVars = array(
1076 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1077 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1078 'wgUploadAutoFill' => !$this->mForReUpload
&&
1079 // If we received mDestFile from the request, don't autofill
1080 // the wpDestFile textbox
1081 $this->mDestFile
=== '',
1082 'wgUploadSourceIds' => $this->mSourceIds
,
1083 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1084 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1085 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1088 $out = $this->getOutput();
1089 $out->addJsConfigVars( $scriptVars );
1092 $out->addModules( array(
1093 'mediawiki.action.edit', // For <charinsert> support
1094 'mediawiki.legacy.upload', // Old form stuff...
1095 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1100 * Empty function; submission is handled elsewhere.
1102 * @return bool false
1104 function trySubmit() {
1111 * A form field that contains a radio box in the label
1113 class UploadSourceField
extends HTMLTextField
{
1116 * @param $cellAttributes array
1119 function getLabelHtml( $cellAttributes = array() ) {
1120 $id = "wpSourceType{$this->mParams['upload-type']}";
1121 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1123 if ( !empty( $this->mParams
['radio'] ) ) {
1125 'name' => 'wpSourceType',
1128 'value' => $this->mParams
['upload-type'],
1130 if ( !empty( $this->mParams
['checked'] ) ) {
1131 $attribs['checked'] = 'checked';
1133 $label .= Html
::element( 'input', $attribs );
1136 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1142 function getSize() {
1143 return isset( $this->mParams
['size'] )
1144 ?
$this->mParams
['size']