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
58 public $mUploadClicked;
60 /** User input variables from the "description" section **/
61 public $mDesiredDestName; // The requested target file name
65 /** User input variables from the root section **/
66 public $mIgnoreWarning;
68 public $mCopyrightStatus;
69 public $mCopyrightSource;
71 /** Hidden variables **/
72 public $mDestWarningAck;
73 public $mForReUpload; // The user followed an "overwrite this file" link
74 public $mCancelUpload; // The user clicked "Cancel and return to upload form" button
76 public $mUploadSuccessful = false; // Subclasses can use this to determine whether a file was uploaded
78 /** Text injection points for hooks not using HTMLForm **/
79 public $uploadFormTextTop;
80 public $uploadFormTextAfterSummary;
83 * Initialize instance variables from request and create an Upload handler
85 * @param $request WebRequest: the request to extract variables from
87 protected function loadRequest( $request ) {
90 $this->mRequest
= $request;
91 $this->mSourceType
= $request->getVal( 'wpSourceType', 'file' );
92 $this->mUpload
= UploadBase
::createFromRequest( $request );
93 $this->mUploadClicked
= $request->wasPosted()
94 && ( $request->getCheck( 'wpUpload' )
95 ||
$request->getCheck( 'wpUploadIgnoreWarning' ) );
97 // Guess the desired name from the filename if not provided
98 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
99 if( !$this->mDesiredDestName
&& $request->getFileName( 'wpUploadFile' ) !== null ) {
100 $this->mDesiredDestName
= $request->getFileName( 'wpUploadFile' );
102 $this->mComment
= $request->getText( 'wpUploadDescription' );
103 $this->mLicense
= $request->getText( 'wpLicense' );
106 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
107 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
108 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
109 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $wgUser->isLoggedIn();
110 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
111 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
114 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
115 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
116 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
118 // If it was posted check for the token (no remote POST'ing with user credentials)
119 $token = $request->getVal( 'wpEditToken' );
120 if( $this->mSourceType
== 'file' && $token == null ) {
121 // Skip token check for file uploads as that can't be faked via JS...
122 // Some client-side tools don't expect to need to send wpEditToken
123 // with their submissions, as that's new in 1.16.
124 $this->mTokenOk
= true;
126 $this->mTokenOk
= $wgUser->matchEditToken( $token );
129 $this->uploadFormTextTop
= '';
130 $this->uploadFormTextAfterSummary
= '';
134 * This page can be shown if uploading is enabled.
135 * Handle permission checking elsewhere in order to be able to show
136 * custom error messages.
138 * @param $user User object
141 public function userCanExecute( $user ) {
142 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
146 * Special page entry point
148 public function execute( $par ) {
149 global $wgUser, $wgOut;
152 $this->outputHeader();
154 # Check uploading enabled
155 if( !UploadBase
::isEnabled() ) {
156 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
161 global $wgGroupPermissions;
162 $permissionRequired = UploadBase
::isAllowed( $wgUser );
163 if( $permissionRequired !== true ) {
164 if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
165 ||
$wgGroupPermissions['autoconfirmed']['upload'] ) ) {
166 // Custom message if logged-in users without any special rights can upload
167 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
169 $wgOut->permissionRequired( $permissionRequired );
175 if( $wgUser->isBlocked() ) {
176 $wgOut->blockedPage();
180 # Check whether we actually want to allow changing stuff
182 $wgOut->readOnlyPage();
186 # Unsave the temporary file in case this was a cancelled upload
187 if ( $this->mCancelUpload
) {
188 if ( !$this->unsaveUploadedFile() ) {
189 # Something went wrong, so unsaveUploadedFile showed a warning
194 # Process upload or show a form
196 $this->mTokenOk
&& !$this->mCancelUpload
&&
197 ( $this->mUpload
&& $this->mUploadClicked
)
200 $this->processUpload();
202 # Backwards compatibility hook
203 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
204 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
209 $this->showUploadForm( $this->getUploadForm() );
213 if ( $this->mUpload
) {
214 $this->mUpload
->cleanupTempFile();
219 * Show the main upload form
221 * @param $form Mixed: an HTMLForm instance or HTML string to show
223 protected function showUploadForm( $form ) {
224 # Add links if file was previously deleted
225 if ( !$this->mDesiredDestName
) {
226 $this->showViewDeletedLinks();
229 if ( $form instanceof HTMLForm
) {
233 $wgOut->addHTML( $form );
239 * Get an UploadForm instance with title and text properly set.
241 * @param $message String: HTML string to add to the form
242 * @param $sessionKey String: session key in case this is a stashed upload
243 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
246 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
250 $form = new UploadForm( array(
251 'watch' => $this->getWatchCheck(),
252 'forreupload' => $this->mForReUpload
,
253 'sessionkey' => $sessionKey,
254 'hideignorewarning' => $hideIgnoreWarning,
255 'destwarningack' => (bool)$this->mDestWarningAck
,
257 'description' => $this->mComment
,
258 'texttop' => $this->uploadFormTextTop
,
259 'textaftersummary' => $this->uploadFormTextAfterSummary
,
260 'destfile' => $this->mDesiredDestName
,
262 $form->setTitle( $this->getTitle() );
264 # Check the token, but only if necessary
266 !$this->mTokenOk
&& !$this->mCancelUpload
&&
267 ( $this->mUpload
&& $this->mUploadClicked
)
270 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
273 # Give a notice if the user is uploading a file that has been deleted or moved
274 # Note that this is independent from the message 'filewasdeleted' that requires JS
275 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
276 $delNotice = ''; // empty by default
277 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
278 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
279 $desiredTitleObj->getPrefixedText(),
280 '', array( 'lim' => 10,
281 'conds' => array( "log_action != 'revision'" ),
282 'showIfEmpty' => false,
283 'msgKey' => array( 'upload-recreate-warning' ) )
286 $form->addPreText( $delNotice );
289 $form->addPreText( '<div id="uploadtext">' .
290 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName
) ) .
292 # Add upload error message
293 $form->addPreText( $message );
296 $uploadFooter = wfMessage( 'uploadfooter' );
297 if ( !$uploadFooter->isDisabled() ) {
298 $form->addPostText( '<div id="mw-upload-footer-message">'
299 . $wgOut->parse( $uploadFooter->plain() ) . "</div>\n" );
307 * Shows the "view X deleted revivions link""
309 protected function showViewDeletedLinks() {
310 global $wgOut, $wgUser;
312 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
313 // Show a subtitle link to deleted revisions (to sysops et al only)
314 if( $title instanceof Title
) {
315 $count = $title->isDeleted();
316 if ( $count > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
318 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
319 array( 'parse', 'replaceafter' ),
320 $wgUser->getSkin()->linkKnown(
321 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
322 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
325 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
329 // Show the relevant lines from deletion log (for still deleted files only)
330 if( $title instanceof Title
&& $title->isDeletedQuick() && !$title->exists() ) {
331 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
336 * Stashes the upload and shows the main upload form.
338 * Note: only errors that can be handled by changing the name or
339 * description should be redirected here. It should be assumed that the
340 * file itself is sane and has passed UploadBase::verifyFile. This
341 * essentially means that UploadBase::VERIFICATION_ERROR and
342 * UploadBase::EMPTY_FILE should not be passed here.
344 * @param $message String: HTML message to be passed to mainUploadForm
346 protected function showRecoverableUploadError( $message ) {
347 $sessionKey = $this->mUpload
->stashSession();
348 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
349 '<div class="error">' . $message . "</div>\n";
351 $form = $this->getUploadForm( $message, $sessionKey );
352 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
353 $this->showUploadForm( $form );
356 * Stashes the upload, shows the main form, but adds an "continue anyway button".
357 * Also checks whether there are actually warnings to display.
359 * @param $warnings Array
360 * @return boolean true if warnings were displayed, false if there are no
361 * warnings and the should continue processing like there was no warning
363 protected function showUploadWarning( $warnings ) {
364 # If there are no warnings, or warnings we can ignore, return early.
365 # mDestWarningAck is set when some javascript has shown the warning
366 # to the user. mForReUpload is set when the user clicks the "upload a
368 if ( !$warnings ||
( count( $warnings ) == 1 &&
369 isset( $warnings['exists'] ) &&
370 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
375 $sessionKey = $this->mUpload
->stashSession();
377 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
378 . '<ul class="warning">';
379 foreach( $warnings as $warning => $args ) {
380 if( $warning == 'exists' ) {
381 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
382 } elseif( $warning == 'duplicate' ) {
383 $msg = self
::getDupeWarning( $args );
384 } elseif( $warning == 'duplicate-archive' ) {
385 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
386 array( Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() ) )
389 if ( $args === true ) {
391 } elseif ( !is_array( $args ) ) {
392 $args = array( $args );
394 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
396 $warningHtml .= $msg;
398 $warningHtml .= "</ul>\n";
399 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
401 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
402 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
403 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
404 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
406 $this->showUploadForm( $form );
408 # Indicate that we showed a form
413 * Show the upload form with error message, but do not stash the file.
415 * @param $message HTML string
417 protected function showUploadError( $message ) {
418 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
419 '<div class="error">' . $message . "</div>\n";
420 $this->showUploadForm( $this->getUploadForm( $message ) );
425 * Checks are made in SpecialUpload::execute()
427 protected function processUpload() {
428 global $wgUser, $wgOut;
430 // Fetch the file if required
431 $status = $this->mUpload
->fetchFile();
432 if( !$status->isOK() ) {
433 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
437 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
438 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
439 // This code path is deprecated. If you want to break upload processing
440 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
441 // and UploadBase::verifyFile.
442 // If you use this hook to break uploading, the user will be returned
443 // an empty form with no error message whatsoever.
447 // Upload verification
448 $details = $this->mUpload
->verifyUpload();
449 if ( $details['status'] != UploadBase
::OK
) {
450 $this->processVerificationError( $details );
454 // Verify permissions for this title
455 $permErrors = $this->mUpload
->verifyPermissions( $wgUser );
456 if( $permErrors !== true ) {
457 $code = array_shift( $permErrors[0] );
458 $this->showRecoverableUploadError( wfMsgExt( $code[0],
459 'parseinline', $code[1] ) );
463 $this->mLocalFile
= $this->mUpload
->getLocalFile();
465 // Check warnings if necessary
466 if( !$this->mIgnoreWarning
) {
467 $warnings = $this->mUpload
->checkWarnings();
468 if( $this->showUploadWarning( $warnings ) ) {
473 // Get the page text if this is not a reupload
474 if( !$this->mForReUpload
) {
475 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
476 $this->mCopyrightStatus
, $this->mCopyrightSource
);
480 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $wgUser );
481 if ( !$status->isGood() ) {
482 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
486 // Success, redirect to description page
487 $this->mUploadSuccessful
= true;
488 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
489 $wgOut->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
493 * Get the initial image page text based on a comment and optional file status information
495 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
496 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
497 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
499 /* These messages are transcluded into the actual text of the description page.
500 * Thus, forcing them as content messages makes the upload to produce an int: template
501 * instead of hardcoding it there in the uploader language.
503 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
504 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
505 $msg[$msgName] = "{{int:$msgName}}";
507 $msg[$msgName] = wfMsgForContent( $msgName );
511 if ( $wgUseCopyrightUpload ) {
513 if ( $license != '' ) {
514 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
516 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
517 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
519 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
521 if ( $license != '' ) {
522 $filedesc = $comment == '' ?
'' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
523 $pageText = $filedesc .
524 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
526 $pageText = $comment;
533 * See if we should check the 'watch this page' checkbox on the form
534 * based on the user's preferences and whether we're being asked
535 * to create a new file or update an existing one.
537 * In the case where 'watch edits' is off but 'watch creations' is on,
538 * we'll leave the box unchecked.
540 * Note that the page target can be changed *on the form*, so our check
541 * state can get out of sync.
543 protected function getWatchCheck() {
545 if( $wgUser->getOption( 'watchdefault' ) ) {
550 $local = wfLocalFile( $this->mDesiredDestName
);
551 if( $local && $local->exists() ) {
552 // We're uploading a new version of an existing file.
553 // No creation, so don't watch it if we're not already.
554 return $local->getTitle()->userIsWatching();
556 // New page should get watched if that's our option.
557 return $wgUser->getOption( 'watchcreations' );
563 * Provides output to the user for a result of UploadBase::verifyUpload
565 * @param $details Array: result of UploadBase::verifyUpload
567 protected function processVerificationError( $details ) {
568 global $wgFileExtensions;
570 switch( $details['status'] ) {
572 /** Statuses that only require name changing **/
573 case UploadBase
::MIN_LENGTH_PARTNAME
:
574 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
576 case UploadBase
::ILLEGAL_FILENAME
:
577 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
578 'parseinline', $details['filtered'] ) );
580 case UploadBase
::FILETYPE_MISSING
:
581 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
585 /** Statuses that require reuploading **/
586 case UploadBase
::EMPTY_FILE
:
587 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
589 case UploadBase
::FILE_TOO_LARGE
:
590 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
592 case UploadBase
::FILETYPE_BADTYPE
:
593 $msg = wfMessage( 'filetype-banned-type' );
594 $sep = wfMsg( 'comma-separator' );
595 if ( isset( $details['blacklistedExt'] ) ) {
596 $msg->params( implode( $sep, $details['blacklistedExt'] ) );
598 $msg->params( $details['finalExt'] );
600 $msg->params( implode( $sep, $wgFileExtensions ),
601 count( $wgFileExtensions ) );
603 // Add PLURAL support for the first parameter. This results
604 // in a bit unlogical parameter sequence, but does not break
606 if ( isset( $details['blacklistedExt'] ) ) {
607 $msg->numParams( count( $details['blacklistedExt'] ) );
609 $msg->numParams( 1 );
612 $this->showUploadError( $msg->parse() );
614 case UploadBase
::VERIFICATION_ERROR
:
615 unset( $details['status'] );
616 $code = array_shift( $details['details'] );
617 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
619 case UploadBase
::HOOK_ABORTED
:
620 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
621 $args = $details['error'];
622 $error = array_shift( $args );
624 $error = $details['error'];
628 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
631 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
636 * Remove a temporarily kept file stashed by saveTempUploadedFile().
638 * @return Boolean: success
640 protected function unsaveUploadedFile() {
642 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
645 $success = $this->mUpload
->unsaveUploadedFile();
647 $wgOut->showFileDeleteError( $this->mUpload
->getTempPath() );
654 /*** Functions for formatting warnings ***/
657 * Formats a result of UploadBase::getExistsWarning as HTML
658 * This check is static and can be done pre-upload via AJAX
660 * @param $exists Array: the result of UploadBase::getExistsWarning
661 * @return String: empty string if there is no warning or an HTML fragment
663 public static function getExistsWarning( $exists ) {
670 $file = $exists['file'];
671 $filename = $file->getTitle()->getPrefixedText();
674 $sk = $wgUser->getSkin();
676 if( $exists['warning'] == 'exists' ) {
678 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
679 } elseif( $exists['warning'] == 'page-exists' ) {
680 // Page exists but file does not
681 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
682 } elseif ( $exists['warning'] == 'exists-normalized' ) {
683 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
684 $exists['normalizedFile']->getTitle()->getPrefixedText() );
685 } elseif ( $exists['warning'] == 'thumb' ) {
686 // Swapped argument order compared with other messages for backwards compatibility
687 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
688 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
689 } elseif ( $exists['warning'] == 'thumb-name' ) {
690 // Image w/o '180px-' does not exists, but we do not like these filenames
691 $name = $file->getName();
692 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
693 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
694 } elseif ( $exists['warning'] == 'bad-prefix' ) {
695 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
696 } elseif ( $exists['warning'] == 'was-deleted' ) {
697 # If the file existed before and was deleted, warn the user of this
698 $ltitle = SpecialPage
::getTitleFor( 'Log' );
699 $llink = $sk->linkKnown(
701 wfMsgHtml( 'deletionlog' ),
708 $warning = wfMsgExt( 'filewasdeleted', array( 'parse', 'replaceafter' ), $llink );
715 * Get a list of warnings
717 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
718 * @return Array: list of warning messages
720 public static function ajaxGetExistsWarning( $filename ) {
721 $file = wfFindFile( $filename );
723 // Force local file so we have an object to do further checks against
724 // if there isn't an exact match...
725 $file = wfLocalFile( $filename );
729 $exists = UploadBase
::getExistsWarning( $file );
730 $warning = self
::getExistsWarning( $exists );
731 if ( $warning !== '' ) {
732 $s = "<div>$warning</div>";
739 * Construct a warning and a gallery from an array of duplicate files.
741 public static function getDupeWarning( $dupes ) {
745 foreach( $dupes as $file ) {
746 $title = $file->getTitle();
747 $msg .= $title->getPrefixedText() .
748 '|' . $title->getText() . "\n";
750 $msg .= '</gallery>';
752 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
753 $wgOut->parse( $msg ) .
763 * Sub class of HTMLForm that provides the form section of SpecialUpload
765 class UploadForm
extends HTMLForm
{
767 protected $mForReUpload;
768 protected $mSessionKey;
769 protected $mHideIgnoreWarning;
770 protected $mDestWarningAck;
771 protected $mDestFile;
775 protected $mTextAfterSummary;
777 protected $mSourceIds;
779 protected $mMaxFileSize = array();
781 public function __construct( $options = array() ) {
782 $this->mWatch
= !empty( $options['watch'] );
783 $this->mForReUpload
= !empty( $options['forreupload'] );
784 $this->mSessionKey
= isset( $options['sessionkey'] )
785 ?
$options['sessionkey'] : '';
786 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
787 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
788 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
790 $this->mComment
= isset( $options['description'] ) ?
791 $options['description'] : '';
793 $this->mTextTop
= isset( $options['texttop'] )
794 ?
$options['texttop'] : '';
796 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
797 ?
$options['textaftersummary'] : '';
799 $sourceDescriptor = $this->getSourceSection();
800 $descriptor = $sourceDescriptor
801 +
$this->getDescriptionSection()
802 +
$this->getOptionsSection();
804 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
805 parent
::__construct( $descriptor, 'upload' );
807 # Set some form properties
808 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
809 $this->setSubmitName( 'wpUpload' );
810 # Used message keys: 'accesskey-upload', 'tooltip-upload'
811 $this->setSubmitTooltip( 'upload' );
812 $this->setId( 'mw-upload-form' );
814 # Build a list of IDs for javascript insertion
815 $this->mSourceIds
= array();
816 foreach ( $sourceDescriptor as $field ) {
817 if ( !empty( $field['id'] ) ) {
818 $this->mSourceIds
[] = $field['id'];
825 * Get the descriptor of the fieldset that contains the file source
826 * selection. The section is 'source'
828 * @return Array: descriptor array
830 protected function getSourceSection() {
831 global $wgLang, $wgUser, $wgRequest;
833 if ( $this->mSessionKey
) {
835 'SessionKey' => array(
837 'default' => $this->mSessionKey
,
839 'SourceType' => array(
841 'default' => 'Stash',
846 $canUploadByUrl = UploadFromUrl
::isEnabled() && $wgUser->isAllowed( 'upload_by_url' );
847 $radio = $canUploadByUrl;
848 $selectedSourceType = strtolower( $wgRequest->getText( 'wpSourceType', 'File' ) );
850 $descriptor = array();
851 if ( $this->mTextTop
) {
852 $descriptor['UploadFormTextTop'] = array(
854 'section' => 'source',
855 'default' => $this->mTextTop
,
860 $this->mMaxUploadSize
['file'] = min(
861 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
862 UploadBase
::getMaxUploadSize( 'file' ) );
864 $descriptor['UploadFile'] = array(
865 'class' => 'UploadSourceField',
866 'section' => 'source',
868 'id' => 'wpUploadFile',
869 'label-message' => 'sourcefilename',
870 'upload-type' => 'File',
872 'help' => wfMsgExt( 'upload-maxfilesize',
873 array( 'parseinline', 'escapenoentities' ),
874 $wgLang->formatSize( $this->mMaxUploadSize
['file'] )
875 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
876 'checked' => $selectedSourceType == 'file',
878 if ( $canUploadByUrl ) {
879 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
880 $descriptor['UploadFileURL'] = array(
881 'class' => 'UploadSourceField',
882 'section' => 'source',
883 'id' => 'wpUploadFileURL',
884 'label-message' => 'sourceurl',
885 'upload-type' => 'url',
887 'help' => wfMsgExt( 'upload-maxfilesize',
888 array( 'parseinline', 'escapenoentities' ),
889 $wgLang->formatSize( $this->mMaxUploadSize
['url'] )
890 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
891 'checked' => $selectedSourceType == 'url',
894 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
896 $descriptor['Extensions'] = array(
898 'section' => 'source',
899 'default' => $this->getExtensionsMessage(),
906 * Get the messages indicating which extensions are preferred and prohibitted.
908 * @return String: HTML string containing the message
910 protected function getExtensionsMessage() {
911 # Print a list of allowed file extensions, if so configured. We ignore
912 # MIME type here, it's incomprehensible to most people and too long.
913 global $wgLang, $wgCheckFileExtensions, $wgStrictFileExtensions,
914 $wgFileExtensions, $wgFileBlacklist;
916 if( $wgCheckFileExtensions ) {
917 if( $wgStrictFileExtensions ) {
918 # Everything not permitted is banned
920 '<div id="mw-upload-permitted">' .
921 wfMsgExt( 'upload-permitted', 'parse', $wgLang->commaList( $wgFileExtensions ) ) .
924 # We have to list both preferred and prohibited
926 '<div id="mw-upload-preferred">' .
927 wfMsgExt( 'upload-preferred', 'parse', $wgLang->commaList( $wgFileExtensions ) ) .
929 '<div id="mw-upload-prohibited">' .
930 wfMsgExt( 'upload-prohibited', 'parse', $wgLang->commaList( $wgFileBlacklist ) ) .
934 # Everything is permitted.
935 $extensionsList = '';
937 return $extensionsList;
941 * Get the descriptor of the fieldset that contains the file description
942 * input. The section is 'description'
944 * @return Array: descriptor array
946 protected function getDescriptionSection() {
949 if ( $this->mSessionKey
) {
950 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
952 $file = $stash->getFile( $this->mSessionKey
);
953 } catch ( MWException
$e ) {
959 $mto = $file->transform( array( 'width' => 120 ) );
960 $this->addHeaderText(
961 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
962 Html
::element( 'img', array(
963 'src' => $mto->getUrl(),
964 'class' => 'thumbimage',
965 ) ) . '</div>', 'description' );
972 'section' => 'description',
973 'id' => 'wpDestFile',
974 'label-message' => 'destfilename',
976 'default' => $this->mDestFile
,
977 # FIXME: hack to work around poor handling of the 'default' option in HTMLForm
978 'nodata' => strval( $this->mDestFile
) !== '',
980 'UploadDescription' => array(
981 'type' => 'textarea',
982 'section' => 'description',
983 'id' => 'wpUploadDescription',
984 'label-message' => $this->mForReUpload
985 ?
'filereuploadsummary'
986 : 'fileuploadsummary',
987 'default' => $this->mComment
,
988 'cols' => intval( $wgUser->getOption( 'cols' ) ),
992 if ( $this->mTextAfterSummary
) {
993 $descriptor['UploadFormTextAfterSummary'] = array(
995 'section' => 'description',
996 'default' => $this->mTextAfterSummary
,
1001 $descriptor +
= array(
1002 'EditTools' => array(
1003 'type' => 'edittools',
1004 'section' => 'description',
1005 'message' => 'edittools-upload',
1009 if ( $this->mForReUpload
) {
1010 $descriptor['DestFile']['readonly'] = true;
1012 $descriptor['License'] = array(
1014 'class' => 'Licenses',
1015 'section' => 'description',
1016 'id' => 'wpLicense',
1017 'label-message' => 'license',
1021 global $wgUseCopyrightUpload;
1022 if ( $wgUseCopyrightUpload ) {
1023 $descriptor['UploadCopyStatus'] = array(
1025 'section' => 'description',
1026 'id' => 'wpUploadCopyStatus',
1027 'label-message' => 'filestatus',
1029 $descriptor['UploadSource'] = array(
1031 'section' => 'description',
1032 'id' => 'wpUploadSource',
1033 'label-message' => 'filesource',
1041 * Get the descriptor of the fieldset that contains the upload options,
1042 * such as "watch this file". The section is 'options'
1044 * @return Array: descriptor array
1046 protected function getOptionsSection() {
1049 if ( $wgUser->isLoggedIn() ) {
1050 $descriptor = array(
1051 'Watchthis' => array(
1053 'id' => 'wpWatchthis',
1054 'label-message' => 'watchthisupload',
1055 'section' => 'options',
1056 'default' => $wgUser->getOption( 'watchcreations' ),
1060 if ( !$this->mHideIgnoreWarning
) {
1061 $descriptor['IgnoreWarning'] = array(
1063 'id' => 'wpIgnoreWarning',
1064 'label-message' => 'ignorewarnings',
1065 'section' => 'options',
1069 $descriptor['DestFileWarningAck'] = array(
1071 'id' => 'wpDestFileWarningAck',
1072 'default' => $this->mDestWarningAck ?
'1' : '',
1075 if ( $this->mForReUpload
) {
1076 $descriptor['ForReUpload'] = array(
1078 'id' => 'wpForReUpload',
1087 * Add the upload JS and show the form.
1089 public function show() {
1090 $this->addUploadJS();
1095 * Add upload JS to $wgOut
1097 protected function addUploadJS() {
1098 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1101 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1102 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1103 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1105 $scriptVars = array(
1106 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1107 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1108 'wgUploadAutoFill' => !$this->mForReUpload
&&
1109 // If we received mDestFile from the request, don't autofill
1110 // the wpDestFile textbox
1111 $this->mDestFile
=== '',
1112 'wgUploadSourceIds' => $this->mSourceIds
,
1113 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1114 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1115 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1118 $wgOut->addScript( Skin
::makeVariablesScript( $scriptVars ) );
1121 $wgOut->addModules( array(
1122 'mediawiki.legacy.edit', // For <charinsert> support
1123 'mediawiki.legacy.upload', // Old form stuff...
1124 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1129 * Empty function; submission is handled elsewhere.
1131 * @return bool false
1133 function trySubmit() {
1140 * A form field that contains a radio box in the label
1142 class UploadSourceField
extends HTMLTextField
{
1143 function getLabelHtml( $cellAttributes = array() ) {
1144 $id = "wpSourceType{$this->mParams['upload-type']}";
1145 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1147 if ( !empty( $this->mParams
['radio'] ) ) {
1149 'name' => 'wpSourceType',
1152 'value' => $this->mParams
['upload-type'],
1154 if ( !empty( $this->mParams
['checked'] ) ) {
1155 $attribs['checked'] = 'checked';
1157 $label .= Html
::element( 'input', $attribs );
1160 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1163 function getSize() {
1164 return isset( $this->mParams
['size'] )
1165 ?
$this->mParams
['size']