3 * Implements Special:Upload
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
26 * Form for handling uploads and special page.
28 * @ingroup SpecialPage
31 class SpecialUpload extends SpecialPage {
33 * Constructor : initialise object
34 * Get data POSTed through the form and assign them to the object
35 * @param $request WebRequest : data posted.
37 public function __construct( $request = null ) {
40 parent::__construct( 'Upload', 'upload' );
42 $this->loadRequest( is_null( $request ) ? $wgRequest : $request );
45 /** Misc variables **/
46 public $mRequest; // The WebRequest or FauxRequest this form is supposed to handle
50 public $mUploadClicked;
52 /** User input variables from the "description" section **/
53 public $mDesiredDestName; // The requested target file name
57 /** User input variables from the root section **/
58 public $mIgnoreWarning;
60 public $mCopyrightStatus;
61 public $mCopyrightSource;
63 /** Hidden variables **/
64 public $mDestWarningAck;
65 public $mForReUpload; // The user followed an "overwrite this file" link
66 public $mCancelUpload; // The user clicked "Cancel and return to upload form" button
68 public $mUploadSuccessful = false; // Subclasses can use this to determine whether a file was uploaded
70 /** Text injection points for hooks not using HTMLForm **/
71 public $uploadFormTextTop;
72 public $uploadFormTextAfterSummary;
75 * Initialize instance variables from request and create an Upload handler
77 * @param $request WebRequest: the request to extract variables from
79 protected function loadRequest( $request ) {
82 $this->mRequest = $request;
83 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
84 $this->mUpload = UploadBase::createFromRequest( $request );
85 $this->mUploadClicked = $request->wasPosted()
86 && ( $request->getCheck( 'wpUpload' )
87 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
89 // Guess the desired name from the filename if not provided
90 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
91 if( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
92 $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
94 $this->mComment = $request->getText( 'wpUploadDescription' );
95 $this->mLicense = $request->getText( 'wpLicense' );
98 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
99 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
100 || $request->getCheck( 'wpUploadIgnoreWarning' );
101 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $wgUser->isLoggedIn();
102 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
103 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
106 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
107 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
108 || $request->getCheck( 'wpReUpload' ); // b/w compat
110 // If it was posted check for the token (no remote POST'ing with user credentials)
111 $token = $request->getVal( 'wpEditToken' );
112 $this->mTokenOk = $wgUser->matchEditToken( $token );
114 $this->uploadFormTextTop = '';
115 $this->uploadFormTextAfterSummary = '';
119 * This page can be shown if uploading is enabled.
120 * Handle permission checking elsewhere in order to be able to show
121 * custom error messages.
123 * @param $user User object
126 public function userCanExecute( $user ) {
127 return UploadBase::isEnabled() && parent::userCanExecute( $user );
131 * Special page entry point
133 public function execute( $par ) {
134 global $wgUser, $wgOut;
137 $this->outputHeader();
139 # Check uploading enabled
140 if( !UploadBase::isEnabled() ) {
141 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
146 global $wgGroupPermissions;
147 $permissionRequired = UploadBase::isAllowed( $wgUser );
148 if( $permissionRequired !== true ) {
149 if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
150 || $wgGroupPermissions['autoconfirmed']['upload'] ) ) {
151 // Custom message if logged-in users without any special rights can upload
152 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
154 $wgOut->permissionRequired( $permissionRequired );
160 if( $wgUser->isBlocked() ) {
161 $wgOut->blockedPage();
165 # Check whether we actually want to allow changing stuff
167 $wgOut->readOnlyPage();
171 # Unsave the temporary file in case this was a cancelled upload
172 if ( $this->mCancelUpload ) {
173 if ( !$this->unsaveUploadedFile() ) {
174 # Something went wrong, so unsaveUploadedFile showed a warning
179 # Process upload or show a form
181 $this->mTokenOk && !$this->mCancelUpload &&
182 ( $this->mUpload && $this->mUploadClicked )
185 $this->processUpload();
187 # Backwards compatibility hook
188 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
189 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
194 $this->showUploadForm( $this->getUploadForm() );
198 if ( $this->mUpload ) {
199 $this->mUpload->cleanupTempFile();
204 * Show the main upload form
206 * @param $form Mixed: an HTMLForm instance or HTML string to show
208 protected function showUploadForm( $form ) {
209 # Add links if file was previously deleted
210 if ( !$this->mDesiredDestName ) {
211 $this->showViewDeletedLinks();
214 if ( $form instanceof HTMLForm ) {
218 $wgOut->addHTML( $form );
224 * Get an UploadForm instance with title and text properly set.
226 * @param $message String: HTML string to add to the form
227 * @param $sessionKey String: session key in case this is a stashed upload
228 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
231 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
235 $form = new UploadForm( array(
236 'watch' => $this->getWatchCheck(),
237 'forreupload' => $this->mForReUpload,
238 'sessionkey' => $sessionKey,
239 'hideignorewarning' => $hideIgnoreWarning,
240 'destwarningack' => (bool)$this->mDestWarningAck,
242 'description' => $this->mComment,
243 'texttop' => $this->uploadFormTextTop,
244 'textaftersummary' => $this->uploadFormTextAfterSummary,
245 'destfile' => $this->mDesiredDestName,
247 $form->setTitle( $this->getTitle() );
249 # Check the token, but only if necessary
251 !$this->mTokenOk && !$this->mCancelUpload &&
252 ( $this->mUpload && $this->mUploadClicked )
255 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
258 # Give a notice if the user is uploading a file that has been deleted or moved
259 # Note that this is independent from the message 'filewasdeleted' that requires JS
260 $desiredTitleObj = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
261 $delNotice = ''; // empty by default
262 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
263 LogEventsList::showLogExtract( $delNotice, array( 'delete', 'move' ),
264 $desiredTitleObj->getPrefixedText(),
265 '', array( 'lim' => 10,
266 'conds' => array( "log_action != 'revision'" ),
267 'showIfEmpty' => false,
268 'msgKey' => array( 'upload-recreate-warning' ) )
271 $form->addPreText( $delNotice );
274 $form->addPreText( '<div id="uploadtext">' .
275 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName ) ) .
277 # Add upload error message
278 $form->addPreText( $message );
281 $uploadFooter = wfMsgNoTrans( 'uploadfooter' );
282 if ( $uploadFooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadFooter ) ) {
283 $form->addPostText( '<div id="mw-upload-footer-message">'
284 . $wgOut->parse( $uploadFooter ) . "</div>\n" );
292 * Shows the "view X deleted revivions link""
294 protected function showViewDeletedLinks() {
295 global $wgOut, $wgUser;
297 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
298 // Show a subtitle link to deleted revisions (to sysops et al only)
299 if( $title instanceof Title ) {
300 $count = $title->isDeleted();
301 if ( $count > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
303 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
304 array( 'parse', 'replaceafter' ),
305 $wgUser->getSkin()->linkKnown(
306 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
307 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
310 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
314 // Show the relevant lines from deletion log (for still deleted files only)
315 if( $title instanceof Title && $title->isDeletedQuick() && !$title->exists() ) {
316 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
321 * Stashes the upload and shows the main upload form.
323 * Note: only errors that can be handled by changing the name or
324 * description should be redirected here. It should be assumed that the
325 * file itself is sane and has passed UploadBase::verifyFile. This
326 * essentially means that UploadBase::VERIFICATION_ERROR and
327 * UploadBase::EMPTY_FILE should not be passed here.
329 * @param $message String: HTML message to be passed to mainUploadForm
331 protected function showRecoverableUploadError( $message ) {
332 $sessionKey = $this->mUpload->stashSession();
333 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
334 '<div class="error">' . $message . "</div>\n";
336 $form = $this->getUploadForm( $message, $sessionKey );
337 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
338 $this->showUploadForm( $form );
341 * Stashes the upload, shows the main form, but adds an "continue anyway button".
342 * Also checks whether there are actually warnings to display.
344 * @param $warnings Array
345 * @return boolean true if warnings were displayed, false if there are no
346 * warnings and the should continue processing like there was no warning
348 protected function showUploadWarning( $warnings ) {
349 # If there are no warnings, or warnings we can ignore, return early.
350 # mDestWarningAck is set when some javascript has shown the warning
351 # to the user. mForReUpload is set when the user clicks the "upload a
353 if ( !$warnings || ( count( $warnings ) == 1 &&
354 isset( $warnings['exists'] ) &&
355 ( $this->mDestWarningAck || $this->mForReUpload ) ) )
360 $sessionKey = $this->mUpload->stashSession();
362 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
363 . '<ul class="warning">';
364 foreach( $warnings as $warning => $args ) {
365 if( $warning == 'exists' ) {
366 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
367 } elseif( $warning == 'duplicate' ) {
368 $msg = self::getDupeWarning( $args );
369 } elseif( $warning == 'duplicate-archive' ) {
370 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
371 array( Title::makeTitle( NS_FILE, $args )->getPrefixedText() ) )
374 if ( $args === true ) {
376 } elseif ( !is_array( $args ) ) {
377 $args = array( $args );
379 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
381 $warningHtml .= $msg;
383 $warningHtml .= "</ul>\n";
384 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
386 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
387 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
388 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
389 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
391 $this->showUploadForm( $form );
393 # Indicate that we showed a form
398 * Show the upload form with error message, but do not stash the file.
400 * @param $message HTML string
402 protected function showUploadError( $message ) {
403 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
404 '<div class="error">' . $message . "</div>\n";
405 $this->showUploadForm( $this->getUploadForm( $message ) );
410 * Checks are made in SpecialUpload::execute()
412 protected function processUpload() {
413 global $wgUser, $wgOut;
415 // Fetch the file if required
416 $status = $this->mUpload->fetchFile();
417 if( !$status->isOK() ) {
418 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
422 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
423 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
424 // This code path is deprecated. If you want to break upload processing
425 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
426 // and UploadBase::verifyFile.
427 // If you use this hook to break uploading, the user will be returned
428 // an empty form with no error message whatsoever.
433 // Upload verification
434 $details = $this->mUpload->verifyUpload();
435 if ( $details['status'] != UploadBase::OK ) {
436 $this->processVerificationError( $details );
440 // Verify permissions for this title
441 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
442 if( $permErrors !== true ) {
443 $code = array_shift( $permErrors[0] );
444 $this->showRecoverableUploadError( wfMsgExt( $code,
445 'parseinline', $permErrors[0] ) );
449 $this->mLocalFile = $this->mUpload->getLocalFile();
451 // Check warnings if necessary
452 if( !$this->mIgnoreWarning ) {
453 $warnings = $this->mUpload->checkWarnings();
454 if( $this->showUploadWarning( $warnings ) ) {
459 // Get the page text if this is not a reupload
460 if( !$this->mForReUpload ) {
461 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
462 $this->mCopyrightStatus, $this->mCopyrightSource );
466 $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $wgUser );
467 if ( !$status->isGood() ) {
468 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
472 // Success, redirect to description page
473 $this->mUploadSuccessful = true;
474 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
475 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
479 * Get the initial image page text based on a comment and optional file status information
481 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
482 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
483 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
485 /* These messages are transcluded into the actual text of the description page.
486 * Thus, forcing them as content messages makes the upload to produce an int: template
487 * instead of hardcoding it there in the uploader language.
489 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
490 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
491 $msg[$msgName] = "{{int:$msgName}}";
493 $msg[$msgName] = wfMsgForContent( $msgName );
497 if ( $wgUseCopyrightUpload ) {
499 if ( $license != '' ) {
500 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
502 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
503 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
505 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
507 if ( $license != '' ) {
508 $filedesc = $comment == '' ? '' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
509 $pageText = $filedesc .
510 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
512 $pageText = $comment;
519 * See if we should check the 'watch this page' checkbox on the form
520 * based on the user's preferences and whether we're being asked
521 * to create a new file or update an existing one.
523 * In the case where 'watch edits' is off but 'watch creations' is on,
524 * we'll leave the box unchecked.
526 * Note that the page target can be changed *on the form*, so our check
527 * state can get out of sync.
529 protected function getWatchCheck() {
531 if( $wgUser->getOption( 'watchdefault' ) ) {
536 $local = wfLocalFile( $this->mDesiredDestName );
537 if( $local && $local->exists() ) {
538 // We're uploading a new version of an existing file.
539 // No creation, so don't watch it if we're not already.
540 return $local->getTitle()->userIsWatching();
542 // New page should get watched if that's our option.
543 return $wgUser->getOption( 'watchcreations' );
549 * Provides output to the user for a result of UploadBase::verifyUpload
551 * @param $details Array: result of UploadBase::verifyUpload
553 protected function processVerificationError( $details ) {
554 global $wgFileExtensions, $wgLang;
556 switch( $details['status'] ) {
558 /** Statuses that only require name changing **/
559 case UploadBase::MIN_LENGTH_PARTNAME:
560 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
562 case UploadBase::ILLEGAL_FILENAME:
563 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
564 'parseinline', $details['filtered'] ) );
566 case UploadBase::FILETYPE_MISSING:
567 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
571 /** Statuses that require reuploading **/
572 case UploadBase::EMPTY_FILE:
573 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
575 case UploadBase::FILE_TOO_LARGE:
576 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
578 case UploadBase::FILETYPE_BADTYPE:
579 $finalExt = $details['finalExt'];
580 $this->showUploadError(
581 wfMsgExt( 'filetype-banned-type',
582 array( 'parseinline' ),
583 htmlspecialchars( $finalExt ),
585 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
588 $wgLang->formatNum( count( $wgFileExtensions ) )
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() {
620 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
623 $success = $this->mUpload->unsaveUploadedFile();
625 $wgOut->showFileDeleteError( $this->mUpload->getTempPath() );
632 /*** Functions for formatting warnings ***/
635 * Formats a result of UploadBase::getExistsWarning as HTML
636 * This check is static and can be done pre-upload via AJAX
638 * @param $exists Array: the result of UploadBase::getExistsWarning
639 * @return String: empty string if there is no warning or an HTML fragment
641 public static function getExistsWarning( $exists ) {
648 $file = $exists['file'];
649 $filename = $file->getTitle()->getPrefixedText();
652 $sk = $wgUser->getSkin();
654 if( $exists['warning'] == 'exists' ) {
656 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
657 } elseif( $exists['warning'] == 'page-exists' ) {
658 // Page exists but file does not
659 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
660 } elseif ( $exists['warning'] == 'exists-normalized' ) {
661 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
662 $exists['normalizedFile']->getTitle()->getPrefixedText() );
663 } elseif ( $exists['warning'] == 'thumb' ) {
664 // Swapped argument order compared with other messages for backwards compatibility
665 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
666 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
667 } elseif ( $exists['warning'] == 'thumb-name' ) {
668 // Image w/o '180px-' does not exists, but we do not like these filenames
669 $name = $file->getName();
670 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
671 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
672 } elseif ( $exists['warning'] == 'bad-prefix' ) {
673 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
674 } elseif ( $exists['warning'] == 'was-deleted' ) {
675 # If the file existed before and was deleted, warn the user of this
676 $ltitle = SpecialPage::getTitleFor( 'Log' );
677 $llink = $sk->linkKnown(
679 wfMsgHtml( 'deletionlog' ),
686 $warning = wfMsgWikiHtml( 'filewasdeleted', $llink );
693 * Get a list of warnings
695 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
696 * @return Array: list of warning messages
698 public static function ajaxGetExistsWarning( $filename ) {
699 $file = wfFindFile( $filename );
701 // Force local file so we have an object to do further checks against
702 // if there isn't an exact match...
703 $file = wfLocalFile( $filename );
707 $exists = UploadBase::getExistsWarning( $file );
708 $warning = self::getExistsWarning( $exists );
709 if ( $warning !== '' ) {
710 $s = "<div>$warning</div>";
717 * Construct a warning and a gallery from an array of duplicate files.
719 public static function getDupeWarning( $dupes ) {
723 foreach( $dupes as $file ) {
724 $title = $file->getTitle();
725 $msg .= $title->getPrefixedText() .
726 '|' . $title->getText() . "\n";
728 $msg .= '</gallery>';
730 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
731 $wgOut->parse( $msg ) .
741 * Sub class of HTMLForm that provides the form section of SpecialUpload
743 class UploadForm extends HTMLForm {
745 protected $mForReUpload;
746 protected $mSessionKey;
747 protected $mHideIgnoreWarning;
748 protected $mDestWarningAck;
749 protected $mDestFile;
753 protected $mTextAfterSummary;
755 protected $mSourceIds;
757 public function __construct( $options = array() ) {
758 $this->mWatch = !empty( $options['watch'] );
759 $this->mForReUpload = !empty( $options['forreupload'] );
760 $this->mSessionKey = isset( $options['sessionkey'] )
761 ? $options['sessionkey'] : '';
762 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
763 $this->mDestWarningAck = !empty( $options['destwarningack'] );
764 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
766 $this->mComment = isset( $options['description'] ) ?
767 $options['description'] : '';
769 $this->mTextTop = isset( $options['texttop'] )
770 ? $options['texttop'] : '';
772 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
773 ? $options['textaftersummary'] : '';
775 $sourceDescriptor = $this->getSourceSection();
776 $descriptor = $sourceDescriptor
777 + $this->getDescriptionSection()
778 + $this->getOptionsSection();
780 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
781 parent::__construct( $descriptor, 'upload' );
783 # Set some form properties
784 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
785 $this->setSubmitName( 'wpUpload' );
786 # Used message keys: 'accesskey-upload', 'tooltip-upload'
787 $this->setSubmitTooltip( 'upload' );
788 $this->setId( 'mw-upload-form' );
790 # Build a list of IDs for javascript insertion
791 $this->mSourceIds = array();
792 foreach ( $sourceDescriptor as $field ) {
793 if ( !empty( $field['id'] ) ) {
794 $this->mSourceIds[] = $field['id'];
801 * Get the descriptor of the fieldset that contains the file source
802 * selection. The section is 'source'
804 * @return Array: descriptor array
806 protected function getSourceSection() {
807 global $wgLang, $wgUser, $wgRequest;
808 global $wgMaxUploadSize;
810 if ( $this->mSessionKey ) {
812 'SessionKey' => array(
814 'default' => $this->mSessionKey,
816 'SourceType' => array(
818 'default' => 'Stash',
823 $canUploadByUrl = UploadFromUrl::isEnabled() && $wgUser->isAllowed( 'upload_by_url' );
824 $radio = $canUploadByUrl;
825 $selectedSourceType = strtolower( $wgRequest->getText( 'wpSourceType', 'File' ) );
827 $descriptor = array();
828 if ( $this->mTextTop ) {
829 $descriptor['UploadFormTextTop'] = array(
831 'section' => 'source',
832 'default' => $this->mTextTop,
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' ),
848 wfShorthandToInteger( min(
849 wfShorthandToInteger(
850 ini_get( 'upload_max_filesize' )
854 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
855 'checked' => $selectedSourceType == 'file',
857 if ( $canUploadByUrl ) {
858 $descriptor['UploadFileURL'] = array(
859 'class' => 'UploadSourceField',
860 'section' => 'source',
861 'id' => 'wpUploadFileURL',
862 'label-message' => 'sourceurl',
863 'upload-type' => 'url',
865 'help' => wfMsgExt( 'upload-maxfilesize',
866 array( 'parseinline', 'escapenoentities' ),
867 $wgLang->formatSize( $wgMaxUploadSize )
868 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
869 'checked' => $selectedSourceType == 'url',
872 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
874 $descriptor['Extensions'] = array(
876 'section' => 'source',
877 'default' => $this->getExtensionsMessage(),
884 * Get the messages indicating which extensions are preferred and prohibitted.
886 * @return String: HTML string containing the message
888 protected function getExtensionsMessage() {
889 # Print a list of allowed file extensions, if so configured. We ignore
890 # MIME type here, it's incomprehensible to most people and too long.
891 global $wgLang, $wgCheckFileExtensions, $wgStrictFileExtensions,
892 $wgFileExtensions, $wgFileBlacklist;
894 if( $wgCheckFileExtensions ) {
895 if( $wgStrictFileExtensions ) {
896 # Everything not permitted is banned
898 '<div id="mw-upload-permitted">' .
899 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
902 # We have to list both preferred and prohibited
904 '<div id="mw-upload-preferred">' .
905 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
907 '<div id="mw-upload-prohibited">' .
908 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
912 # Everything is permitted.
913 $extensionsList = '';
915 return $extensionsList;
919 * Get the descriptor of the fieldset that contains the file description
920 * input. The section is 'description'
922 * @return Array: descriptor array
924 protected function getDescriptionSection() {
930 'section' => 'description',
931 'id' => 'wpDestFile',
932 'label-message' => 'destfilename',
934 'default' => $this->mDestFile,
935 # FIXME: hack to work around poor handling of the 'default' option in HTMLForm
936 'nodata' => strval( $this->mDestFile ) !== '',
938 'UploadDescription' => array(
939 'type' => 'textarea',
940 'section' => 'description',
941 'id' => 'wpUploadDescription',
942 'label-message' => $this->mForReUpload
943 ? 'filereuploadsummary'
944 : 'fileuploadsummary',
945 'default' => $this->mComment,
946 'cols' => intval( $wgUser->getOption( 'cols' ) ),
950 if ( $this->mTextAfterSummary ) {
951 $descriptor['UploadFormTextAfterSummary'] = array(
953 'section' => 'description',
954 'default' => $this->mTextAfterSummary,
959 $descriptor += array(
960 'EditTools' => array(
961 'type' => 'edittools',
962 'section' => 'description',
966 if ( $this->mForReUpload ) {
967 $descriptor['DestFile']['readonly'] = true;
969 $descriptor['License'] = array(
971 'class' => 'Licenses',
972 'section' => 'description',
974 'label-message' => 'license',
978 global $wgUseCopyrightUpload;
979 if ( $wgUseCopyrightUpload ) {
980 $descriptor['UploadCopyStatus'] = array(
982 'section' => 'description',
983 'id' => 'wpUploadCopyStatus',
984 'label-message' => 'filestatus',
986 $descriptor['UploadSource'] = array(
988 'section' => 'description',
989 'id' => 'wpUploadSource',
990 'label-message' => 'filesource',
998 * Get the descriptor of the fieldset that contains the upload options,
999 * such as "watch this file". The section is 'options'
1001 * @return Array: descriptor array
1003 protected function getOptionsSection() {
1006 if ( $wgUser->isLoggedIn() ) {
1007 $descriptor = array(
1008 'Watchthis' => array(
1010 'id' => 'wpWatchthis',
1011 'label-message' => 'watchthisupload',
1012 'section' => 'options',
1013 'default' => $wgUser->getOption( 'watchcreations' ),
1017 if ( !$this->mHideIgnoreWarning ) {
1018 $descriptor['IgnoreWarning'] = array(
1020 'id' => 'wpIgnoreWarning',
1021 'label-message' => 'ignorewarnings',
1022 'section' => 'options',
1026 $descriptor['DestFileWarningAck'] = array(
1028 'id' => 'wpDestFileWarningAck',
1029 'default' => $this->mDestWarningAck ? '1' : '',
1032 if ( $this->mForReUpload ) {
1033 $descriptor['ForReUpload'] = array(
1035 'id' => 'wpForReUpload',
1044 * Add the upload JS and show the form.
1046 public function show() {
1047 $this->addUploadJS();
1052 * Add upload JS to $wgOut
1054 protected function addUploadJS() {
1055 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1058 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1059 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1061 $scriptVars = array(
1062 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1063 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1064 'wgUploadAutoFill' => !$this->mForReUpload &&
1065 // If we received mDestFile from the request, don't autofill
1066 // the wpDestFile textbox
1067 $this->mDestFile === '',
1068 'wgUploadSourceIds' => $this->mSourceIds,
1069 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1070 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1073 $wgOut->addScript( Skin::makeVariablesScript( $scriptVars ) );
1075 // For <charinsert> support
1076 $wgOut->addModules( array( 'mediawiki.legacy.edit', 'mediawiki.legacy.upload' ) );
1080 * Empty function; submission is handled elsewhere.
1082 * @return bool false
1084 function trySubmit() {
1091 * A form field that contains a radio box in the label
1093 class UploadSourceField extends HTMLTextField {
1094 function getLabelHtml( $cellAttributes = array() ) {
1095 $id = "wpSourceType{$this->mParams['upload-type']}";
1096 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1098 if ( !empty( $this->mParams['radio'] ) ) {
1100 'name' => 'wpSourceType',
1103 'value' => $this->mParams['upload-type'],
1105 if ( !empty( $this->mParams['checked'] ) ) {
1106 $attribs['checked'] = 'checked';
1108 $label .= Html::element( 'input', $attribs );
1111 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes, $label );
1114 function getSize() {
1115 return isset( $this->mParams['size'] )
1116 ? $this->mParams['size']