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
165 throw new ReadOnlyError
;
168 $this->loadRequest();
170 # Unsave the temporary file in case this was a cancelled upload
171 if ( $this->mCancelUpload
) {
172 if ( !$this->unsaveUploadedFile() ) {
173 # Something went wrong, so unsaveUploadedFile showed a warning
178 # Process upload or show a form
180 $this->mTokenOk
&& !$this->mCancelUpload
&&
181 ( $this->mUpload
&& $this->mUploadClicked
)
184 $this->processUpload();
186 # Backwards compatibility hook
187 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
188 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
193 $this->showUploadForm( $this->getUploadForm() );
197 if ( $this->mUpload
) {
198 $this->mUpload
->cleanupTempFile();
203 * Show the main upload form
205 * @param $form Mixed: an HTMLForm instance or HTML string to show
207 protected function showUploadForm( $form ) {
208 # Add links if file was previously deleted
209 if ( $this->mDesiredDestName
) {
210 $this->showViewDeletedLinks();
213 if ( $form instanceof HTMLForm
) {
216 $this->getOutput()->addHTML( $form );
222 * Get an UploadForm instance with title and text properly set.
224 * @param $message String: HTML string to add to the form
225 * @param $sessionKey String: session key in case this is a stashed upload
226 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
229 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
231 $form = new UploadForm( array(
232 'watch' => $this->getWatchCheck(),
233 'forreupload' => $this->mForReUpload
,
234 'sessionkey' => $sessionKey,
235 'hideignorewarning' => $hideIgnoreWarning,
236 'destwarningack' => (bool)$this->mDestWarningAck
,
238 'description' => $this->mComment
,
239 'texttop' => $this->uploadFormTextTop
,
240 'textaftersummary' => $this->uploadFormTextAfterSummary
,
241 'destfile' => $this->mDesiredDestName
,
242 ), $this->getContext() );
243 $form->setTitle( $this->getTitle() );
245 # Check the token, but only if necessary
247 !$this->mTokenOk
&& !$this->mCancelUpload
&&
248 ( $this->mUpload
&& $this->mUploadClicked
)
251 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
254 # Give a notice if the user is uploading a file that has been deleted or moved
255 # Note that this is independent from the message 'filewasdeleted' that requires JS
256 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
257 $delNotice = ''; // empty by default
258 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
259 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
261 '', array( 'lim' => 10,
262 'conds' => array( "log_action != 'revision'" ),
263 'showIfEmpty' => false,
264 'msgKey' => array( 'upload-recreate-warning' ) )
267 $form->addPreText( $delNotice );
270 $form->addPreText( '<div id="uploadtext">' .
271 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName
) ) .
273 # Add upload error message
274 $form->addPreText( $message );
277 $uploadFooter = wfMessage( 'uploadfooter' );
278 if ( !$uploadFooter->isDisabled() ) {
279 $form->addPostText( '<div id="mw-upload-footer-message">'
280 . $this->getOutput()->parse( $uploadFooter->plain() ) . "</div>\n" );
288 * Shows the "view X deleted revivions link""
290 protected function showViewDeletedLinks() {
291 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
292 $user = $this->getUser();
293 // Show a subtitle link to deleted revisions (to sysops et al only)
294 if( $title instanceof Title
) {
295 $count = $title->isDeleted();
296 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
298 $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
299 array( 'parse', 'replaceafter' ),
301 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
302 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
305 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
311 * Stashes the upload and shows the main upload form.
313 * Note: only errors that can be handled by changing the name or
314 * description should be redirected here. It should be assumed that the
315 * file itself is sane and has passed UploadBase::verifyFile. This
316 * essentially means that UploadBase::VERIFICATION_ERROR and
317 * UploadBase::EMPTY_FILE should not be passed here.
319 * @param $message String: HTML message to be passed to mainUploadForm
321 protected function showRecoverableUploadError( $message ) {
322 $sessionKey = $this->mUpload
->stashSession();
323 $message = '<h2>' . wfMsgHtml( 'uploaderror' ) . "</h2>\n" .
324 '<div class="error">' . $message . "</div>\n";
326 $form = $this->getUploadForm( $message, $sessionKey );
327 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
328 $this->showUploadForm( $form );
331 * Stashes the upload, shows the main form, but adds an "continue anyway button".
332 * Also checks whether there are actually warnings to display.
334 * @param $warnings Array
335 * @return boolean true if warnings were displayed, false if there are no
336 * warnings and the should continue processing like there was no warning
338 protected function showUploadWarning( $warnings ) {
339 # If there are no warnings, or warnings we can ignore, return early.
340 # mDestWarningAck is set when some javascript has shown the warning
341 # to the user. mForReUpload is set when the user clicks the "upload a
343 if ( !$warnings ||
( count( $warnings ) == 1 &&
344 isset( $warnings['exists'] ) &&
345 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
350 $sessionKey = $this->mUpload
->stashSession();
352 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
353 . '<ul class="warning">';
354 foreach( $warnings as $warning => $args ) {
355 if( $warning == 'exists' ) {
356 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
357 } elseif( $warning == 'duplicate' ) {
358 $msg = self
::getDupeWarning( $args );
359 } elseif( $warning == 'duplicate-archive' ) {
360 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
361 array( Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() ) )
364 if ( $args === true ) {
366 } elseif ( !is_array( $args ) ) {
367 $args = array( $args );
369 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
371 $warningHtml .= $msg;
373 $warningHtml .= "</ul>\n";
374 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
376 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
377 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
378 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
379 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
381 $this->showUploadForm( $form );
383 # Indicate that we showed a form
388 * Show the upload form with error message, but do not stash the file.
390 * @param $message HTML string
392 protected function showUploadError( $message ) {
393 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
394 '<div class="error">' . $message . "</div>\n";
395 $this->showUploadForm( $this->getUploadForm( $message ) );
400 * Checks are made in SpecialUpload::execute()
402 protected function processUpload() {
403 // Fetch the file if required
404 $status = $this->mUpload
->fetchFile();
405 if( !$status->isOK() ) {
406 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
410 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
411 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
412 // This code path is deprecated. If you want to break upload processing
413 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
414 // and UploadBase::verifyFile.
415 // If you use this hook to break uploading, the user will be returned
416 // an empty form with no error message whatsoever.
420 // Upload verification
421 $details = $this->mUpload
->verifyUpload();
422 if ( $details['status'] != UploadBase
::OK
) {
423 $this->processVerificationError( $details );
427 // Verify permissions for this title
428 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
429 if( $permErrors !== true ) {
430 $code = array_shift( $permErrors[0] );
431 $this->showRecoverableUploadError( wfMsgExt( $code,
432 'parseinline', $permErrors[0] ) );
436 $this->mLocalFile
= $this->mUpload
->getLocalFile();
438 // Check warnings if necessary
439 if( !$this->mIgnoreWarning
) {
440 $warnings = $this->mUpload
->checkWarnings();
441 if( $this->showUploadWarning( $warnings ) ) {
446 // Get the page text if this is not a reupload
447 if( !$this->mForReUpload
) {
448 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
449 $this->mCopyrightStatus
, $this->mCopyrightSource
);
453 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $this->getUser() );
454 if ( !$status->isGood() ) {
455 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
459 // Success, redirect to description page
460 $this->mUploadSuccessful
= true;
461 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
462 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
466 * Get the initial image page text based on a comment and optional file status information
468 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
469 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
470 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
472 /* These messages are transcluded into the actual text of the description page.
473 * Thus, forcing them as content messages makes the upload to produce an int: template
474 * instead of hardcoding it there in the uploader language.
476 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
477 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
478 $msg[$msgName] = "{{int:$msgName}}";
480 $msg[$msgName] = wfMsgForContent( $msgName );
484 if ( $wgUseCopyrightUpload ) {
486 if ( $license != '' ) {
487 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
489 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
490 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
492 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
494 if ( $license != '' ) {
495 $filedesc = $comment == '' ?
'' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
496 $pageText = $filedesc .
497 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
499 $pageText = $comment;
506 * See if we should check the 'watch this page' checkbox on the form
507 * based on the user's preferences and whether we're being asked
508 * to create a new file or update an existing one.
510 * In the case where 'watch edits' is off but 'watch creations' is on,
511 * we'll leave the box unchecked.
513 * Note that the page target can be changed *on the form*, so our check
514 * state can get out of sync.
516 protected function getWatchCheck() {
517 if( $this->getUser()->getOption( 'watchdefault' ) ) {
522 $local = wfLocalFile( $this->mDesiredDestName
);
523 if( $local && $local->exists() ) {
524 // We're uploading a new version of an existing file.
525 // No creation, so don't watch it if we're not already.
526 return $local->getTitle()->userIsWatching();
528 // New page should get watched if that's our option.
529 return $this->getUser()->getOption( 'watchcreations' );
535 * Provides output to the user for a result of UploadBase::verifyUpload
537 * @param $details Array: result of UploadBase::verifyUpload
539 protected function processVerificationError( $details ) {
540 global $wgFileExtensions;
542 switch( $details['status'] ) {
544 /** Statuses that only require name changing **/
545 case UploadBase
::MIN_LENGTH_PARTNAME
:
546 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
548 case UploadBase
::ILLEGAL_FILENAME
:
549 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
550 'parseinline', $details['filtered'] ) );
552 case UploadBase
::FILENAME_TOO_LONG
:
553 $this->showRecoverableUploadError( wfMsgHtml( 'filename-toolong' ) );
555 case UploadBase
::FILETYPE_MISSING
:
556 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
559 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
560 $this->showRecoverableUploadError( wfMsgExt( 'windows-nonascii-filename',
564 /** Statuses that require reuploading **/
565 case UploadBase
::EMPTY_FILE
:
566 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
568 case UploadBase
::FILE_TOO_LARGE
:
569 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
571 case UploadBase
::FILETYPE_BADTYPE
:
572 $msg = wfMessage( 'filetype-banned-type' );
573 if ( isset( $details['blacklistedExt'] ) ) {
574 $msg->params( $this->getLang()->commaList( $details['blacklistedExt'] ) );
576 $msg->params( $details['finalExt'] );
578 $msg->params( $this->getLang()->commaList( $wgFileExtensions ),
579 count( $wgFileExtensions ) );
581 // Add PLURAL support for the first parameter. This results
582 // in a bit unlogical parameter sequence, but does not break
584 if ( isset( $details['blacklistedExt'] ) ) {
585 $msg->params( count( $details['blacklistedExt'] ) );
590 $this->showUploadError( $msg->parse() );
592 case UploadBase
::VERIFICATION_ERROR
:
593 unset( $details['status'] );
594 $code = array_shift( $details['details'] );
595 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
597 case UploadBase
::HOOK_ABORTED
:
598 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
599 $args = $details['error'];
600 $error = array_shift( $args );
602 $error = $details['error'];
606 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
609 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
614 * Remove a temporarily kept file stashed by saveTempUploadedFile().
616 * @return Boolean: success
618 protected function unsaveUploadedFile() {
619 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
622 $success = $this->mUpload
->unsaveUploadedFile();
624 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
631 /*** Functions for formatting warnings ***/
634 * Formats a result of UploadBase::getExistsWarning as HTML
635 * This check is static and can be done pre-upload via AJAX
637 * @param $exists Array: the result of UploadBase::getExistsWarning
638 * @return String: empty string if there is no warning or an HTML fragment
640 public static function getExistsWarning( $exists ) {
645 $file = $exists['file'];
646 $filename = $file->getTitle()->getPrefixedText();
649 if( $exists['warning'] == 'exists' ) {
651 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
652 } elseif( $exists['warning'] == 'page-exists' ) {
653 // Page exists but file does not
654 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
655 } elseif ( $exists['warning'] == 'exists-normalized' ) {
656 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
657 $exists['normalizedFile']->getTitle()->getPrefixedText() );
658 } elseif ( $exists['warning'] == 'thumb' ) {
659 // Swapped argument order compared with other messages for backwards compatibility
660 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
661 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
662 } elseif ( $exists['warning'] == 'thumb-name' ) {
663 // Image w/o '180px-' does not exists, but we do not like these filenames
664 $name = $file->getName();
665 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
666 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
667 } elseif ( $exists['warning'] == 'bad-prefix' ) {
668 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
669 } elseif ( $exists['warning'] == 'was-deleted' ) {
670 # If the file existed before and was deleted, warn the user of this
671 $ltitle = SpecialPage
::getTitleFor( 'Log' );
672 $llink = Linker
::linkKnown(
674 wfMsgHtml( 'deletionlog' ),
681 $warning = wfMsgExt( 'filewasdeleted', array( 'parse', 'replaceafter' ), $llink );
688 * Get a list of warnings
690 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
691 * @return Array: list of warning messages
693 public static function ajaxGetExistsWarning( $filename ) {
694 $file = wfFindFile( $filename );
696 // Force local file so we have an object to do further checks against
697 // if there isn't an exact match...
698 $file = wfLocalFile( $filename );
702 $exists = UploadBase
::getExistsWarning( $file );
703 $warning = self
::getExistsWarning( $exists );
704 if ( $warning !== '' ) {
705 $s = "<div>$warning</div>";
712 * Construct a warning and a gallery from an array of duplicate files.
714 public static function getDupeWarning( $dupes ) {
718 foreach( $dupes as $file ) {
719 $title = $file->getTitle();
720 $msg .= $title->getPrefixedText() .
721 '|' . $title->getText() . "\n";
723 $msg .= '</gallery>';
725 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
726 $wgOut->parse( $msg ) .
736 * Sub class of HTMLForm that provides the form section of SpecialUpload
738 class UploadForm
extends HTMLForm
{
740 protected $mForReUpload;
741 protected $mSessionKey;
742 protected $mHideIgnoreWarning;
743 protected $mDestWarningAck;
744 protected $mDestFile;
748 protected $mTextAfterSummary;
750 protected $mSourceIds;
752 protected $mMaxFileSize = array();
754 public function __construct( array $options = array(), IContextSource
$context = null ) {
755 $this->mWatch
= !empty( $options['watch'] );
756 $this->mForReUpload
= !empty( $options['forreupload'] );
757 $this->mSessionKey
= isset( $options['sessionkey'] )
758 ?
$options['sessionkey'] : '';
759 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
760 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
761 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
763 $this->mComment
= isset( $options['description'] ) ?
764 $options['description'] : '';
766 $this->mTextTop
= isset( $options['texttop'] )
767 ?
$options['texttop'] : '';
769 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
770 ?
$options['textaftersummary'] : '';
772 $sourceDescriptor = $this->getSourceSection();
773 $descriptor = $sourceDescriptor
774 +
$this->getDescriptionSection()
775 +
$this->getOptionsSection();
777 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
778 parent
::__construct( $descriptor, $context, 'upload' );
780 # Set some form properties
781 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
782 $this->setSubmitName( 'wpUpload' );
783 # Used message keys: 'accesskey-upload', 'tooltip-upload'
784 $this->setSubmitTooltip( 'upload' );
785 $this->setId( 'mw-upload-form' );
787 # Build a list of IDs for javascript insertion
788 $this->mSourceIds
= array();
789 foreach ( $sourceDescriptor as $field ) {
790 if ( !empty( $field['id'] ) ) {
791 $this->mSourceIds
[] = $field['id'];
798 * Get the descriptor of the fieldset that contains the file source
799 * selection. The section is 'source'
801 * @return Array: descriptor array
803 protected function getSourceSection() {
804 if ( $this->mSessionKey
) {
806 'SessionKey' => array(
808 'default' => $this->mSessionKey
,
810 'SourceType' => array(
812 'default' => 'Stash',
817 $canUploadByUrl = UploadFromUrl
::isEnabled() && $this->getUser()->isAllowed( 'upload_by_url' );
818 $radio = $canUploadByUrl;
819 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
821 $descriptor = array();
822 if ( $this->mTextTop
) {
823 $descriptor['UploadFormTextTop'] = array(
825 'section' => 'source',
826 'default' => $this->mTextTop
,
831 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
832 # Limit to upload_max_filesize unless we are running under HipHop and
833 # that setting doesn't exist
834 if ( !wfIsHipHop() ) {
835 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
836 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ) );
839 $descriptor['UploadFile'] = array(
840 'class' => 'UploadSourceField',
841 'section' => 'source',
843 'id' => 'wpUploadFile',
844 'label-message' => 'sourcefilename',
845 'upload-type' => 'File',
847 'help' => wfMsgExt( 'upload-maxfilesize',
848 array( 'parseinline', 'escapenoentities' ),
849 $this->getContext()->getLang()->formatSize( $this->mMaxUploadSize
['file'] )
850 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
851 'checked' => $selectedSourceType == 'file',
853 if ( $canUploadByUrl ) {
854 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
855 $descriptor['UploadFileURL'] = array(
856 'class' => 'UploadSourceField',
857 'section' => 'source',
858 'id' => 'wpUploadFileURL',
859 'label-message' => 'sourceurl',
860 'upload-type' => 'url',
862 'help' => wfMsgExt( 'upload-maxfilesize',
863 array( 'parseinline', 'escapenoentities' ),
864 $this->getContext()->getLang()->formatSize( $this->mMaxUploadSize
['url'] )
865 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
866 'checked' => $selectedSourceType == 'url',
869 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
871 $descriptor['Extensions'] = array(
873 'section' => 'source',
874 'default' => $this->getExtensionsMessage(),
881 * Get the messages indicating which extensions are preferred and prohibitted.
883 * @return String: HTML string containing the message
885 protected function getExtensionsMessage() {
886 # Print a list of allowed file extensions, if so configured. We ignore
887 # MIME type here, it's incomprehensible to most people and too long.
888 global $wgCheckFileExtensions, $wgStrictFileExtensions,
889 $wgFileExtensions, $wgFileBlacklist;
891 if( $wgCheckFileExtensions ) {
892 if( $wgStrictFileExtensions ) {
893 # Everything not permitted is banned
895 '<div id="mw-upload-permitted">' .
896 wfMsgExt( 'upload-permitted', 'parse', $this->getContext()->getLang()->commaList( $wgFileExtensions ) ) .
899 # We have to list both preferred and prohibited
901 '<div id="mw-upload-preferred">' .
902 wfMsgExt( 'upload-preferred', 'parse', $this->getContext()->getLang()->commaList( $wgFileExtensions ) ) .
904 '<div id="mw-upload-prohibited">' .
905 wfMsgExt( 'upload-prohibited', 'parse', $this->getContext()->getLang()->commaList( $wgFileBlacklist ) ) .
909 # Everything is permitted.
910 $extensionsList = '';
912 return $extensionsList;
916 * Get the descriptor of the fieldset that contains the file description
917 * input. The section is 'description'
919 * @return Array: descriptor array
921 protected function getDescriptionSection() {
922 if ( $this->mSessionKey
) {
923 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
925 $file = $stash->getFile( $this->mSessionKey
);
926 } catch ( MWException
$e ) {
932 $mto = $file->transform( array( 'width' => 120 ) );
933 $this->addHeaderText(
934 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
935 Html
::element( 'img', array(
936 'src' => $mto->getUrl(),
937 'class' => 'thumbimage',
938 ) ) . '</div>', 'description' );
945 'section' => 'description',
946 'id' => 'wpDestFile',
947 'label-message' => 'destfilename',
949 'default' => $this->mDestFile
,
950 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
951 'nodata' => strval( $this->mDestFile
) !== '',
953 'UploadDescription' => array(
954 'type' => 'textarea',
955 'section' => 'description',
956 'id' => 'wpUploadDescription',
957 'label-message' => $this->mForReUpload
958 ?
'filereuploadsummary'
959 : 'fileuploadsummary',
960 'default' => $this->mComment
,
961 'cols' => intval( $this->getUser()->getOption( 'cols' ) ),
965 if ( $this->mTextAfterSummary
) {
966 $descriptor['UploadFormTextAfterSummary'] = array(
968 'section' => 'description',
969 'default' => $this->mTextAfterSummary
,
974 $descriptor +
= array(
975 'EditTools' => array(
976 'type' => 'edittools',
977 'section' => 'description',
978 'message' => 'edittools-upload',
982 if ( $this->mForReUpload
) {
983 $descriptor['DestFile']['readonly'] = true;
985 $descriptor['License'] = array(
987 'class' => 'Licenses',
988 'section' => 'description',
990 'label-message' => 'license',
994 global $wgUseCopyrightUpload;
995 if ( $wgUseCopyrightUpload ) {
996 $descriptor['UploadCopyStatus'] = array(
998 'section' => 'description',
999 'id' => 'wpUploadCopyStatus',
1000 'label-message' => 'filestatus',
1002 $descriptor['UploadSource'] = array(
1004 'section' => 'description',
1005 'id' => 'wpUploadSource',
1006 'label-message' => 'filesource',
1014 * Get the descriptor of the fieldset that contains the upload options,
1015 * such as "watch this file". The section is 'options'
1017 * @return Array: descriptor array
1019 protected function getOptionsSection() {
1020 $user = $this->getUser();
1021 if ( $user->isLoggedIn() ) {
1022 $descriptor = array(
1023 'Watchthis' => array(
1025 'id' => 'wpWatchthis',
1026 'label-message' => 'watchthisupload',
1027 'section' => 'options',
1028 'default' => $user->getOption( 'watchcreations' ),
1032 if ( !$this->mHideIgnoreWarning
) {
1033 $descriptor['IgnoreWarning'] = array(
1035 'id' => 'wpIgnoreWarning',
1036 'label-message' => 'ignorewarnings',
1037 'section' => 'options',
1041 $descriptor['DestFileWarningAck'] = array(
1043 'id' => 'wpDestFileWarningAck',
1044 'default' => $this->mDestWarningAck ?
'1' : '',
1047 if ( $this->mForReUpload
) {
1048 $descriptor['ForReUpload'] = array(
1050 'id' => 'wpForReUpload',
1059 * Add the upload JS and show the form.
1061 public function show() {
1062 $this->addUploadJS();
1067 * Add upload JS to the OutputPage
1069 protected function addUploadJS() {
1070 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1072 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1073 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1074 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1076 $scriptVars = array(
1077 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1078 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1079 'wgUploadAutoFill' => !$this->mForReUpload
&&
1080 // If we received mDestFile from the request, don't autofill
1081 // the wpDestFile textbox
1082 $this->mDestFile
=== '',
1083 'wgUploadSourceIds' => $this->mSourceIds
,
1084 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1085 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1086 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1089 $out = $this->getOutput();
1090 $out->addScript( Skin
::makeVariablesScript( $scriptVars ) );
1093 $out->addModules( array(
1094 'mediawiki.action.edit', // For <charinsert> support
1095 'mediawiki.legacy.upload', // Old form stuff...
1096 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1101 * Empty function; submission is handled elsewhere.
1103 * @return bool false
1105 function trySubmit() {
1112 * A form field that contains a radio box in the label
1114 class UploadSourceField
extends HTMLTextField
{
1115 function getLabelHtml( $cellAttributes = array() ) {
1116 $id = "wpSourceType{$this->mParams['upload-type']}";
1117 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1119 if ( !empty( $this->mParams
['radio'] ) ) {
1121 'name' => 'wpSourceType',
1124 'value' => $this->mParams
['upload-type'],
1126 if ( !empty( $this->mParams
['checked'] ) ) {
1127 $attribs['checked'] = 'checked';
1129 $label .= Html
::element( 'input', $attribs );
1132 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1135 function getSize() {
1136 return isset( $this->mParams
['size'] )
1137 ?
$this->mParams
['size']