3 * Implements Special:Upload
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
26 * Form for handling uploads and special page.
28 * @ingroup SpecialPage
31 class SpecialUpload
extends SpecialPage
{
33 * Constructor : initialise object
34 * Get data POSTed through the form and assign them to the object
35 * @param $request WebRequest : data posted.
37 public function __construct( $request = null ) {
38 parent
::__construct( 'Upload', 'upload' );
41 /** Misc variables **/
42 public $mRequest; // The WebRequest or FauxRequest this form is supposed to handle
54 public $mUploadClicked;
56 /** User input variables from the "description" section **/
57 public $mDesiredDestName; // The requested target file name
61 /** User input variables from the root section **/
62 public $mIgnoreWarning;
64 public $mCopyrightStatus;
65 public $mCopyrightSource;
67 /** Hidden variables **/
68 public $mDestWarningAck;
69 public $mForReUpload; // The user followed an "overwrite this file" link
70 public $mCancelUpload; // The user clicked "Cancel and return to upload form" button
72 public $mUploadSuccessful = false; // Subclasses can use this to determine whether a file was uploaded
74 /** Text injection points for hooks not using HTMLForm **/
75 public $uploadFormTextTop;
76 public $uploadFormTextAfterSummary;
81 * Initialize instance variables from request and create an Upload handler
83 protected function loadRequest() {
84 $this->mRequest
= $request = $this->getRequest();
85 $this->mSourceType
= $request->getVal( 'wpSourceType', 'file' );
86 $this->mUpload
= UploadBase
::createFromRequest( $request );
87 $this->mUploadClicked
= $request->wasPosted()
88 && ( $request->getCheck( 'wpUpload' )
89 ||
$request->getCheck( 'wpUploadIgnoreWarning' ) );
91 // Guess the desired name from the filename if not provided
92 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
93 if( !$this->mDesiredDestName
&& $request->getFileName( 'wpUploadFile' ) !== null ) {
94 $this->mDesiredDestName
= $request->getFileName( 'wpUploadFile' );
96 $this->mComment
= $request->getText( 'wpUploadDescription' );
97 $this->mLicense
= $request->getText( 'wpLicense' );
100 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
101 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
102 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
103 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
104 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
105 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
108 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
109 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
110 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
112 // If it was posted check for the token (no remote POST'ing with user credentials)
113 $token = $request->getVal( 'wpEditToken' );
114 if( $this->mSourceType
== 'file' && $token == null ) {
115 // Skip token check for file uploads as that can't be faked via JS...
116 // Some client-side tools don't expect to need to send wpEditToken
117 // with their submissions, as that's new in 1.16.
118 $this->mTokenOk
= true;
120 $this->mTokenOk
= $this->getUser()->matchEditToken( $token );
123 $this->uploadFormTextTop
= '';
124 $this->uploadFormTextAfterSummary
= '';
128 * This page can be shown if uploading is enabled.
129 * Handle permission checking elsewhere in order to be able to show
130 * custom error messages.
132 * @param $user User object
135 public function userCanExecute( User
$user ) {
136 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
140 * Special page entry point
142 public function execute( $par ) {
144 $this->outputHeader();
146 # Check uploading enabled
147 if( !UploadBase
::isEnabled() ) {
148 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
152 $user = $this->getUser();
153 $permissionRequired = UploadBase
::isAllowed( $user );
154 if( $permissionRequired !== true ) {
155 throw new PermissionsError( $permissionRequired );
159 if( $user->isBlocked() ) {
160 throw new UserBlockedError( $user->mBlock
);
163 # Check whether we actually want to allow changing stuff
164 $this->checkReadOnly();
166 $this->loadRequest();
168 # Unsave the temporary file in case this was a cancelled upload
169 if ( $this->mCancelUpload
) {
170 if ( !$this->unsaveUploadedFile() ) {
171 # Something went wrong, so unsaveUploadedFile showed a warning
176 # Process upload or show a form
178 $this->mTokenOk
&& !$this->mCancelUpload
&&
179 ( $this->mUpload
&& $this->mUploadClicked
)
182 $this->processUpload();
184 # Backwards compatibility hook
185 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
186 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
191 $this->showUploadForm( $this->getUploadForm() );
195 if ( $this->mUpload
) {
196 $this->mUpload
->cleanupTempFile();
201 * Show the main upload form
203 * @param $form Mixed: an HTMLForm instance or HTML string to show
205 protected function showUploadForm( $form ) {
206 # Add links if file was previously deleted
207 if ( $this->mDesiredDestName
) {
208 $this->showViewDeletedLinks();
211 if ( $form instanceof HTMLForm
) {
214 $this->getOutput()->addHTML( $form );
220 * Get an UploadForm instance with title and text properly set.
222 * @param $message String: HTML string to add to the form
223 * @param $sessionKey String: session key in case this is a stashed upload
224 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
227 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
229 $form = new UploadForm( array(
230 'watch' => $this->getWatchCheck(),
231 'forreupload' => $this->mForReUpload
,
232 'sessionkey' => $sessionKey,
233 'hideignorewarning' => $hideIgnoreWarning,
234 'destwarningack' => (bool)$this->mDestWarningAck
,
236 'description' => $this->mComment
,
237 'texttop' => $this->uploadFormTextTop
,
238 'textaftersummary' => $this->uploadFormTextAfterSummary
,
239 'destfile' => $this->mDesiredDestName
,
240 ), $this->getContext() );
241 $form->setTitle( $this->getTitle() );
243 # Check the token, but only if necessary
245 !$this->mTokenOk
&& !$this->mCancelUpload
&&
246 ( $this->mUpload
&& $this->mUploadClicked
)
248 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
251 # Give a notice if the user is uploading a file that has been deleted or moved
252 # Note that this is independent from the message 'filewasdeleted' that requires JS
253 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
254 $delNotice = ''; // empty by default
255 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
256 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
258 '', array( 'lim' => 10,
259 'conds' => array( "log_action != 'revision'" ),
260 'showIfEmpty' => false,
261 'msgKey' => array( 'upload-recreate-warning' ) )
264 $form->addPreText( $delNotice );
267 $form->addPreText( '<div id="uploadtext">' .
268 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName
) ) .
270 # Add upload error message
271 $form->addPreText( $message );
274 $uploadFooter = wfMessage( 'uploadfooter' );
275 if ( !$uploadFooter->isDisabled() ) {
276 $form->addPostText( '<div id="mw-upload-footer-message">'
277 . $this->getOutput()->parse( $uploadFooter->plain() ) . "</div>\n" );
284 * Shows the "view X deleted revivions link""
286 protected function showViewDeletedLinks() {
287 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
288 $user = $this->getUser();
289 // Show a subtitle link to deleted revisions (to sysops et al only)
290 if( $title instanceof Title
) {
291 $count = $title->isDeleted();
292 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
294 $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
295 array( 'parse', 'replaceafter' ),
297 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
298 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
301 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
307 * Stashes the upload and shows the main upload form.
309 * Note: only errors that can be handled by changing the name or
310 * description should be redirected here. It should be assumed that the
311 * file itself is sane and has passed UploadBase::verifyFile. This
312 * essentially means that UploadBase::VERIFICATION_ERROR and
313 * UploadBase::EMPTY_FILE should not be passed here.
315 * @param $message String: HTML message to be passed to mainUploadForm
317 protected function showRecoverableUploadError( $message ) {
318 $sessionKey = $this->mUpload
->stashSession();
319 $message = '<h2>' . wfMsgHtml( 'uploaderror' ) . "</h2>\n" .
320 '<div class="error">' . $message . "</div>\n";
322 $form = $this->getUploadForm( $message, $sessionKey );
323 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
324 $this->showUploadForm( $form );
327 * Stashes the upload, shows the main form, but adds an "continue anyway button".
328 * Also checks whether there are actually warnings to display.
330 * @param $warnings Array
331 * @return boolean true if warnings were displayed, false if there are no
332 * warnings and the should continue processing like there was no warning
334 protected function showUploadWarning( $warnings ) {
335 # If there are no warnings, or warnings we can ignore, return early.
336 # mDestWarningAck is set when some javascript has shown the warning
337 # to the user. mForReUpload is set when the user clicks the "upload a
339 if ( !$warnings ||
( count( $warnings ) == 1 &&
340 isset( $warnings['exists'] ) &&
341 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
346 $sessionKey = $this->mUpload
->stashSession();
348 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
349 . '<ul class="warning">';
350 foreach( $warnings as $warning => $args ) {
351 if( $warning == 'exists' ) {
352 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
353 } elseif( $warning == 'duplicate' ) {
354 $msg = self
::getDupeWarning( $args );
355 } elseif( $warning == 'duplicate-archive' ) {
356 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
357 array( Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() ) )
360 if ( $args === true ) {
362 } elseif ( !is_array( $args ) ) {
363 $args = array( $args );
365 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
367 $warningHtml .= $msg;
369 $warningHtml .= "</ul>\n";
370 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
372 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
373 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
374 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
375 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
377 $this->showUploadForm( $form );
379 # Indicate that we showed a form
384 * Show the upload form with error message, but do not stash the file.
386 * @param $message string HTML string
388 protected function showUploadError( $message ) {
389 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
390 '<div class="error">' . $message . "</div>\n";
391 $this->showUploadForm( $this->getUploadForm( $message ) );
396 * Checks are made in SpecialUpload::execute()
398 protected function processUpload() {
399 // Fetch the file if required
400 $status = $this->mUpload
->fetchFile();
401 if( !$status->isOK() ) {
402 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
406 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
407 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
408 // This code path is deprecated. If you want to break upload processing
409 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
410 // and UploadBase::verifyFile.
411 // If you use this hook to break uploading, the user will be returned
412 // an empty form with no error message whatsoever.
416 // Upload verification
417 $details = $this->mUpload
->verifyUpload();
418 if ( $details['status'] != UploadBase
::OK
) {
419 $this->processVerificationError( $details );
423 // Verify permissions for this title
424 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
425 if( $permErrors !== true ) {
426 $code = array_shift( $permErrors[0] );
427 $this->showRecoverableUploadError( wfMsgExt( $code,
428 'parseinline', $permErrors[0] ) );
432 $this->mLocalFile
= $this->mUpload
->getLocalFile();
434 // Check warnings if necessary
435 if( !$this->mIgnoreWarning
) {
436 $warnings = $this->mUpload
->checkWarnings();
437 if( $this->showUploadWarning( $warnings ) ) {
442 // Get the page text if this is not a reupload
443 if( !$this->mForReUpload
) {
444 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
445 $this->mCopyrightStatus
, $this->mCopyrightSource
);
449 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $this->getUser() );
450 if ( !$status->isGood() ) {
451 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
455 // Success, redirect to description page
456 $this->mUploadSuccessful
= true;
457 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
458 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
462 * Get the initial image page text based on a comment and optional file status information
463 * @param $comment string
464 * @param $license string
465 * @param $copyStatus string
466 * @param $source string
469 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
470 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
471 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
474 /* These messages are transcluded into the actual text of the description page.
475 * Thus, forcing them as content messages makes the upload to produce an int: template
476 * instead of hardcoding it there in the uploader language.
478 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
479 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
480 $msg[$msgName] = "{{int:$msgName}}";
482 $msg[$msgName] = wfMsgForContent( $msgName );
486 if ( $wgUseCopyrightUpload ) {
488 if ( $license != '' ) {
489 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
491 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
492 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
494 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
496 if ( $license != '' ) {
497 $filedesc = $comment == '' ?
'' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
498 $pageText = $filedesc .
499 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
501 $pageText = $comment;
508 * See if we should check the 'watch this page' checkbox on the form
509 * based on the user's preferences and whether we're being asked
510 * to create a new file or update an existing one.
512 * In the case where 'watch edits' is off but 'watch creations' is on,
513 * we'll leave the box unchecked.
515 * Note that the page target can be changed *on the form*, so our check
516 * state can get out of sync.
517 * @return Bool|String
519 protected function getWatchCheck() {
520 if( $this->getUser()->getOption( 'watchdefault' ) ) {
525 $local = wfLocalFile( $this->mDesiredDestName
);
526 if( $local && $local->exists() ) {
527 // We're uploading a new version of an existing file.
528 // No creation, so don't watch it if we're not already.
529 return $local->getTitle()->userIsWatching();
531 // New page should get watched if that's our option.
532 return $this->getUser()->getOption( 'watchcreations' );
538 * Provides output to the user for a result of UploadBase::verifyUpload
540 * @param $details Array: result of UploadBase::verifyUpload
542 protected function processVerificationError( $details ) {
543 global $wgFileExtensions;
545 switch( $details['status'] ) {
547 /** Statuses that only require name changing **/
548 case UploadBase
::MIN_LENGTH_PARTNAME
:
549 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
551 case UploadBase
::ILLEGAL_FILENAME
:
552 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
553 'parseinline', $details['filtered'] ) );
555 case UploadBase
::FILENAME_TOO_LONG
:
556 $this->showRecoverableUploadError( wfMsgHtml( 'filename-toolong' ) );
558 case UploadBase
::FILETYPE_MISSING
:
559 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
562 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
563 $this->showRecoverableUploadError( wfMsgExt( 'windows-nonascii-filename',
567 /** Statuses that require reuploading **/
568 case UploadBase
::EMPTY_FILE
:
569 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
571 case UploadBase
::FILE_TOO_LARGE
:
572 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
574 case UploadBase
::FILETYPE_BADTYPE
:
575 $msg = wfMessage( 'filetype-banned-type' );
576 if ( isset( $details['blacklistedExt'] ) ) {
577 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
579 $msg->params( $details['finalExt'] );
581 $msg->params( $this->getLanguage()->commaList( $wgFileExtensions ),
582 count( $wgFileExtensions ) );
584 // Add PLURAL support for the first parameter. This results
585 // in a bit unlogical parameter sequence, but does not break
587 if ( isset( $details['blacklistedExt'] ) ) {
588 $msg->params( count( $details['blacklistedExt'] ) );
593 $this->showUploadError( $msg->parse() );
595 case UploadBase
::VERIFICATION_ERROR
:
596 unset( $details['status'] );
597 $code = array_shift( $details['details'] );
598 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
600 case UploadBase
::HOOK_ABORTED
:
601 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
602 $args = $details['error'];
603 $error = array_shift( $args );
605 $error = $details['error'];
609 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
612 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
617 * Remove a temporarily kept file stashed by saveTempUploadedFile().
619 * @return Boolean: success
621 protected function unsaveUploadedFile() {
622 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
625 $success = $this->mUpload
->unsaveUploadedFile();
627 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
634 /*** Functions for formatting warnings ***/
637 * Formats a result of UploadBase::getExistsWarning as HTML
638 * This check is static and can be done pre-upload via AJAX
640 * @param $exists Array: the result of UploadBase::getExistsWarning
641 * @return String: empty string if there is no warning or an HTML fragment
643 public static function getExistsWarning( $exists ) {
648 $file = $exists['file'];
649 $filename = $file->getTitle()->getPrefixedText();
652 if( $exists['warning'] == 'exists' ) {
654 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
655 } elseif( $exists['warning'] == 'page-exists' ) {
656 // Page exists but file does not
657 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
658 } elseif ( $exists['warning'] == 'exists-normalized' ) {
659 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
660 $exists['normalizedFile']->getTitle()->getPrefixedText() );
661 } elseif ( $exists['warning'] == 'thumb' ) {
662 // Swapped argument order compared with other messages for backwards compatibility
663 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
664 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
665 } elseif ( $exists['warning'] == 'thumb-name' ) {
666 // Image w/o '180px-' does not exists, but we do not like these filenames
667 $name = $file->getName();
668 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
669 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
670 } elseif ( $exists['warning'] == 'bad-prefix' ) {
671 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
672 } elseif ( $exists['warning'] == 'was-deleted' ) {
673 # If the file existed before and was deleted, warn the user of this
674 $ltitle = SpecialPage
::getTitleFor( 'Log' );
675 $llink = Linker
::linkKnown(
677 wfMsgHtml( 'deletionlog' ),
684 $warning = wfMsgExt( 'filewasdeleted', array( 'parse', 'replaceafter' ), $llink );
691 * Get a list of warnings
693 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
694 * @return Array: list of warning messages
696 public static function ajaxGetExistsWarning( $filename ) {
697 $file = wfFindFile( $filename );
699 // Force local file so we have an object to do further checks against
700 // if there isn't an exact match...
701 $file = wfLocalFile( $filename );
705 $exists = UploadBase
::getExistsWarning( $file );
706 $warning = self
::getExistsWarning( $exists );
707 if ( $warning !== '' ) {
708 $s = "<div>$warning</div>";
715 * Construct a warning and a gallery from an array of duplicate files.
716 * @param $dupes array
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 protected $mMaxFileSize = array();
759 protected $mMaxUploadSize = array();
761 public function __construct( array $options = array(), IContextSource
$context = null ) {
762 $this->mWatch
= !empty( $options['watch'] );
763 $this->mForReUpload
= !empty( $options['forreupload'] );
764 $this->mSessionKey
= isset( $options['sessionkey'] )
765 ?
$options['sessionkey'] : '';
766 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
767 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
768 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
770 $this->mComment
= isset( $options['description'] ) ?
771 $options['description'] : '';
773 $this->mTextTop
= isset( $options['texttop'] )
774 ?
$options['texttop'] : '';
776 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
777 ?
$options['textaftersummary'] : '';
779 $sourceDescriptor = $this->getSourceSection();
780 $descriptor = $sourceDescriptor
781 +
$this->getDescriptionSection()
782 +
$this->getOptionsSection();
784 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
785 parent
::__construct( $descriptor, $context, 'upload' );
787 # Set some form properties
788 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
789 $this->setSubmitName( 'wpUpload' );
790 # Used message keys: 'accesskey-upload', 'tooltip-upload'
791 $this->setSubmitTooltip( 'upload' );
792 $this->setId( 'mw-upload-form' );
794 # Build a list of IDs for javascript insertion
795 $this->mSourceIds
= array();
796 foreach ( $sourceDescriptor as $field ) {
797 if ( !empty( $field['id'] ) ) {
798 $this->mSourceIds
[] = $field['id'];
805 * Get the descriptor of the fieldset that contains the file source
806 * selection. The section is 'source'
808 * @return Array: descriptor array
810 protected function getSourceSection() {
811 if ( $this->mSessionKey
) {
813 'SessionKey' => array(
815 'default' => $this->mSessionKey
,
817 'SourceType' => array(
819 'default' => 'Stash',
824 $canUploadByUrl = UploadFromUrl
::isEnabled() && $this->getUser()->isAllowed( 'upload_by_url' );
825 $radio = $canUploadByUrl;
826 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
828 $descriptor = array();
829 if ( $this->mTextTop
) {
830 $descriptor['UploadFormTextTop'] = array(
832 'section' => 'source',
833 'default' => $this->mTextTop
,
838 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
839 # Limit to upload_max_filesize unless we are running under HipHop and
840 # that setting doesn't exist
841 if ( !wfIsHipHop() ) {
842 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
843 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ) );
846 $descriptor['UploadFile'] = array(
847 'class' => 'UploadSourceField',
848 'section' => 'source',
850 'id' => 'wpUploadFile',
851 'label-message' => 'sourcefilename',
852 'upload-type' => 'File',
854 'help' => wfMsgExt( 'upload-maxfilesize',
855 array( 'parseinline', 'escapenoentities' ),
856 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
857 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
858 'checked' => $selectedSourceType == 'file',
860 if ( $canUploadByUrl ) {
861 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
862 $descriptor['UploadFileURL'] = array(
863 'class' => 'UploadSourceField',
864 'section' => 'source',
865 'id' => 'wpUploadFileURL',
866 'label-message' => 'sourceurl',
867 'upload-type' => 'url',
869 'help' => wfMsgExt( 'upload-maxfilesize',
870 array( 'parseinline', 'escapenoentities' ),
871 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
872 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
873 'checked' => $selectedSourceType == 'url',
876 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
878 $descriptor['Extensions'] = array(
880 'section' => 'source',
881 'default' => $this->getExtensionsMessage(),
888 * Get the messages indicating which extensions are preferred and prohibitted.
890 * @return String: HTML string containing the message
892 protected function getExtensionsMessage() {
893 # Print a list of allowed file extensions, if so configured. We ignore
894 # MIME type here, it's incomprehensible to most people and too long.
895 global $wgCheckFileExtensions, $wgStrictFileExtensions,
896 $wgFileExtensions, $wgFileBlacklist;
898 if( $wgCheckFileExtensions ) {
899 if( $wgStrictFileExtensions ) {
900 # Everything not permitted is banned
902 '<div id="mw-upload-permitted">' .
903 wfMsgExt( 'upload-permitted', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) ) .
906 # We have to list both preferred and prohibited
908 '<div id="mw-upload-preferred">' .
909 wfMsgExt( 'upload-preferred', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) ) .
911 '<div id="mw-upload-prohibited">' .
912 wfMsgExt( 'upload-prohibited', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileBlacklist ) ) .
916 # Everything is permitted.
917 $extensionsList = '';
919 return $extensionsList;
923 * Get the descriptor of the fieldset that contains the file description
924 * input. The section is 'description'
926 * @return Array: descriptor array
928 protected function getDescriptionSection() {
929 if ( $this->mSessionKey
) {
930 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
932 $file = $stash->getFile( $this->mSessionKey
);
933 } catch ( MWException
$e ) {
939 $mto = $file->transform( array( 'width' => 120 ) );
940 $this->addHeaderText(
941 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
942 Html
::element( 'img', array(
943 'src' => $mto->getUrl(),
944 'class' => 'thumbimage',
945 ) ) . '</div>', 'description' );
952 'section' => 'description',
953 'id' => 'wpDestFile',
954 'label-message' => 'destfilename',
956 'default' => $this->mDestFile
,
957 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
958 'nodata' => strval( $this->mDestFile
) !== '',
960 'UploadDescription' => array(
961 'type' => 'textarea',
962 'section' => 'description',
963 'id' => 'wpUploadDescription',
964 'label-message' => $this->mForReUpload
965 ?
'filereuploadsummary'
966 : 'fileuploadsummary',
967 'default' => $this->mComment
,
971 if ( $this->mTextAfterSummary
) {
972 $descriptor['UploadFormTextAfterSummary'] = array(
974 'section' => 'description',
975 'default' => $this->mTextAfterSummary
,
980 $descriptor +
= array(
981 'EditTools' => array(
982 'type' => 'edittools',
983 'section' => 'description',
984 'message' => 'edittools-upload',
988 if ( $this->mForReUpload
) {
989 $descriptor['DestFile']['readonly'] = true;
991 $descriptor['License'] = array(
993 'class' => 'Licenses',
994 'section' => 'description',
996 'label-message' => 'license',
1000 global $wgUseCopyrightUpload;
1001 if ( $wgUseCopyrightUpload ) {
1002 $descriptor['UploadCopyStatus'] = array(
1004 'section' => 'description',
1005 'id' => 'wpUploadCopyStatus',
1006 'label-message' => 'filestatus',
1008 $descriptor['UploadSource'] = array(
1010 'section' => 'description',
1011 'id' => 'wpUploadSource',
1012 'label-message' => 'filesource',
1020 * Get the descriptor of the fieldset that contains the upload options,
1021 * such as "watch this file". The section is 'options'
1023 * @return Array: descriptor array
1025 protected function getOptionsSection() {
1026 $user = $this->getUser();
1027 if ( $user->isLoggedIn() ) {
1028 $descriptor = array(
1029 'Watchthis' => array(
1031 'id' => 'wpWatchthis',
1032 'label-message' => 'watchthisupload',
1033 'section' => 'options',
1034 'default' => $user->getOption( 'watchcreations' ),
1038 if ( !$this->mHideIgnoreWarning
) {
1039 $descriptor['IgnoreWarning'] = array(
1041 'id' => 'wpIgnoreWarning',
1042 'label-message' => 'ignorewarnings',
1043 'section' => 'options',
1047 $descriptor['DestFileWarningAck'] = array(
1049 'id' => 'wpDestFileWarningAck',
1050 'default' => $this->mDestWarningAck ?
'1' : '',
1053 if ( $this->mForReUpload
) {
1054 $descriptor['ForReUpload'] = array(
1056 'id' => 'wpForReUpload',
1065 * Add the upload JS and show the form.
1067 public function show() {
1068 $this->addUploadJS();
1073 * Add upload JS to the OutputPage
1075 protected function addUploadJS() {
1076 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1078 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1079 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1080 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1082 $scriptVars = array(
1083 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1084 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1085 'wgUploadAutoFill' => !$this->mForReUpload
&&
1086 // If we received mDestFile from the request, don't autofill
1087 // the wpDestFile textbox
1088 $this->mDestFile
=== '',
1089 'wgUploadSourceIds' => $this->mSourceIds
,
1090 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1091 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1092 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1095 $out = $this->getOutput();
1096 $out->addJsConfigVars( $scriptVars );
1099 $out->addModules( array(
1100 'mediawiki.action.edit', // For <charinsert> support
1101 'mediawiki.legacy.upload', // Old form stuff...
1102 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1107 * Empty function; submission is handled elsewhere.
1109 * @return bool false
1111 function trySubmit() {
1118 * A form field that contains a radio box in the label
1120 class UploadSourceField
extends HTMLTextField
{
1123 * @param $cellAttributes array
1126 function getLabelHtml( $cellAttributes = array() ) {
1127 $id = "wpSourceType{$this->mParams['upload-type']}";
1128 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1130 if ( !empty( $this->mParams
['radio'] ) ) {
1132 'name' => 'wpSourceType',
1135 'value' => $this->mParams
['upload-type'],
1137 if ( !empty( $this->mParams
['checked'] ) ) {
1138 $attribs['checked'] = 'checked';
1140 $label .= Html
::element( 'input', $attribs );
1143 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1149 function getSize() {
1150 return isset( $this->mParams
['size'] )
1151 ?
$this->mParams
['size']