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 if( $this->mSourceType
== 'file' && $token == null ) {
115 // Skip token check for file uploads as that can't be faked via JS...
116 // Some client-side tools don't expect to need to send wpEditToken
117 // with their submissions, as that's new in 1.16.
118 $this->mTokenOk
= true;
120 $this->mTokenOk
= $this->getUser()->matchEditToken( $token );
123 $this->uploadFormTextTop
= '';
124 $this->uploadFormTextAfterSummary
= '';
128 * This page can be shown if uploading is enabled.
129 * Handle permission checking elsewhere in order to be able to show
130 * custom error messages.
132 * @param $user User object
135 public function userCanExecute( User
$user ) {
136 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
140 * Special page entry point
142 public function execute( $par ) {
144 $this->outputHeader();
146 # Check uploading enabled
147 if( !UploadBase
::isEnabled() ) {
148 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
152 $user = $this->getUser();
153 $permissionRequired = UploadBase
::isAllowed( $user );
154 if( $permissionRequired !== true ) {
155 throw new PermissionsError( $permissionRequired );
159 if( $user->isBlocked() ) {
160 throw new UserBlockedError( $user->mBlock
);
163 # Check whether we actually want to allow changing stuff
164 $this->checkReadOnly();
166 $this->loadRequest();
168 # Unsave the temporary file in case this was a cancelled upload
169 if ( $this->mCancelUpload
) {
170 if ( !$this->unsaveUploadedFile() ) {
171 # Something went wrong, so unsaveUploadedFile showed a warning
176 # Process upload or show a form
178 $this->mTokenOk
&& !$this->mCancelUpload
&&
179 ( $this->mUpload
&& $this->mUploadClicked
)
182 $this->processUpload();
184 # Backwards compatibility hook
185 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
186 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
191 $this->showUploadForm( $this->getUploadForm() );
195 if ( $this->mUpload
) {
196 $this->mUpload
->cleanupTempFile();
201 * Show the main upload form
203 * @param $form Mixed: an HTMLForm instance or HTML string to show
205 protected function showUploadForm( $form ) {
206 # Add links if file was previously deleted
207 if ( $this->mDesiredDestName
) {
208 $this->showViewDeletedLinks();
211 if ( $form instanceof HTMLForm
) {
214 $this->getOutput()->addHTML( $form );
220 * Get an UploadForm instance with title and text properly set.
222 * @param $message String: HTML string to add to the form
223 * @param $sessionKey String: session key in case this is a stashed upload
224 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
227 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
229 $form = new UploadForm( array(
230 'watch' => $this->getWatchCheck(),
231 'forreupload' => $this->mForReUpload
,
232 'sessionkey' => $sessionKey,
233 'hideignorewarning' => $hideIgnoreWarning,
234 'destwarningack' => (bool)$this->mDestWarningAck
,
236 'description' => $this->mComment
,
237 'texttop' => $this->uploadFormTextTop
,
238 'textaftersummary' => $this->uploadFormTextAfterSummary
,
239 'destfile' => $this->mDesiredDestName
,
240 ), $this->getContext() );
241 $form->setTitle( $this->getTitle() );
243 # Check the token, but only if necessary
245 !$this->mTokenOk
&& !$this->mCancelUpload
&&
246 ( $this->mUpload
&& $this->mUploadClicked
)
249 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
252 # Give a notice if the user is uploading a file that has been deleted or moved
253 # Note that this is independent from the message 'filewasdeleted' that requires JS
254 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
255 $delNotice = ''; // empty by default
256 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
257 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
259 '', array( 'lim' => 10,
260 'conds' => array( "log_action != 'revision'" ),
261 'showIfEmpty' => false,
262 'msgKey' => array( 'upload-recreate-warning' ) )
265 $form->addPreText( $delNotice );
268 $form->addPreText( '<div id="uploadtext">' .
269 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName
) ) .
271 # Add upload error message
272 $form->addPreText( $message );
275 $uploadFooter = wfMessage( 'uploadfooter' );
276 if ( !$uploadFooter->isDisabled() ) {
277 $form->addPostText( '<div id="mw-upload-footer-message">'
278 . $this->getOutput()->parse( $uploadFooter->plain() ) . "</div>\n" );
286 * Shows the "view X deleted revivions link""
288 protected function showViewDeletedLinks() {
289 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
290 $user = $this->getUser();
291 // Show a subtitle link to deleted revisions (to sysops et al only)
292 if( $title instanceof Title
) {
293 $count = $title->isDeleted();
294 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
296 $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
297 array( 'parse', 'replaceafter' ),
299 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
300 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
303 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
309 * Stashes the upload and shows the main upload form.
311 * Note: only errors that can be handled by changing the name or
312 * description should be redirected here. It should be assumed that the
313 * file itself is sane and has passed UploadBase::verifyFile. This
314 * essentially means that UploadBase::VERIFICATION_ERROR and
315 * UploadBase::EMPTY_FILE should not be passed here.
317 * @param $message String: HTML message to be passed to mainUploadForm
319 protected function showRecoverableUploadError( $message ) {
320 $sessionKey = $this->mUpload
->stashSession();
321 $message = '<h2>' . wfMsgHtml( 'uploaderror' ) . "</h2>\n" .
322 '<div class="error">' . $message . "</div>\n";
324 $form = $this->getUploadForm( $message, $sessionKey );
325 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
326 $this->showUploadForm( $form );
329 * Stashes the upload, shows the main form, but adds an "continue anyway button".
330 * Also checks whether there are actually warnings to display.
332 * @param $warnings Array
333 * @return boolean true if warnings were displayed, false if there are no
334 * warnings and the should continue processing like there was no warning
336 protected function showUploadWarning( $warnings ) {
337 # If there are no warnings, or warnings we can ignore, return early.
338 # mDestWarningAck is set when some javascript has shown the warning
339 # to the user. mForReUpload is set when the user clicks the "upload a
341 if ( !$warnings ||
( count( $warnings ) == 1 &&
342 isset( $warnings['exists'] ) &&
343 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
348 $sessionKey = $this->mUpload
->stashSession();
350 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
351 . '<ul class="warning">';
352 foreach( $warnings as $warning => $args ) {
353 if( $warning == 'exists' ) {
354 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
355 } elseif( $warning == 'duplicate' ) {
356 $msg = self
::getDupeWarning( $args );
357 } elseif( $warning == 'duplicate-archive' ) {
358 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
359 array( Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() ) )
362 if ( $args === true ) {
364 } elseif ( !is_array( $args ) ) {
365 $args = array( $args );
367 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
369 $warningHtml .= $msg;
371 $warningHtml .= "</ul>\n";
372 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
374 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
375 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
376 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
377 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
379 $this->showUploadForm( $form );
381 # Indicate that we showed a form
386 * Show the upload form with error message, but do not stash the file.
388 * @param $message HTML string
390 protected function showUploadError( $message ) {
391 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
392 '<div class="error">' . $message . "</div>\n";
393 $this->showUploadForm( $this->getUploadForm( $message ) );
398 * Checks are made in SpecialUpload::execute()
400 protected function processUpload() {
401 // Fetch the file if required
402 $status = $this->mUpload
->fetchFile();
403 if( !$status->isOK() ) {
404 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
408 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
409 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
410 // This code path is deprecated. If you want to break upload processing
411 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
412 // and UploadBase::verifyFile.
413 // If you use this hook to break uploading, the user will be returned
414 // an empty form with no error message whatsoever.
418 // Upload verification
419 $details = $this->mUpload
->verifyUpload();
420 if ( $details['status'] != UploadBase
::OK
) {
421 $this->processVerificationError( $details );
425 // Verify permissions for this title
426 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
427 if( $permErrors !== true ) {
428 $code = array_shift( $permErrors[0] );
429 $this->showRecoverableUploadError( wfMsgExt( $code,
430 'parseinline', $permErrors[0] ) );
434 $this->mLocalFile
= $this->mUpload
->getLocalFile();
436 // Check warnings if necessary
437 if( !$this->mIgnoreWarning
) {
438 $warnings = $this->mUpload
->checkWarnings();
439 if( $this->showUploadWarning( $warnings ) ) {
444 // Get the page text if this is not a reupload
445 if( !$this->mForReUpload
) {
446 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
447 $this->mCopyrightStatus
, $this->mCopyrightSource
);
451 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $this->getUser() );
452 if ( !$status->isGood() ) {
453 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
457 // Success, redirect to description page
458 $this->mUploadSuccessful
= true;
459 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
460 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
464 * Get the initial image page text based on a comment and optional file status information
466 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
467 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
468 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
470 /* These messages are transcluded into the actual text of the description page.
471 * Thus, forcing them as content messages makes the upload to produce an int: template
472 * instead of hardcoding it there in the uploader language.
474 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
475 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
476 $msg[$msgName] = "{{int:$msgName}}";
478 $msg[$msgName] = wfMsgForContent( $msgName );
482 if ( $wgUseCopyrightUpload ) {
484 if ( $license != '' ) {
485 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
487 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
488 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
490 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
492 if ( $license != '' ) {
493 $filedesc = $comment == '' ?
'' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
494 $pageText = $filedesc .
495 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
497 $pageText = $comment;
504 * See if we should check the 'watch this page' checkbox on the form
505 * based on the user's preferences and whether we're being asked
506 * to create a new file or update an existing one.
508 * In the case where 'watch edits' is off but 'watch creations' is on,
509 * we'll leave the box unchecked.
511 * Note that the page target can be changed *on the form*, so our check
512 * state can get out of sync.
514 protected function getWatchCheck() {
515 if( $this->getUser()->getOption( 'watchdefault' ) ) {
520 $local = wfLocalFile( $this->mDesiredDestName
);
521 if( $local && $local->exists() ) {
522 // We're uploading a new version of an existing file.
523 // No creation, so don't watch it if we're not already.
524 return $local->getTitle()->userIsWatching();
526 // New page should get watched if that's our option.
527 return $this->getUser()->getOption( 'watchcreations' );
533 * Provides output to the user for a result of UploadBase::verifyUpload
535 * @param $details Array: result of UploadBase::verifyUpload
537 protected function processVerificationError( $details ) {
538 global $wgFileExtensions;
540 switch( $details['status'] ) {
542 /** Statuses that only require name changing **/
543 case UploadBase
::MIN_LENGTH_PARTNAME
:
544 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
546 case UploadBase
::ILLEGAL_FILENAME
:
547 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
548 'parseinline', $details['filtered'] ) );
550 case UploadBase
::FILENAME_TOO_LONG
:
551 $this->showRecoverableUploadError( wfMsgHtml( 'filename-toolong' ) );
553 case UploadBase
::FILETYPE_MISSING
:
554 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
557 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
558 $this->showRecoverableUploadError( wfMsgExt( 'windows-nonascii-filename',
562 /** Statuses that require reuploading **/
563 case UploadBase
::EMPTY_FILE
:
564 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
566 case UploadBase
::FILE_TOO_LARGE
:
567 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
569 case UploadBase
::FILETYPE_BADTYPE
:
570 $msg = wfMessage( 'filetype-banned-type' );
571 if ( isset( $details['blacklistedExt'] ) ) {
572 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
574 $msg->params( $details['finalExt'] );
576 $msg->params( $this->getLanguage()->commaList( $wgFileExtensions ),
577 count( $wgFileExtensions ) );
579 // Add PLURAL support for the first parameter. This results
580 // in a bit unlogical parameter sequence, but does not break
582 if ( isset( $details['blacklistedExt'] ) ) {
583 $msg->params( count( $details['blacklistedExt'] ) );
588 $this->showUploadError( $msg->parse() );
590 case UploadBase
::VERIFICATION_ERROR
:
591 unset( $details['status'] );
592 $code = array_shift( $details['details'] );
593 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
595 case UploadBase
::HOOK_ABORTED
:
596 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
597 $args = $details['error'];
598 $error = array_shift( $args );
600 $error = $details['error'];
604 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
607 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
612 * Remove a temporarily kept file stashed by saveTempUploadedFile().
614 * @return Boolean: success
616 protected function unsaveUploadedFile() {
617 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
620 $success = $this->mUpload
->unsaveUploadedFile();
622 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
629 /*** Functions for formatting warnings ***/
632 * Formats a result of UploadBase::getExistsWarning as HTML
633 * This check is static and can be done pre-upload via AJAX
635 * @param $exists Array: the result of UploadBase::getExistsWarning
636 * @return String: empty string if there is no warning or an HTML fragment
638 public static function getExistsWarning( $exists ) {
643 $file = $exists['file'];
644 $filename = $file->getTitle()->getPrefixedText();
647 if( $exists['warning'] == 'exists' ) {
649 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
650 } elseif( $exists['warning'] == 'page-exists' ) {
651 // Page exists but file does not
652 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
653 } elseif ( $exists['warning'] == 'exists-normalized' ) {
654 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
655 $exists['normalizedFile']->getTitle()->getPrefixedText() );
656 } elseif ( $exists['warning'] == 'thumb' ) {
657 // Swapped argument order compared with other messages for backwards compatibility
658 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
659 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
660 } elseif ( $exists['warning'] == 'thumb-name' ) {
661 // Image w/o '180px-' does not exists, but we do not like these filenames
662 $name = $file->getName();
663 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
664 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
665 } elseif ( $exists['warning'] == 'bad-prefix' ) {
666 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
667 } elseif ( $exists['warning'] == 'was-deleted' ) {
668 # If the file existed before and was deleted, warn the user of this
669 $ltitle = SpecialPage
::getTitleFor( 'Log' );
670 $llink = Linker
::linkKnown(
672 wfMsgHtml( 'deletionlog' ),
679 $warning = wfMsgExt( 'filewasdeleted', array( 'parse', 'replaceafter' ), $llink );
686 * Get a list of warnings
688 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
689 * @return Array: list of warning messages
691 public static function ajaxGetExistsWarning( $filename ) {
692 $file = wfFindFile( $filename );
694 // Force local file so we have an object to do further checks against
695 // if there isn't an exact match...
696 $file = wfLocalFile( $filename );
700 $exists = UploadBase
::getExistsWarning( $file );
701 $warning = self
::getExistsWarning( $exists );
702 if ( $warning !== '' ) {
703 $s = "<div>$warning</div>";
710 * Construct a warning and a gallery from an array of duplicate files.
712 public static function getDupeWarning( $dupes ) {
716 foreach( $dupes as $file ) {
717 $title = $file->getTitle();
718 $msg .= $title->getPrefixedText() .
719 '|' . $title->getText() . "\n";
721 $msg .= '</gallery>';
723 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
724 $wgOut->parse( $msg ) .
734 * Sub class of HTMLForm that provides the form section of SpecialUpload
736 class UploadForm
extends HTMLForm
{
738 protected $mForReUpload;
739 protected $mSessionKey;
740 protected $mHideIgnoreWarning;
741 protected $mDestWarningAck;
742 protected $mDestFile;
746 protected $mTextAfterSummary;
748 protected $mSourceIds;
750 protected $mMaxFileSize = array();
752 public function __construct( array $options = array(), IContextSource
$context = null ) {
753 $this->mWatch
= !empty( $options['watch'] );
754 $this->mForReUpload
= !empty( $options['forreupload'] );
755 $this->mSessionKey
= isset( $options['sessionkey'] )
756 ?
$options['sessionkey'] : '';
757 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
758 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
759 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
761 $this->mComment
= isset( $options['description'] ) ?
762 $options['description'] : '';
764 $this->mTextTop
= isset( $options['texttop'] )
765 ?
$options['texttop'] : '';
767 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
768 ?
$options['textaftersummary'] : '';
770 $sourceDescriptor = $this->getSourceSection();
771 $descriptor = $sourceDescriptor
772 +
$this->getDescriptionSection()
773 +
$this->getOptionsSection();
775 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
776 parent
::__construct( $descriptor, $context, 'upload' );
778 # Set some form properties
779 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
780 $this->setSubmitName( 'wpUpload' );
781 # Used message keys: 'accesskey-upload', 'tooltip-upload'
782 $this->setSubmitTooltip( 'upload' );
783 $this->setId( 'mw-upload-form' );
785 # Build a list of IDs for javascript insertion
786 $this->mSourceIds
= array();
787 foreach ( $sourceDescriptor as $field ) {
788 if ( !empty( $field['id'] ) ) {
789 $this->mSourceIds
[] = $field['id'];
796 * Get the descriptor of the fieldset that contains the file source
797 * selection. The section is 'source'
799 * @return Array: descriptor array
801 protected function getSourceSection() {
802 if ( $this->mSessionKey
) {
804 'SessionKey' => array(
806 'default' => $this->mSessionKey
,
808 'SourceType' => array(
810 'default' => 'Stash',
815 $canUploadByUrl = UploadFromUrl
::isEnabled() && $this->getUser()->isAllowed( 'upload_by_url' );
816 $radio = $canUploadByUrl;
817 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
819 $descriptor = array();
820 if ( $this->mTextTop
) {
821 $descriptor['UploadFormTextTop'] = array(
823 'section' => 'source',
824 'default' => $this->mTextTop
,
829 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
830 # Limit to upload_max_filesize unless we are running under HipHop and
831 # that setting doesn't exist
832 if ( !wfIsHipHop() ) {
833 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
834 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ) );
837 $descriptor['UploadFile'] = array(
838 'class' => 'UploadSourceField',
839 'section' => 'source',
841 'id' => 'wpUploadFile',
842 'label-message' => 'sourcefilename',
843 'upload-type' => 'File',
845 'help' => wfMsgExt( 'upload-maxfilesize',
846 array( 'parseinline', 'escapenoentities' ),
847 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
848 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
849 'checked' => $selectedSourceType == 'file',
851 if ( $canUploadByUrl ) {
852 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
853 $descriptor['UploadFileURL'] = array(
854 'class' => 'UploadSourceField',
855 'section' => 'source',
856 'id' => 'wpUploadFileURL',
857 'label-message' => 'sourceurl',
858 'upload-type' => 'url',
860 'help' => wfMsgExt( 'upload-maxfilesize',
861 array( 'parseinline', 'escapenoentities' ),
862 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
863 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
864 'checked' => $selectedSourceType == 'url',
867 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
869 $descriptor['Extensions'] = array(
871 'section' => 'source',
872 'default' => $this->getExtensionsMessage(),
879 * Get the messages indicating which extensions are preferred and prohibitted.
881 * @return String: HTML string containing the message
883 protected function getExtensionsMessage() {
884 # Print a list of allowed file extensions, if so configured. We ignore
885 # MIME type here, it's incomprehensible to most people and too long.
886 global $wgCheckFileExtensions, $wgStrictFileExtensions,
887 $wgFileExtensions, $wgFileBlacklist;
889 if( $wgCheckFileExtensions ) {
890 if( $wgStrictFileExtensions ) {
891 # Everything not permitted is banned
893 '<div id="mw-upload-permitted">' .
894 wfMsgExt( 'upload-permitted', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) ) .
897 # We have to list both preferred and prohibited
899 '<div id="mw-upload-preferred">' .
900 wfMsgExt( 'upload-preferred', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) ) .
902 '<div id="mw-upload-prohibited">' .
903 wfMsgExt( 'upload-prohibited', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileBlacklist ) ) .
907 # Everything is permitted.
908 $extensionsList = '';
910 return $extensionsList;
914 * Get the descriptor of the fieldset that contains the file description
915 * input. The section is 'description'
917 * @return Array: descriptor array
919 protected function getDescriptionSection() {
920 if ( $this->mSessionKey
) {
921 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
923 $file = $stash->getFile( $this->mSessionKey
);
924 } catch ( MWException
$e ) {
930 $mto = $file->transform( array( 'width' => 120 ) );
931 $this->addHeaderText(
932 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
933 Html
::element( 'img', array(
934 'src' => $mto->getUrl(),
935 'class' => 'thumbimage',
936 ) ) . '</div>', 'description' );
943 'section' => 'description',
944 'id' => 'wpDestFile',
945 'label-message' => 'destfilename',
947 'default' => $this->mDestFile
,
948 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
949 'nodata' => strval( $this->mDestFile
) !== '',
951 'UploadDescription' => array(
952 'type' => 'textarea',
953 'section' => 'description',
954 'id' => 'wpUploadDescription',
955 'label-message' => $this->mForReUpload
956 ?
'filereuploadsummary'
957 : 'fileuploadsummary',
958 'default' => $this->mComment
,
962 if ( $this->mTextAfterSummary
) {
963 $descriptor['UploadFormTextAfterSummary'] = array(
965 'section' => 'description',
966 'default' => $this->mTextAfterSummary
,
971 $descriptor +
= array(
972 'EditTools' => array(
973 'type' => 'edittools',
974 'section' => 'description',
975 'message' => 'edittools-upload',
979 if ( $this->mForReUpload
) {
980 $descriptor['DestFile']['readonly'] = true;
982 $descriptor['License'] = array(
984 'class' => 'Licenses',
985 'section' => 'description',
987 'label-message' => 'license',
991 global $wgUseCopyrightUpload;
992 if ( $wgUseCopyrightUpload ) {
993 $descriptor['UploadCopyStatus'] = array(
995 'section' => 'description',
996 'id' => 'wpUploadCopyStatus',
997 'label-message' => 'filestatus',
999 $descriptor['UploadSource'] = array(
1001 'section' => 'description',
1002 'id' => 'wpUploadSource',
1003 'label-message' => 'filesource',
1011 * Get the descriptor of the fieldset that contains the upload options,
1012 * such as "watch this file". The section is 'options'
1014 * @return Array: descriptor array
1016 protected function getOptionsSection() {
1017 $user = $this->getUser();
1018 if ( $user->isLoggedIn() ) {
1019 $descriptor = array(
1020 'Watchthis' => array(
1022 'id' => 'wpWatchthis',
1023 'label-message' => 'watchthisupload',
1024 'section' => 'options',
1025 'default' => $user->getOption( 'watchcreations' ),
1029 if ( !$this->mHideIgnoreWarning
) {
1030 $descriptor['IgnoreWarning'] = array(
1032 'id' => 'wpIgnoreWarning',
1033 'label-message' => 'ignorewarnings',
1034 'section' => 'options',
1038 $descriptor['DestFileWarningAck'] = array(
1040 'id' => 'wpDestFileWarningAck',
1041 'default' => $this->mDestWarningAck ?
'1' : '',
1044 if ( $this->mForReUpload
) {
1045 $descriptor['ForReUpload'] = array(
1047 'id' => 'wpForReUpload',
1056 * Add the upload JS and show the form.
1058 public function show() {
1059 $this->addUploadJS();
1064 * Add upload JS to the OutputPage
1066 protected function addUploadJS() {
1067 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1069 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1070 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1071 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1073 $scriptVars = array(
1074 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1075 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1076 'wgUploadAutoFill' => !$this->mForReUpload
&&
1077 // If we received mDestFile from the request, don't autofill
1078 // the wpDestFile textbox
1079 $this->mDestFile
=== '',
1080 'wgUploadSourceIds' => $this->mSourceIds
,
1081 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1082 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1083 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1086 $out = $this->getOutput();
1087 $out->addJsConfigVars( $scriptVars );
1090 $out->addModules( array(
1091 'mediawiki.action.edit', // For <charinsert> support
1092 'mediawiki.legacy.upload', // Old form stuff...
1093 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1098 * Empty function; submission is handled elsewhere.
1100 * @return bool false
1102 function trySubmit() {
1109 * A form field that contains a radio box in the label
1111 class UploadSourceField
extends HTMLTextField
{
1112 function getLabelHtml( $cellAttributes = array() ) {
1113 $id = "wpSourceType{$this->mParams['upload-type']}";
1114 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1116 if ( !empty( $this->mParams
['radio'] ) ) {
1118 'name' => 'wpSourceType',
1121 'value' => $this->mParams
['upload-type'],
1123 if ( !empty( $this->mParams
['checked'] ) ) {
1124 $attribs['checked'] = 'checked';
1126 $label .= Html
::element( 'input', $attribs );
1129 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1132 function getSize() {
1133 return isset( $this->mParams
['size'] )
1134 ?
$this->mParams
['size']