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
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;
79 * Initialize instance variables from request and create an Upload handler
81 * @param $request WebRequest: the request to extract variables from
83 protected function loadRequest( $request ) {
86 $this->mRequest
= $request;
87 $this->mSourceType
= $request->getVal( 'wpSourceType', 'file' );
88 $this->mUpload
= UploadBase
::createFromRequest( $request );
89 $this->mUploadClicked
= $request->wasPosted()
90 && ( $request->getCheck( 'wpUpload' )
91 ||
$request->getCheck( 'wpUploadIgnoreWarning' ) );
93 // Guess the desired name from the filename if not provided
94 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
95 if( !$this->mDesiredDestName
&& $request->getFileName( 'wpUploadFile' ) !== null ) {
96 $this->mDesiredDestName
= $request->getFileName( 'wpUploadFile' );
98 $this->mComment
= $request->getText( 'wpUploadDescription' );
99 $this->mLicense
= $request->getText( 'wpLicense' );
102 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
103 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
104 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
105 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $wgUser->isLoggedIn();
106 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
107 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
110 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
111 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
112 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
114 // If it was posted check for the token (no remote POST'ing with user credentials)
115 $token = $request->getVal( 'wpEditToken' );
116 if( $this->mSourceType
== 'file' && $token == null ) {
117 // Skip token check for file uploads as that can't be faked via JS...
118 // Some client-side tools don't expect to need to send wpEditToken
119 // with their submissions, as that's new in 1.16.
120 $this->mTokenOk
= true;
122 $this->mTokenOk
= $wgUser->matchEditToken( $token );
125 $this->uploadFormTextTop
= '';
126 $this->uploadFormTextAfterSummary
= '';
130 * This page can be shown if uploading is enabled.
131 * Handle permission checking elsewhere in order to be able to show
132 * custom error messages.
134 * @param $user User object
137 public function userCanExecute( $user ) {
138 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
142 * Special page entry point
144 public function execute( $par ) {
145 global $wgUser, $wgOut;
148 $this->outputHeader();
150 # Check uploading enabled
151 if( !UploadBase
::isEnabled() ) {
152 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
157 global $wgGroupPermissions;
158 $permissionRequired = UploadBase
::isAllowed( $wgUser );
159 if( $permissionRequired !== true ) {
160 if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
161 ||
$wgGroupPermissions['autoconfirmed']['upload'] ) ) {
162 // Custom message if logged-in users without any special rights can upload
163 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
165 $wgOut->permissionRequired( $permissionRequired );
171 if( $wgUser->isBlocked() ) {
172 $wgOut->blockedPage();
176 # Check whether we actually want to allow changing stuff
178 $wgOut->readOnlyPage();
182 # Unsave the temporary file in case this was a cancelled upload
183 if ( $this->mCancelUpload
) {
184 if ( !$this->unsaveUploadedFile() ) {
185 # Something went wrong, so unsaveUploadedFile showed a warning
190 # Process upload or show a form
192 $this->mTokenOk
&& !$this->mCancelUpload
&&
193 ( $this->mUpload
&& $this->mUploadClicked
)
196 $this->processUpload();
198 # Backwards compatibility hook
199 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
200 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
205 $this->showUploadForm( $this->getUploadForm() );
209 if ( $this->mUpload
) {
210 $this->mUpload
->cleanupTempFile();
215 * Show the main upload form
217 * @param $form Mixed: an HTMLForm instance or HTML string to show
219 protected function showUploadForm( $form ) {
220 # Add links if file was previously deleted
221 if ( !$this->mDesiredDestName
) {
222 $this->showViewDeletedLinks();
225 if ( $form instanceof HTMLForm
) {
229 $wgOut->addHTML( $form );
235 * Get an UploadForm instance with title and text properly set.
237 * @param $message String: HTML string to add to the form
238 * @param $sessionKey String: session key in case this is a stashed upload
239 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
242 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
246 $form = new UploadForm( array(
247 'watch' => $this->getWatchCheck(),
248 'forreupload' => $this->mForReUpload
,
249 'sessionkey' => $sessionKey,
250 'hideignorewarning' => $hideIgnoreWarning,
251 'destwarningack' => (bool)$this->mDestWarningAck
,
253 'description' => $this->mComment
,
254 'texttop' => $this->uploadFormTextTop
,
255 'textaftersummary' => $this->uploadFormTextAfterSummary
,
256 'destfile' => $this->mDesiredDestName
,
258 $form->setTitle( $this->getTitle() );
260 # Check the token, but only if necessary
262 !$this->mTokenOk
&& !$this->mCancelUpload
&&
263 ( $this->mUpload
&& $this->mUploadClicked
)
266 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
269 # Give a notice if the user is uploading a file that has been deleted or moved
270 # Note that this is independent from the message 'filewasdeleted' that requires JS
271 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
272 $delNotice = ''; // empty by default
273 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
274 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
275 $desiredTitleObj->getPrefixedText(),
276 '', array( 'lim' => 10,
277 'conds' => array( "log_action != 'revision'" ),
278 'showIfEmpty' => false,
279 'msgKey' => array( 'upload-recreate-warning' ) )
282 $form->addPreText( $delNotice );
285 $form->addPreText( '<div id="uploadtext">' .
286 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName
) ) .
288 # Add upload error message
289 $form->addPreText( $message );
292 $uploadFooter = wfMessage( 'uploadfooter' );
293 if ( !$uploadFooter->isDisabled() ) {
294 $form->addPostText( '<div id="mw-upload-footer-message">'
295 . $wgOut->parse( $uploadFooter->plain() ) . "</div>\n" );
303 * Shows the "view X deleted revivions link""
305 protected function showViewDeletedLinks() {
306 global $wgOut, $wgUser;
308 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
309 // Show a subtitle link to deleted revisions (to sysops et al only)
310 if( $title instanceof Title
) {
311 $count = $title->isDeleted();
312 if ( $count > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
314 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
315 array( 'parse', 'replaceafter' ),
316 $wgUser->getSkin()->linkKnown(
317 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
318 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
321 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
325 // Show the relevant lines from deletion log (for still deleted files only)
326 if( $title instanceof Title
&& $title->isDeletedQuick() && !$title->exists() ) {
327 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
332 * Stashes the upload and shows the main upload form.
334 * Note: only errors that can be handled by changing the name or
335 * description should be redirected here. It should be assumed that the
336 * file itself is sane and has passed UploadBase::verifyFile. This
337 * essentially means that UploadBase::VERIFICATION_ERROR and
338 * UploadBase::EMPTY_FILE should not be passed here.
340 * @param $message String: HTML message to be passed to mainUploadForm
342 protected function showRecoverableUploadError( $message ) {
343 $sessionKey = $this->mUpload
->stashSession();
344 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
345 '<div class="error">' . $message . "</div>\n";
347 $form = $this->getUploadForm( $message, $sessionKey );
348 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
349 $this->showUploadForm( $form );
352 * Stashes the upload, shows the main form, but adds an "continue anyway button".
353 * Also checks whether there are actually warnings to display.
355 * @param $warnings Array
356 * @return boolean true if warnings were displayed, false if there are no
357 * warnings and the should continue processing like there was no warning
359 protected function showUploadWarning( $warnings ) {
360 # If there are no warnings, or warnings we can ignore, return early.
361 # mDestWarningAck is set when some javascript has shown the warning
362 # to the user. mForReUpload is set when the user clicks the "upload a
364 if ( !$warnings ||
( count( $warnings ) == 1 &&
365 isset( $warnings['exists'] ) &&
366 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
371 $sessionKey = $this->mUpload
->stashSession();
373 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
374 . '<ul class="warning">';
375 foreach( $warnings as $warning => $args ) {
376 if( $warning == 'exists' ) {
377 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
378 } elseif( $warning == 'duplicate' ) {
379 $msg = self
::getDupeWarning( $args );
380 } elseif( $warning == 'duplicate-archive' ) {
381 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
382 array( Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() ) )
385 if ( $args === true ) {
387 } elseif ( !is_array( $args ) ) {
388 $args = array( $args );
390 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
392 $warningHtml .= $msg;
394 $warningHtml .= "</ul>\n";
395 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
397 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
398 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
399 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
400 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
402 $this->showUploadForm( $form );
404 # Indicate that we showed a form
409 * Show the upload form with error message, but do not stash the file.
411 * @param $message HTML string
413 protected function showUploadError( $message ) {
414 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
415 '<div class="error">' . $message . "</div>\n";
416 $this->showUploadForm( $this->getUploadForm( $message ) );
421 * Checks are made in SpecialUpload::execute()
423 protected function processUpload() {
424 global $wgUser, $wgOut;
426 // Fetch the file if required
427 $status = $this->mUpload
->fetchFile();
428 if( !$status->isOK() ) {
429 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
433 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
434 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
435 // This code path is deprecated. If you want to break upload processing
436 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
437 // and UploadBase::verifyFile.
438 // If you use this hook to break uploading, the user will be returned
439 // an empty form with no error message whatsoever.
443 // Upload verification
444 $details = $this->mUpload
->verifyUpload();
445 if ( $details['status'] != UploadBase
::OK
) {
446 $this->processVerificationError( $details );
450 // Verify permissions for this title
451 $permErrors = $this->mUpload
->verifyPermissions( $wgUser );
452 if( $permErrors !== true ) {
453 $code = array_shift( $permErrors[0] );
454 $this->showRecoverableUploadError( wfMsgExt( $code,
455 'parseinline', $permErrors[0] ) );
459 $this->mLocalFile
= $this->mUpload
->getLocalFile();
461 // Check warnings if necessary
462 if( !$this->mIgnoreWarning
) {
463 $warnings = $this->mUpload
->checkWarnings();
464 if( $this->showUploadWarning( $warnings ) ) {
469 // Get the page text if this is not a reupload
470 if( !$this->mForReUpload
) {
471 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
472 $this->mCopyrightStatus
, $this->mCopyrightSource
);
476 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $wgUser );
477 if ( !$status->isGood() ) {
478 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
482 // Success, redirect to description page
483 $this->mUploadSuccessful
= true;
484 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
485 $wgOut->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
489 * Get the initial image page text based on a comment and optional file status information
491 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
492 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
493 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
495 /* These messages are transcluded into the actual text of the description page.
496 * Thus, forcing them as content messages makes the upload to produce an int: template
497 * instead of hardcoding it there in the uploader language.
499 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
500 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
501 $msg[$msgName] = "{{int:$msgName}}";
503 $msg[$msgName] = wfMsgForContent( $msgName );
507 if ( $wgUseCopyrightUpload ) {
509 if ( $license != '' ) {
510 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
512 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
513 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
515 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
517 if ( $license != '' ) {
518 $filedesc = $comment == '' ?
'' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
519 $pageText = $filedesc .
520 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
522 $pageText = $comment;
529 * See if we should check the 'watch this page' checkbox on the form
530 * based on the user's preferences and whether we're being asked
531 * to create a new file or update an existing one.
533 * In the case where 'watch edits' is off but 'watch creations' is on,
534 * we'll leave the box unchecked.
536 * Note that the page target can be changed *on the form*, so our check
537 * state can get out of sync.
539 protected function getWatchCheck() {
541 if( $wgUser->getOption( 'watchdefault' ) ) {
546 $local = wfLocalFile( $this->mDesiredDestName
);
547 if( $local && $local->exists() ) {
548 // We're uploading a new version of an existing file.
549 // No creation, so don't watch it if we're not already.
550 return $local->getTitle()->userIsWatching();
552 // New page should get watched if that's our option.
553 return $wgUser->getOption( 'watchcreations' );
559 * Provides output to the user for a result of UploadBase::verifyUpload
561 * @param $details Array: result of UploadBase::verifyUpload
563 protected function processVerificationError( $details ) {
564 global $wgFileExtensions;
566 switch( $details['status'] ) {
568 /** Statuses that only require name changing **/
569 case UploadBase
::MIN_LENGTH_PARTNAME
:
570 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
572 case UploadBase
::ILLEGAL_FILENAME
:
573 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
574 'parseinline', $details['filtered'] ) );
576 case UploadBase
::FILETYPE_MISSING
:
577 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
581 /** Statuses that require reuploading **/
582 case UploadBase
::EMPTY_FILE
:
583 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
585 case UploadBase
::FILE_TOO_LARGE
:
586 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
588 case UploadBase
::FILETYPE_BADTYPE
:
589 $msg = wfMessage( 'filetype-banned-type' );
590 $sep = wfMsg( 'comma-separator' );
591 if ( isset( $details['blacklistedExt'] ) ) {
592 $msg->params( implode( $sep, $details['blacklistedExt'] ) );
594 $msg->params( $details['finalExt'] );
596 $msg->params( implode( $sep, $wgFileExtensions ),
597 count( $wgFileExtensions ) );
599 // Add PLURAL support for the first parameter. This results
600 // in a bit unlogical parameter sequence, but does not break
602 if ( isset( $details['blacklistedExt'] ) ) {
603 $msg->numParams( count( $details['blacklistedExt'] ) );
605 $msg->numParams( 1 );
608 $this->showUploadError( $msg->parse() );
610 case UploadBase
::VERIFICATION_ERROR
:
611 unset( $details['status'] );
612 $code = array_shift( $details['details'] );
613 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
615 case UploadBase
::HOOK_ABORTED
:
616 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
617 $args = $details['error'];
618 $error = array_shift( $args );
620 $error = $details['error'];
624 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
627 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
632 * Remove a temporarily kept file stashed by saveTempUploadedFile().
634 * @return Boolean: success
636 protected function unsaveUploadedFile() {
638 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
641 $success = $this->mUpload
->unsaveUploadedFile();
643 $wgOut->showFileDeleteError( $this->mUpload
->getTempPath() );
650 /*** Functions for formatting warnings ***/
653 * Formats a result of UploadBase::getExistsWarning as HTML
654 * This check is static and can be done pre-upload via AJAX
656 * @param $exists Array: the result of UploadBase::getExistsWarning
657 * @return String: empty string if there is no warning or an HTML fragment
659 public static function getExistsWarning( $exists ) {
666 $file = $exists['file'];
667 $filename = $file->getTitle()->getPrefixedText();
670 $sk = $wgUser->getSkin();
672 if( $exists['warning'] == 'exists' ) {
674 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
675 } elseif( $exists['warning'] == 'page-exists' ) {
676 // Page exists but file does not
677 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
678 } elseif ( $exists['warning'] == 'exists-normalized' ) {
679 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
680 $exists['normalizedFile']->getTitle()->getPrefixedText() );
681 } elseif ( $exists['warning'] == 'thumb' ) {
682 // Swapped argument order compared with other messages for backwards compatibility
683 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
684 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
685 } elseif ( $exists['warning'] == 'thumb-name' ) {
686 // Image w/o '180px-' does not exists, but we do not like these filenames
687 $name = $file->getName();
688 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
689 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
690 } elseif ( $exists['warning'] == 'bad-prefix' ) {
691 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
692 } elseif ( $exists['warning'] == 'was-deleted' ) {
693 # If the file existed before and was deleted, warn the user of this
694 $ltitle = SpecialPage
::getTitleFor( 'Log' );
695 $llink = $sk->linkKnown(
697 wfMsgHtml( 'deletionlog' ),
704 $warning = wfMsgExt( 'filewasdeleted', array( 'parse', 'replaceafter' ), $llink );
711 * Get a list of warnings
713 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
714 * @return Array: list of warning messages
716 public static function ajaxGetExistsWarning( $filename ) {
717 $file = wfFindFile( $filename );
719 // Force local file so we have an object to do further checks against
720 // if there isn't an exact match...
721 $file = wfLocalFile( $filename );
725 $exists = UploadBase
::getExistsWarning( $file );
726 $warning = self
::getExistsWarning( $exists );
727 if ( $warning !== '' ) {
728 $s = "<div>$warning</div>";
735 * Construct a warning and a gallery from an array of duplicate files.
737 public static function getDupeWarning( $dupes ) {
741 foreach( $dupes as $file ) {
742 $title = $file->getTitle();
743 $msg .= $title->getPrefixedText() .
744 '|' . $title->getText() . "\n";
746 $msg .= '</gallery>';
748 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
749 $wgOut->parse( $msg ) .
759 * Sub class of HTMLForm that provides the form section of SpecialUpload
761 class UploadForm
extends HTMLForm
{
763 protected $mForReUpload;
764 protected $mSessionKey;
765 protected $mHideIgnoreWarning;
766 protected $mDestWarningAck;
767 protected $mDestFile;
771 protected $mTextAfterSummary;
773 protected $mSourceIds;
775 public function __construct( $options = array() ) {
776 $this->mWatch
= !empty( $options['watch'] );
777 $this->mForReUpload
= !empty( $options['forreupload'] );
778 $this->mSessionKey
= isset( $options['sessionkey'] )
779 ?
$options['sessionkey'] : '';
780 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
781 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
782 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
784 $this->mComment
= isset( $options['description'] ) ?
785 $options['description'] : '';
787 $this->mTextTop
= isset( $options['texttop'] )
788 ?
$options['texttop'] : '';
790 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
791 ?
$options['textaftersummary'] : '';
793 $sourceDescriptor = $this->getSourceSection();
794 $descriptor = $sourceDescriptor
795 +
$this->getDescriptionSection()
796 +
$this->getOptionsSection();
798 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
799 parent
::__construct( $descriptor, 'upload' );
801 # Set some form properties
802 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
803 $this->setSubmitName( 'wpUpload' );
804 # Used message keys: 'accesskey-upload', 'tooltip-upload'
805 $this->setSubmitTooltip( 'upload' );
806 $this->setId( 'mw-upload-form' );
808 # Build a list of IDs for javascript insertion
809 $this->mSourceIds
= array();
810 foreach ( $sourceDescriptor as $field ) {
811 if ( !empty( $field['id'] ) ) {
812 $this->mSourceIds
[] = $field['id'];
819 * Get the descriptor of the fieldset that contains the file source
820 * selection. The section is 'source'
822 * @return Array: descriptor array
824 protected function getSourceSection() {
825 global $wgLang, $wgUser, $wgRequest;
827 if ( $this->mSessionKey
) {
829 'SessionKey' => array(
831 'default' => $this->mSessionKey
,
833 'SourceType' => array(
835 'default' => 'Stash',
840 $canUploadByUrl = UploadFromUrl
::isEnabled() && $wgUser->isAllowed( 'upload_by_url' );
841 $radio = $canUploadByUrl;
842 $selectedSourceType = strtolower( $wgRequest->getText( 'wpSourceType', 'File' ) );
844 $descriptor = array();
845 if ( $this->mTextTop
) {
846 $descriptor['UploadFormTextTop'] = array(
848 'section' => 'source',
849 'default' => $this->mTextTop
,
854 $descriptor['UploadFile'] = array(
855 'class' => 'UploadSourceField',
856 'section' => 'source',
858 'id' => 'wpUploadFile',
859 'label-message' => 'sourcefilename',
860 'upload-type' => 'File',
862 'help' => wfMsgExt( 'upload-maxfilesize',
863 array( 'parseinline', 'escapenoentities' ),
865 wfShorthandToInteger( min(
866 wfShorthandToInteger(
867 ini_get( 'upload_max_filesize' )
868 ), UploadBase
::getMaxUploadSize( 'file' )
871 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
872 'checked' => $selectedSourceType == 'file',
874 if ( $canUploadByUrl ) {
875 $descriptor['UploadFileURL'] = array(
876 'class' => 'UploadSourceField',
877 'section' => 'source',
878 'id' => 'wpUploadFileURL',
879 'label-message' => 'sourceurl',
880 'upload-type' => 'url',
882 'help' => wfMsgExt( 'upload-maxfilesize',
883 array( 'parseinline', 'escapenoentities' ),
884 $wgLang->formatSize( UploadBase
::getMaxUploadSize( 'url' ) )
885 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
886 'checked' => $selectedSourceType == 'url',
889 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
891 $descriptor['Extensions'] = array(
893 'section' => 'source',
894 'default' => $this->getExtensionsMessage(),
901 * Get the messages indicating which extensions are preferred and prohibitted.
903 * @return String: HTML string containing the message
905 protected function getExtensionsMessage() {
906 # Print a list of allowed file extensions, if so configured. We ignore
907 # MIME type here, it's incomprehensible to most people and too long.
908 global $wgLang, $wgCheckFileExtensions, $wgStrictFileExtensions,
909 $wgFileExtensions, $wgFileBlacklist;
911 if( $wgCheckFileExtensions ) {
912 if( $wgStrictFileExtensions ) {
913 # Everything not permitted is banned
915 '<div id="mw-upload-permitted">' .
916 wfMsgExt( 'upload-permitted', 'parse', $wgLang->commaList( $wgFileExtensions ) ) .
919 # We have to list both preferred and prohibited
921 '<div id="mw-upload-preferred">' .
922 wfMsgExt( 'upload-preferred', 'parse', $wgLang->commaList( $wgFileExtensions ) ) .
924 '<div id="mw-upload-prohibited">' .
925 wfMsgExt( 'upload-prohibited', 'parse', $wgLang->commaList( $wgFileBlacklist ) ) .
929 # Everything is permitted.
930 $extensionsList = '';
932 return $extensionsList;
936 * Get the descriptor of the fieldset that contains the file description
937 * input. The section is 'description'
939 * @return Array: descriptor array
941 protected function getDescriptionSection() {
944 if ( $this->mSessionKey
) {
945 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
947 $file = $stash->getFile( $this->mSessionKey
);
948 } catch ( MWException
$e ) {
954 $mto = $file->transform( array( 'width' => 120 ) );
955 $this->addHeaderText(
956 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
957 Html
::element( 'img', array(
958 'src' => $mto->getUrl(),
959 'class' => 'thumbimage',
960 ) ) . '</div>', 'description' );
967 'section' => 'description',
968 'id' => 'wpDestFile',
969 'label-message' => 'destfilename',
971 'default' => $this->mDestFile
,
972 # FIXME: hack to work around poor handling of the 'default' option in HTMLForm
973 'nodata' => strval( $this->mDestFile
) !== '',
975 'UploadDescription' => array(
976 'type' => 'textarea',
977 'section' => 'description',
978 'id' => 'wpUploadDescription',
979 'label-message' => $this->mForReUpload
980 ?
'filereuploadsummary'
981 : 'fileuploadsummary',
982 'default' => $this->mComment
,
983 'cols' => intval( $wgUser->getOption( 'cols' ) ),
987 if ( $this->mTextAfterSummary
) {
988 $descriptor['UploadFormTextAfterSummary'] = array(
990 'section' => 'description',
991 'default' => $this->mTextAfterSummary
,
996 $descriptor +
= array(
997 'EditTools' => array(
998 'type' => 'edittools',
999 'section' => 'description',
1000 'message' => 'edittools-upload',
1004 if ( $this->mForReUpload
) {
1005 $descriptor['DestFile']['readonly'] = true;
1007 $descriptor['License'] = array(
1009 'class' => 'Licenses',
1010 'section' => 'description',
1011 'id' => 'wpLicense',
1012 'label-message' => 'license',
1016 global $wgUseCopyrightUpload;
1017 if ( $wgUseCopyrightUpload ) {
1018 $descriptor['UploadCopyStatus'] = array(
1020 'section' => 'description',
1021 'id' => 'wpUploadCopyStatus',
1022 'label-message' => 'filestatus',
1024 $descriptor['UploadSource'] = array(
1026 'section' => 'description',
1027 'id' => 'wpUploadSource',
1028 'label-message' => 'filesource',
1036 * Get the descriptor of the fieldset that contains the upload options,
1037 * such as "watch this file". The section is 'options'
1039 * @return Array: descriptor array
1041 protected function getOptionsSection() {
1044 if ( $wgUser->isLoggedIn() ) {
1045 $descriptor = array(
1046 'Watchthis' => array(
1048 'id' => 'wpWatchthis',
1049 'label-message' => 'watchthisupload',
1050 'section' => 'options',
1051 'default' => $wgUser->getOption( 'watchcreations' ),
1055 if ( !$this->mHideIgnoreWarning
) {
1056 $descriptor['IgnoreWarning'] = array(
1058 'id' => 'wpIgnoreWarning',
1059 'label-message' => 'ignorewarnings',
1060 'section' => 'options',
1064 $descriptor['DestFileWarningAck'] = array(
1066 'id' => 'wpDestFileWarningAck',
1067 'default' => $this->mDestWarningAck ?
'1' : '',
1070 if ( $this->mForReUpload
) {
1071 $descriptor['ForReUpload'] = array(
1073 'id' => 'wpForReUpload',
1082 * Add the upload JS and show the form.
1084 public function show() {
1085 $this->addUploadJS();
1090 * Add upload JS to $wgOut
1092 protected function addUploadJS() {
1093 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1096 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1097 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1099 $scriptVars = array(
1100 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1101 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1102 'wgUploadAutoFill' => !$this->mForReUpload
&&
1103 // If we received mDestFile from the request, don't autofill
1104 // the wpDestFile textbox
1105 $this->mDestFile
=== '',
1106 'wgUploadSourceIds' => $this->mSourceIds
,
1107 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1108 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1111 $wgOut->addScript( Skin
::makeVariablesScript( $scriptVars ) );
1114 $wgOut->addModules( array(
1115 'mediawiki.legacy.edit', // For <charinsert> support
1116 'mediawiki.legacy.upload', // Old form stuff...
1117 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1122 * Empty function; submission is handled elsewhere.
1124 * @return bool false
1126 function trySubmit() {
1133 * A form field that contains a radio box in the label
1135 class UploadSourceField
extends HTMLTextField
{
1136 function getLabelHtml( $cellAttributes = array() ) {
1137 $id = "wpSourceType{$this->mParams['upload-type']}";
1138 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1140 if ( !empty( $this->mParams
['radio'] ) ) {
1142 'name' => 'wpSourceType',
1145 'value' => $this->mParams
['upload-type'],
1147 if ( !empty( $this->mParams
['checked'] ) ) {
1148 $attribs['checked'] = 'checked';
1150 $label .= Html
::element( 'input', $attribs );
1153 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1156 function getSize() {
1157 return isset( $this->mParams
['size'] )
1158 ?
$this->mParams
['size']