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( $this->msg( 'session_fail_preview' )->parse() );
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 $this->msg( 'uploadtext', array( $this->mDesiredDestName
) )->parseAsBlock() .
260 # Add upload error message
261 $form->addPreText( $message );
264 $uploadFooter = $this->msg( 'uploadfooter' );
265 if ( !$uploadFooter->isDisabled() ) {
266 $form->addPostText( '<div id="mw-upload-footer-message">'
267 . $uploadFooter->parseAsBlock() . "</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' ) ) {
283 $restorelink = Linker
::linkKnown(
284 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
285 $this->msg( 'restorelink' )->numParams( $count )->escaped()
287 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
288 ->rawParams( $restorelink )->parseAsBlock();
289 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
295 * Stashes the upload and shows the main upload form.
297 * Note: only errors that can be handled by changing the name or
298 * description should be redirected here. It should be assumed that the
299 * file itself is sane and has passed UploadBase::verifyFile. This
300 * essentially means that UploadBase::VERIFICATION_ERROR and
301 * UploadBase::EMPTY_FILE should not be passed here.
303 * @param $message String: HTML message to be passed to mainUploadForm
305 protected function showRecoverableUploadError( $message ) {
306 $sessionKey = $this->mUpload
->stashSession();
307 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
308 '<div class="error">' . $message . "</div>\n";
310 $form = $this->getUploadForm( $message, $sessionKey );
311 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
312 $this->showUploadForm( $form );
315 * Stashes the upload, shows the main form, but adds an "continue anyway button".
316 * Also checks whether there are actually warnings to display.
318 * @param $warnings Array
319 * @return boolean true if warnings were displayed, false if there are no
320 * warnings and the should continue processing like there was no warning
322 protected function showUploadWarning( $warnings ) {
323 # If there are no warnings, or warnings we can ignore, return early.
324 # mDestWarningAck is set when some javascript has shown the warning
325 # to the user. mForReUpload is set when the user clicks the "upload a
327 if ( !$warnings ||
( count( $warnings ) == 1 &&
328 isset( $warnings['exists'] ) &&
329 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
334 $sessionKey = $this->mUpload
->stashSession();
336 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
337 . '<ul class="warning">';
338 foreach( $warnings as $warning => $args ) {
339 if( $warning == 'exists' ) {
340 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
341 } elseif( $warning == 'duplicate' ) {
342 $msg = self
::getDupeWarning( $args );
343 } elseif( $warning == 'duplicate-archive' ) {
344 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
345 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
348 if ( $args === true ) {
350 } elseif ( !is_array( $args ) ) {
351 $args = array( $args );
353 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
355 $warningHtml .= $msg;
357 $warningHtml .= "</ul>\n";
358 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
360 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
361 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
362 $form->addButton( 'wpUploadIgnoreWarning', $this->msg( 'ignorewarning' )->text() );
363 $form->addButton( 'wpCancelUpload', $this->msg( 'reuploaddesc' )->text() );
365 $this->showUploadForm( $form );
367 # Indicate that we showed a form
372 * Show the upload form with error message, but do not stash the file.
374 * @param $message string HTML string
376 protected function showUploadError( $message ) {
377 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
378 '<div class="error">' . $message . "</div>\n";
379 $this->showUploadForm( $this->getUploadForm( $message ) );
384 * Checks are made in SpecialUpload::execute()
386 protected function processUpload() {
387 // Fetch the file if required
388 $status = $this->mUpload
->fetchFile();
389 if( !$status->isOK() ) {
390 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
394 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
395 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
396 // This code path is deprecated. If you want to break upload processing
397 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
398 // and UploadBase::verifyFile.
399 // If you use this hook to break uploading, the user will be returned
400 // an empty form with no error message whatsoever.
404 // Upload verification
405 $details = $this->mUpload
->verifyUpload();
406 if ( $details['status'] != UploadBase
::OK
) {
407 $this->processVerificationError( $details );
411 // Verify permissions for this title
412 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
413 if( $permErrors !== true ) {
414 $code = array_shift( $permErrors[0] );
415 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
419 $this->mLocalFile
= $this->mUpload
->getLocalFile();
421 // Check warnings if necessary
422 if( !$this->mIgnoreWarning
) {
423 $warnings = $this->mUpload
->checkWarnings();
424 if( $this->showUploadWarning( $warnings ) ) {
429 // Get the page text if this is not a reupload
430 if( !$this->mForReUpload
) {
431 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
432 $this->mCopyrightStatus
, $this->mCopyrightSource
);
436 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $this->getUser() );
437 if ( !$status->isGood() ) {
438 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
442 // Success, redirect to description page
443 $this->mUploadSuccessful
= true;
444 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
445 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
449 * Get the initial image page text based on a comment and optional file status information
450 * @param $comment string
451 * @param $license string
452 * @param $copyStatus string
453 * @param $source string
456 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
457 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
458 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
461 /* These messages are transcluded into the actual text of the description page.
462 * Thus, forcing them as content messages makes the upload to produce an int: template
463 * instead of hardcoding it there in the uploader language.
465 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
466 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
467 $msg[$msgName] = "{{int:$msgName}}";
469 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
473 if ( $wgUseCopyrightUpload ) {
475 if ( $license != '' ) {
476 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
478 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
479 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
481 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
483 if ( $license != '' ) {
484 $filedesc = $comment == '' ?
'' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
485 $pageText = $filedesc .
486 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
488 $pageText = $comment;
495 * See if we should check the 'watch this page' checkbox on the form
496 * based on the user's preferences and whether we're being asked
497 * to create a new file or update an existing one.
499 * In the case where 'watch edits' is off but 'watch creations' is on,
500 * we'll leave the box unchecked.
502 * Note that the page target can be changed *on the form*, so our check
503 * state can get out of sync.
504 * @return Bool|String
506 protected function getWatchCheck() {
507 if( $this->getUser()->getOption( 'watchdefault' ) ) {
512 $local = wfLocalFile( $this->mDesiredDestName
);
513 if( $local && $local->exists() ) {
514 // We're uploading a new version of an existing file.
515 // No creation, so don't watch it if we're not already.
516 return $this->getUser()->isWatched( $local->getTitle() );
518 // New page should get watched if that's our option.
519 return $this->getUser()->getOption( 'watchcreations' );
525 * Provides output to the user for a result of UploadBase::verifyUpload
527 * @param $details Array: result of UploadBase::verifyUpload
529 protected function processVerificationError( $details ) {
530 global $wgFileExtensions;
532 switch( $details['status'] ) {
534 /** Statuses that only require name changing **/
535 case UploadBase
::MIN_LENGTH_PARTNAME
:
536 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
538 case UploadBase
::ILLEGAL_FILENAME
:
539 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
540 $details['filtered'] )->parse() );
542 case UploadBase
::FILENAME_TOO_LONG
:
543 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
545 case UploadBase
::FILETYPE_MISSING
:
546 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
548 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
549 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
552 /** Statuses that require reuploading **/
553 case UploadBase
::EMPTY_FILE
:
554 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
556 case UploadBase
::FILE_TOO_LARGE
:
557 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
559 case UploadBase
::FILETYPE_BADTYPE
:
560 $msg = $this->msg( 'filetype-banned-type' );
561 if ( isset( $details['blacklistedExt'] ) ) {
562 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
564 $msg->params( $details['finalExt'] );
566 $msg->params( $this->getLanguage()->commaList( $wgFileExtensions ),
567 count( $wgFileExtensions ) );
569 // Add PLURAL support for the first parameter. This results
570 // in a bit unlogical parameter sequence, but does not break
572 if ( isset( $details['blacklistedExt'] ) ) {
573 $msg->params( count( $details['blacklistedExt'] ) );
578 $this->showUploadError( $msg->parse() );
580 case UploadBase
::VERIFICATION_ERROR
:
581 unset( $details['status'] );
582 $code = array_shift( $details['details'] );
583 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
585 case UploadBase
::HOOK_ABORTED
:
586 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
587 $args = $details['error'];
588 $error = array_shift( $args );
590 $error = $details['error'];
594 $this->showUploadError( $this->msg( $error, $args )->parse() );
597 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
602 * Remove a temporarily kept file stashed by saveTempUploadedFile().
604 * @return Boolean: success
606 protected function unsaveUploadedFile() {
607 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
610 $success = $this->mUpload
->unsaveUploadedFile();
612 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
619 /*** Functions for formatting warnings ***/
622 * Formats a result of UploadBase::getExistsWarning as HTML
623 * This check is static and can be done pre-upload via AJAX
625 * @param $exists Array: the result of UploadBase::getExistsWarning
626 * @return String: empty string if there is no warning or an HTML fragment
628 public static function getExistsWarning( $exists ) {
633 $file = $exists['file'];
634 $filename = $file->getTitle()->getPrefixedText();
637 if( $exists['warning'] == 'exists' ) {
639 $warning = wfMessage( 'fileexists', $filename )->parse();
640 } elseif( $exists['warning'] == 'page-exists' ) {
641 // Page exists but file does not
642 $warning = wfMessage( 'filepageexists', $filename )->parse();
643 } elseif ( $exists['warning'] == 'exists-normalized' ) {
644 $warning = wfMessage( 'fileexists-extension', $filename,
645 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
646 } elseif ( $exists['warning'] == 'thumb' ) {
647 // Swapped argument order compared with other messages for backwards compatibility
648 $warning = wfMessage( 'fileexists-thumbnail-yes',
649 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
650 } elseif ( $exists['warning'] == 'thumb-name' ) {
651 // Image w/o '180px-' does not exists, but we do not like these filenames
652 $name = $file->getName();
653 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
654 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
655 } elseif ( $exists['warning'] == 'bad-prefix' ) {
656 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
657 } elseif ( $exists['warning'] == 'was-deleted' ) {
658 # If the file existed before and was deleted, warn the user of this
659 $ltitle = SpecialPage
::getTitleFor( 'Log' );
660 $llink = Linker
::linkKnown(
662 wfMessage( 'deletionlog' )->escaped(),
669 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
676 * Get a list of warnings
678 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
679 * @return Array: list of warning messages
681 public static function ajaxGetExistsWarning( $filename ) {
682 $file = wfFindFile( $filename );
684 // Force local file so we have an object to do further checks against
685 // if there isn't an exact match...
686 $file = wfLocalFile( $filename );
690 $exists = UploadBase
::getExistsWarning( $file );
691 $warning = self
::getExistsWarning( $exists );
692 if ( $warning !== '' ) {
693 $s = "<div>$warning</div>";
700 * Construct a warning and a gallery from an array of duplicate files.
701 * @param $dupes array
704 public static function getDupeWarning( $dupes ) {
709 $gallery = new ImageGallery
;
710 $gallery->setShowBytes( false );
711 foreach( $dupes as $file ) {
712 $gallery->add( $file->getTitle() );
715 wfMessage( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
716 $gallery->toHtml() . "</li>\n";
722 * Sub class of HTMLForm that provides the form section of SpecialUpload
724 class UploadForm
extends HTMLForm
{
726 protected $mForReUpload;
727 protected $mSessionKey;
728 protected $mHideIgnoreWarning;
729 protected $mDestWarningAck;
730 protected $mDestFile;
734 protected $mTextAfterSummary;
736 protected $mSourceIds;
738 protected $mMaxFileSize = array();
740 protected $mMaxUploadSize = array();
742 public function __construct( array $options = array(), IContextSource
$context = null ) {
743 $this->mWatch
= !empty( $options['watch'] );
744 $this->mForReUpload
= !empty( $options['forreupload'] );
745 $this->mSessionKey
= isset( $options['sessionkey'] )
746 ?
$options['sessionkey'] : '';
747 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
748 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
749 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
751 $this->mComment
= isset( $options['description'] ) ?
752 $options['description'] : '';
754 $this->mTextTop
= isset( $options['texttop'] )
755 ?
$options['texttop'] : '';
757 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
758 ?
$options['textaftersummary'] : '';
760 $sourceDescriptor = $this->getSourceSection();
761 $descriptor = $sourceDescriptor
762 +
$this->getDescriptionSection()
763 +
$this->getOptionsSection();
765 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
766 parent
::__construct( $descriptor, $context, 'upload' );
768 # Set some form properties
769 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
770 $this->setSubmitName( 'wpUpload' );
771 # Used message keys: 'accesskey-upload', 'tooltip-upload'
772 $this->setSubmitTooltip( 'upload' );
773 $this->setId( 'mw-upload-form' );
775 # Build a list of IDs for javascript insertion
776 $this->mSourceIds
= array();
777 foreach ( $sourceDescriptor as $field ) {
778 if ( !empty( $field['id'] ) ) {
779 $this->mSourceIds
[] = $field['id'];
786 * Get the descriptor of the fieldset that contains the file source
787 * selection. The section is 'source'
789 * @return Array: descriptor array
791 protected function getSourceSection() {
792 if ( $this->mSessionKey
) {
794 'SessionKey' => array(
796 'default' => $this->mSessionKey
,
798 'SourceType' => array(
800 'default' => 'Stash',
805 $canUploadByUrl = UploadFromUrl
::isEnabled() && UploadFromUrl
::isAllowed( $this->getUser() );
806 $radio = $canUploadByUrl;
807 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
809 $descriptor = array();
810 if ( $this->mTextTop
) {
811 $descriptor['UploadFormTextTop'] = array(
813 'section' => 'source',
814 'default' => $this->mTextTop
,
819 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
820 # Limit to upload_max_filesize unless we are running under HipHop and
821 # that setting doesn't exist
822 if ( !wfIsHipHop() ) {
823 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
824 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
825 wfShorthandToInteger( ini_get( 'post_max_size' ) )
829 $descriptor['UploadFile'] = array(
830 'class' => 'UploadSourceField',
831 'section' => 'source',
833 'id' => 'wpUploadFile',
834 'label-message' => 'sourcefilename',
835 'upload-type' => 'File',
837 'help' => $this->msg( 'upload-maxfilesize',
838 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
839 )->parse() . ' ' . $this->msg( 'upload_source_file' )->escaped(),
840 'checked' => $selectedSourceType == 'file',
842 if ( $canUploadByUrl ) {
843 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
844 $descriptor['UploadFileURL'] = array(
845 'class' => 'UploadSourceField',
846 'section' => 'source',
847 'id' => 'wpUploadFileURL',
848 'label-message' => 'sourceurl',
849 'upload-type' => 'url',
851 'help' => $this->msg( 'upload-maxfilesize',
852 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
853 )->parse() . ' ' . $this->msg( 'upload_source_url' )->escaped(),
854 'checked' => $selectedSourceType == 'url',
857 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
859 $descriptor['Extensions'] = array(
861 'section' => 'source',
862 'default' => $this->getExtensionsMessage(),
869 * Get the messages indicating which extensions are preferred and prohibitted.
871 * @return String: HTML string containing the message
873 protected function getExtensionsMessage() {
874 # Print a list of allowed file extensions, if so configured. We ignore
875 # MIME type here, it's incomprehensible to most people and too long.
876 global $wgCheckFileExtensions, $wgStrictFileExtensions,
877 $wgFileExtensions, $wgFileBlacklist;
879 if( $wgCheckFileExtensions ) {
880 if( $wgStrictFileExtensions ) {
881 # Everything not permitted is banned
883 '<div id="mw-upload-permitted">' .
884 $this->msg( 'upload-permitted', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) )->parseAsBlock() .
887 # We have to list both preferred and prohibited
889 '<div id="mw-upload-preferred">' .
890 $this->msg( 'upload-preferred', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) )->parseAsBlock() .
892 '<div id="mw-upload-prohibited">' .
893 $this->msg( 'upload-prohibited', $this->getContext()->getLanguage()->commaList( $wgFileBlacklist ) )->parseAsBlock() .
897 # Everything is permitted.
898 $extensionsList = '';
900 return $extensionsList;
904 * Get the descriptor of the fieldset that contains the file description
905 * input. The section is 'description'
907 * @return Array: descriptor array
909 protected function getDescriptionSection() {
910 if ( $this->mSessionKey
) {
911 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
913 $file = $stash->getFile( $this->mSessionKey
);
914 } catch ( MWException
$e ) {
920 $mto = $file->transform( array( 'width' => 120 ) );
921 $this->addHeaderText(
922 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
923 Html
::element( 'img', array(
924 'src' => $mto->getUrl(),
925 'class' => 'thumbimage',
926 ) ) . '</div>', 'description' );
933 'section' => 'description',
934 'id' => 'wpDestFile',
935 'label-message' => 'destfilename',
937 'default' => $this->mDestFile
,
938 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
939 'nodata' => strval( $this->mDestFile
) !== '',
941 'UploadDescription' => array(
942 'type' => 'textarea',
943 'section' => 'description',
944 'id' => 'wpUploadDescription',
945 'label-message' => $this->mForReUpload
946 ?
'filereuploadsummary'
947 : 'fileuploadsummary',
948 'default' => $this->mComment
,
949 'cols' => intval( $this->getUser()->getOption( 'cols' ) ),
953 if ( $this->mTextAfterSummary
) {
954 $descriptor['UploadFormTextAfterSummary'] = array(
956 'section' => 'description',
957 'default' => $this->mTextAfterSummary
,
962 $descriptor +
= array(
963 'EditTools' => array(
964 'type' => 'edittools',
965 'section' => 'description',
966 'message' => 'edittools-upload',
970 if ( $this->mForReUpload
) {
971 $descriptor['DestFile']['readonly'] = true;
973 $descriptor['License'] = array(
975 'class' => 'Licenses',
976 'section' => 'description',
978 'label-message' => 'license',
982 global $wgUseCopyrightUpload;
983 if ( $wgUseCopyrightUpload ) {
984 $descriptor['UploadCopyStatus'] = array(
986 'section' => 'description',
987 'id' => 'wpUploadCopyStatus',
988 'label-message' => 'filestatus',
990 $descriptor['UploadSource'] = array(
992 'section' => 'description',
993 'id' => 'wpUploadSource',
994 'label-message' => 'filesource',
1002 * Get the descriptor of the fieldset that contains the upload options,
1003 * such as "watch this file". The section is 'options'
1005 * @return Array: descriptor array
1007 protected function getOptionsSection() {
1008 $user = $this->getUser();
1009 if ( $user->isLoggedIn() ) {
1010 $descriptor = array(
1011 'Watchthis' => array(
1013 'id' => 'wpWatchthis',
1014 'label-message' => 'watchthisupload',
1015 'section' => 'options',
1016 'default' => $user->getOption( 'watchcreations' ),
1020 if ( !$this->mHideIgnoreWarning
) {
1021 $descriptor['IgnoreWarning'] = array(
1023 'id' => 'wpIgnoreWarning',
1024 'label-message' => 'ignorewarnings',
1025 'section' => 'options',
1029 $descriptor['DestFileWarningAck'] = array(
1031 'id' => 'wpDestFileWarningAck',
1032 'default' => $this->mDestWarningAck ?
'1' : '',
1035 if ( $this->mForReUpload
) {
1036 $descriptor['ForReUpload'] = array(
1038 'id' => 'wpForReUpload',
1047 * Add the upload JS and show the form.
1049 public function show() {
1050 $this->addUploadJS();
1055 * Add upload JS to the OutputPage
1057 protected function addUploadJS() {
1058 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1060 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1061 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1062 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1064 $scriptVars = array(
1065 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1066 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1067 'wgUploadAutoFill' => !$this->mForReUpload
&&
1068 // If we received mDestFile from the request, don't autofill
1069 // the wpDestFile textbox
1070 $this->mDestFile
=== '',
1071 'wgUploadSourceIds' => $this->mSourceIds
,
1072 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1073 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1074 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1077 $out = $this->getOutput();
1078 $out->addJsConfigVars( $scriptVars );
1081 $out->addModules( array(
1082 'mediawiki.action.edit', // For <charinsert> support
1083 'mediawiki.legacy.upload', // Old form stuff...
1084 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1089 * Empty function; submission is handled elsewhere.
1091 * @return bool false
1093 function trySubmit() {
1100 * A form field that contains a radio box in the label
1102 class UploadSourceField
extends HTMLTextField
{
1105 * @param $cellAttributes array
1108 function getLabelHtml( $cellAttributes = array() ) {
1109 $id = "wpSourceType{$this->mParams['upload-type']}";
1110 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1112 if ( !empty( $this->mParams
['radio'] ) ) {
1114 'name' => 'wpSourceType',
1117 'value' => $this->mParams
['upload-type'],
1119 if ( !empty( $this->mParams
['checked'] ) ) {
1120 $attribs['checked'] = 'checked';
1122 $label .= Html
::element( 'input', $attribs );
1125 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1131 function getSize() {
1132 return isset( $this->mParams
['size'] )
1133 ?
$this->mParams
['size']