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 ) {
143 global $wgGroupPermissions;
146 $this->outputHeader();
148 # Check uploading enabled
149 if( !UploadBase
::isEnabled() ) {
150 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
154 $user = $this->getUser();
155 $permissionRequired = UploadBase
::isAllowed( $user );
156 if( $permissionRequired !== true ) {
157 if( !$user->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
158 ||
$wgGroupPermissions['autoconfirmed']['upload'] ) ) {
159 // Custom message if logged-in users without any special rights can upload
160 throw new ErrorPageError( 'uploadnologin', 'uploadnologintext' );
162 throw new PermissionsError( $permissionRequired );
167 if( $user->isBlocked() ) {
168 $this->getOutput()->blockedPage();
172 # Check whether we actually want to allow changing stuff
174 throw new ReadOnlyError
;
177 $this->loadRequest();
179 # Unsave the temporary file in case this was a cancelled upload
180 if ( $this->mCancelUpload
) {
181 if ( !$this->unsaveUploadedFile() ) {
182 # Something went wrong, so unsaveUploadedFile showed a warning
187 # Process upload or show a form
189 $this->mTokenOk
&& !$this->mCancelUpload
&&
190 ( $this->mUpload
&& $this->mUploadClicked
)
193 $this->processUpload();
195 # Backwards compatibility hook
196 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
197 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
202 $this->showUploadForm( $this->getUploadForm() );
206 if ( $this->mUpload
) {
207 $this->mUpload
->cleanupTempFile();
212 * Show the main upload form
214 * @param $form Mixed: an HTMLForm instance or HTML string to show
216 protected function showUploadForm( $form ) {
217 # Add links if file was previously deleted
218 if ( $this->mDesiredDestName
) {
219 $this->showViewDeletedLinks();
222 if ( $form instanceof HTMLForm
) {
225 $this->getOutput()->addHTML( $form );
231 * Get an UploadForm instance with title and text properly set.
233 * @param $message String: HTML string to add to the form
234 * @param $sessionKey String: session key in case this is a stashed upload
235 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
238 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
240 $form = new UploadForm( array(
241 'watch' => $this->getWatchCheck(),
242 'forreupload' => $this->mForReUpload
,
243 'sessionkey' => $sessionKey,
244 'hideignorewarning' => $hideIgnoreWarning,
245 'destwarningack' => (bool)$this->mDestWarningAck
,
247 'description' => $this->mComment
,
248 'texttop' => $this->uploadFormTextTop
,
249 'textaftersummary' => $this->uploadFormTextAfterSummary
,
250 'destfile' => $this->mDesiredDestName
,
251 ), $this->getContext() );
252 $form->setTitle( $this->getTitle() );
254 # Check the token, but only if necessary
256 !$this->mTokenOk
&& !$this->mCancelUpload
&&
257 ( $this->mUpload
&& $this->mUploadClicked
)
260 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
263 # Give a notice if the user is uploading a file that has been deleted or moved
264 # Note that this is independent from the message 'filewasdeleted' that requires JS
265 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
266 $delNotice = ''; // empty by default
267 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
268 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
270 '', array( 'lim' => 10,
271 'conds' => array( "log_action != 'revision'" ),
272 'showIfEmpty' => false,
273 'msgKey' => array( 'upload-recreate-warning' ) )
276 $form->addPreText( $delNotice );
279 $form->addPreText( '<div id="uploadtext">' .
280 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName
) ) .
282 # Add upload error message
283 $form->addPreText( $message );
286 $uploadFooter = wfMessage( 'uploadfooter' );
287 if ( !$uploadFooter->isDisabled() ) {
288 $form->addPostText( '<div id="mw-upload-footer-message">'
289 . $this->getOutput()->parse( $uploadFooter->plain() ) . "</div>\n" );
297 * Shows the "view X deleted revivions link""
299 protected function showViewDeletedLinks() {
300 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
301 $user = $this->getUser();
302 // Show a subtitle link to deleted revisions (to sysops et al only)
303 if( $title instanceof Title
) {
304 $count = $title->isDeleted();
305 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
307 $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
308 array( 'parse', 'replaceafter' ),
310 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
311 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
314 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
320 * Stashes the upload and shows the main upload form.
322 * Note: only errors that can be handled by changing the name or
323 * description should be redirected here. It should be assumed that the
324 * file itself is sane and has passed UploadBase::verifyFile. This
325 * essentially means that UploadBase::VERIFICATION_ERROR and
326 * UploadBase::EMPTY_FILE should not be passed here.
328 * @param $message String: HTML message to be passed to mainUploadForm
330 protected function showRecoverableUploadError( $message ) {
331 $sessionKey = $this->mUpload
->stashSession();
332 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
333 '<div class="error">' . $message . "</div>\n";
335 $form = $this->getUploadForm( $message, $sessionKey );
336 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
337 $this->showUploadForm( $form );
340 * Stashes the upload, shows the main form, but adds an "continue anyway button".
341 * Also checks whether there are actually warnings to display.
343 * @param $warnings Array
344 * @return boolean true if warnings were displayed, false if there are no
345 * warnings and the should continue processing like there was no warning
347 protected function showUploadWarning( $warnings ) {
348 # If there are no warnings, or warnings we can ignore, return early.
349 # mDestWarningAck is set when some javascript has shown the warning
350 # to the user. mForReUpload is set when the user clicks the "upload a
352 if ( !$warnings ||
( count( $warnings ) == 1 &&
353 isset( $warnings['exists'] ) &&
354 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
359 $sessionKey = $this->mUpload
->stashSession();
361 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
362 . '<ul class="warning">';
363 foreach( $warnings as $warning => $args ) {
364 if( $warning == 'exists' ) {
365 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
366 } elseif( $warning == 'duplicate' ) {
367 $msg = self
::getDupeWarning( $args );
368 } elseif( $warning == 'duplicate-archive' ) {
369 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
370 array( Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() ) )
373 if ( $args === true ) {
375 } elseif ( !is_array( $args ) ) {
376 $args = array( $args );
378 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
380 $warningHtml .= $msg;
382 $warningHtml .= "</ul>\n";
383 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
385 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
386 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
387 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
388 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
390 $this->showUploadForm( $form );
392 # Indicate that we showed a form
397 * Show the upload form with error message, but do not stash the file.
399 * @param $message HTML string
401 protected function showUploadError( $message ) {
402 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
403 '<div class="error">' . $message . "</div>\n";
404 $this->showUploadForm( $this->getUploadForm( $message ) );
409 * Checks are made in SpecialUpload::execute()
411 protected function processUpload() {
412 // Fetch the file if required
413 $status = $this->mUpload
->fetchFile();
414 if( !$status->isOK() ) {
415 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
419 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
420 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
421 // This code path is deprecated. If you want to break upload processing
422 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
423 // and UploadBase::verifyFile.
424 // If you use this hook to break uploading, the user will be returned
425 // an empty form with no error message whatsoever.
429 // Upload verification
430 $details = $this->mUpload
->verifyUpload();
431 if ( $details['status'] != UploadBase
::OK
) {
432 $this->processVerificationError( $details );
436 // Verify permissions for this title
437 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
438 if( $permErrors !== true ) {
439 $code = array_shift( $permErrors[0] );
440 $this->showRecoverableUploadError( wfMsgExt( $code,
441 'parseinline', $permErrors[0] ) );
445 $this->mLocalFile
= $this->mUpload
->getLocalFile();
447 // Check warnings if necessary
448 if( !$this->mIgnoreWarning
) {
449 $warnings = $this->mUpload
->checkWarnings();
450 if( $this->showUploadWarning( $warnings ) ) {
455 // Get the page text if this is not a reupload
456 if( !$this->mForReUpload
) {
457 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
458 $this->mCopyrightStatus
, $this->mCopyrightSource
);
462 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $this->getUser() );
463 if ( !$status->isGood() ) {
464 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
468 // Success, redirect to description page
469 $this->mUploadSuccessful
= true;
470 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
471 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
475 * Get the initial image page text based on a comment and optional file status information
477 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
478 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
479 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
481 /* These messages are transcluded into the actual text of the description page.
482 * Thus, forcing them as content messages makes the upload to produce an int: template
483 * instead of hardcoding it there in the uploader language.
485 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
486 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
487 $msg[$msgName] = "{{int:$msgName}}";
489 $msg[$msgName] = wfMsgForContent( $msgName );
493 if ( $wgUseCopyrightUpload ) {
495 if ( $license != '' ) {
496 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
498 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
499 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
501 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
503 if ( $license != '' ) {
504 $filedesc = $comment == '' ?
'' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
505 $pageText = $filedesc .
506 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
508 $pageText = $comment;
515 * See if we should check the 'watch this page' checkbox on the form
516 * based on the user's preferences and whether we're being asked
517 * to create a new file or update an existing one.
519 * In the case where 'watch edits' is off but 'watch creations' is on,
520 * we'll leave the box unchecked.
522 * Note that the page target can be changed *on the form*, so our check
523 * state can get out of sync.
525 protected function getWatchCheck() {
526 if( $this->getUser()->getOption( 'watchdefault' ) ) {
531 $local = wfLocalFile( $this->mDesiredDestName
);
532 if( $local && $local->exists() ) {
533 // We're uploading a new version of an existing file.
534 // No creation, so don't watch it if we're not already.
535 return $local->getTitle()->userIsWatching();
537 // New page should get watched if that's our option.
538 return $this->getUser()->getOption( 'watchcreations' );
544 * Provides output to the user for a result of UploadBase::verifyUpload
546 * @param $details Array: result of UploadBase::verifyUpload
548 protected function processVerificationError( $details ) {
549 global $wgFileExtensions;
551 switch( $details['status'] ) {
553 /** Statuses that only require name changing **/
554 case UploadBase
::MIN_LENGTH_PARTNAME
:
555 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
557 case UploadBase
::ILLEGAL_FILENAME
:
558 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
559 'parseinline', $details['filtered'] ) );
561 case UploadBase
::FILENAME_TOO_LONG
:
562 $this->showRecoverableUploadError( wfMsgHtml( 'filename-toolong' ) );
564 case UploadBase
::FILETYPE_MISSING
:
565 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
568 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
569 $this->showRecoverableUploadError( wfMsgExt( 'windows-nonascii-filename',
573 /** Statuses that require reuploading **/
574 case UploadBase
::EMPTY_FILE
:
575 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
577 case UploadBase
::FILE_TOO_LARGE
:
578 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
580 case UploadBase
::FILETYPE_BADTYPE
:
581 $msg = wfMessage( 'filetype-banned-type' );
582 if ( isset( $details['blacklistedExt'] ) ) {
583 $msg->params( $this->getLang()->commaList( $details['blacklistedExt'] ) );
585 $msg->params( $details['finalExt'] );
587 $msg->params( $this->getLang()->commaList( $wgFileExtensions ),
588 count( $wgFileExtensions ) );
590 // Add PLURAL support for the first parameter. This results
591 // in a bit unlogical parameter sequence, but does not break
593 if ( isset( $details['blacklistedExt'] ) ) {
594 $msg->params( count( $details['blacklistedExt'] ) );
599 $this->showUploadError( $msg->parse() );
601 case UploadBase
::VERIFICATION_ERROR
:
602 unset( $details['status'] );
603 $code = array_shift( $details['details'] );
604 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
606 case UploadBase
::HOOK_ABORTED
:
607 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
608 $args = $details['error'];
609 $error = array_shift( $args );
611 $error = $details['error'];
615 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
618 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
623 * Remove a temporarily kept file stashed by saveTempUploadedFile().
625 * @return Boolean: success
627 protected function unsaveUploadedFile() {
628 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
631 $success = $this->mUpload
->unsaveUploadedFile();
633 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
640 /*** Functions for formatting warnings ***/
643 * Formats a result of UploadBase::getExistsWarning as HTML
644 * This check is static and can be done pre-upload via AJAX
646 * @param $exists Array: the result of UploadBase::getExistsWarning
647 * @return String: empty string if there is no warning or an HTML fragment
649 public static function getExistsWarning( $exists ) {
654 $file = $exists['file'];
655 $filename = $file->getTitle()->getPrefixedText();
658 if( $exists['warning'] == 'exists' ) {
660 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
661 } elseif( $exists['warning'] == 'page-exists' ) {
662 // Page exists but file does not
663 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
664 } elseif ( $exists['warning'] == 'exists-normalized' ) {
665 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
666 $exists['normalizedFile']->getTitle()->getPrefixedText() );
667 } elseif ( $exists['warning'] == 'thumb' ) {
668 // Swapped argument order compared with other messages for backwards compatibility
669 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
670 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
671 } elseif ( $exists['warning'] == 'thumb-name' ) {
672 // Image w/o '180px-' does not exists, but we do not like these filenames
673 $name = $file->getName();
674 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
675 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
676 } elseif ( $exists['warning'] == 'bad-prefix' ) {
677 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
678 } elseif ( $exists['warning'] == 'was-deleted' ) {
679 # If the file existed before and was deleted, warn the user of this
680 $ltitle = SpecialPage
::getTitleFor( 'Log' );
681 $llink = Linker
::linkKnown(
683 wfMsgHtml( 'deletionlog' ),
690 $warning = wfMsgExt( 'filewasdeleted', array( 'parse', 'replaceafter' ), $llink );
697 * Get a list of warnings
699 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
700 * @return Array: list of warning messages
702 public static function ajaxGetExistsWarning( $filename ) {
703 $file = wfFindFile( $filename );
705 // Force local file so we have an object to do further checks against
706 // if there isn't an exact match...
707 $file = wfLocalFile( $filename );
711 $exists = UploadBase
::getExistsWarning( $file );
712 $warning = self
::getExistsWarning( $exists );
713 if ( $warning !== '' ) {
714 $s = "<div>$warning</div>";
721 * Construct a warning and a gallery from an array of duplicate files.
723 public static function getDupeWarning( $dupes ) {
727 foreach( $dupes as $file ) {
728 $title = $file->getTitle();
729 $msg .= $title->getPrefixedText() .
730 '|' . $title->getText() . "\n";
732 $msg .= '</gallery>';
734 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
735 $wgOut->parse( $msg ) .
745 * Sub class of HTMLForm that provides the form section of SpecialUpload
747 class UploadForm
extends HTMLForm
{
749 protected $mForReUpload;
750 protected $mSessionKey;
751 protected $mHideIgnoreWarning;
752 protected $mDestWarningAck;
753 protected $mDestFile;
757 protected $mTextAfterSummary;
759 protected $mSourceIds;
761 protected $mMaxFileSize = array();
763 public function __construct( array $options = array(), IContextSource
$context = null ) {
764 $this->mWatch
= !empty( $options['watch'] );
765 $this->mForReUpload
= !empty( $options['forreupload'] );
766 $this->mSessionKey
= isset( $options['sessionkey'] )
767 ?
$options['sessionkey'] : '';
768 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
769 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
770 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
772 $this->mComment
= isset( $options['description'] ) ?
773 $options['description'] : '';
775 $this->mTextTop
= isset( $options['texttop'] )
776 ?
$options['texttop'] : '';
778 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
779 ?
$options['textaftersummary'] : '';
781 $sourceDescriptor = $this->getSourceSection();
782 $descriptor = $sourceDescriptor
783 +
$this->getDescriptionSection()
784 +
$this->getOptionsSection();
786 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
787 parent
::__construct( $descriptor, $context, 'upload' );
789 # Set some form properties
790 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
791 $this->setSubmitName( 'wpUpload' );
792 # Used message keys: 'accesskey-upload', 'tooltip-upload'
793 $this->setSubmitTooltip( 'upload' );
794 $this->setId( 'mw-upload-form' );
796 # Build a list of IDs for javascript insertion
797 $this->mSourceIds
= array();
798 foreach ( $sourceDescriptor as $field ) {
799 if ( !empty( $field['id'] ) ) {
800 $this->mSourceIds
[] = $field['id'];
807 * Get the descriptor of the fieldset that contains the file source
808 * selection. The section is 'source'
810 * @return Array: descriptor array
812 protected function getSourceSection() {
813 if ( $this->mSessionKey
) {
815 'SessionKey' => array(
817 'default' => $this->mSessionKey
,
819 'SourceType' => array(
821 'default' => 'Stash',
826 $canUploadByUrl = UploadFromUrl
::isEnabled() && $this->getUser()->isAllowed( 'upload_by_url' );
827 $radio = $canUploadByUrl;
828 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
830 $descriptor = array();
831 if ( $this->mTextTop
) {
832 $descriptor['UploadFormTextTop'] = array(
834 'section' => 'source',
835 'default' => $this->mTextTop
,
840 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
841 # Limit to upload_max_filesize unless we are running under HipHop and
842 # that setting doesn't exist
843 if ( !wfIsHipHop() ) {
844 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
845 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ) );
848 $descriptor['UploadFile'] = array(
849 'class' => 'UploadSourceField',
850 'section' => 'source',
852 'id' => 'wpUploadFile',
853 'label-message' => 'sourcefilename',
854 'upload-type' => 'File',
856 'help' => wfMsgExt( 'upload-maxfilesize',
857 array( 'parseinline', 'escapenoentities' ),
858 $this->getContext()->getLang()->formatSize( $this->mMaxUploadSize
['file'] )
859 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
860 'checked' => $selectedSourceType == 'file',
862 if ( $canUploadByUrl ) {
863 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
864 $descriptor['UploadFileURL'] = array(
865 'class' => 'UploadSourceField',
866 'section' => 'source',
867 'id' => 'wpUploadFileURL',
868 'label-message' => 'sourceurl',
869 'upload-type' => 'url',
871 'help' => wfMsgExt( 'upload-maxfilesize',
872 array( 'parseinline', 'escapenoentities' ),
873 $this->getContext()->getLang()->formatSize( $this->mMaxUploadSize
['url'] )
874 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
875 'checked' => $selectedSourceType == 'url',
878 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
880 $descriptor['Extensions'] = array(
882 'section' => 'source',
883 'default' => $this->getExtensionsMessage(),
890 * Get the messages indicating which extensions are preferred and prohibitted.
892 * @return String: HTML string containing the message
894 protected function getExtensionsMessage() {
895 # Print a list of allowed file extensions, if so configured. We ignore
896 # MIME type here, it's incomprehensible to most people and too long.
897 global $wgCheckFileExtensions, $wgStrictFileExtensions,
898 $wgFileExtensions, $wgFileBlacklist;
900 if( $wgCheckFileExtensions ) {
901 if( $wgStrictFileExtensions ) {
902 # Everything not permitted is banned
904 '<div id="mw-upload-permitted">' .
905 wfMsgExt( 'upload-permitted', 'parse', $this->getContext()->getLang()->commaList( $wgFileExtensions ) ) .
908 # We have to list both preferred and prohibited
910 '<div id="mw-upload-preferred">' .
911 wfMsgExt( 'upload-preferred', 'parse', $this->getContext()->getLang()->commaList( $wgFileExtensions ) ) .
913 '<div id="mw-upload-prohibited">' .
914 wfMsgExt( 'upload-prohibited', 'parse', $this->getContext()->getLang()->commaList( $wgFileBlacklist ) ) .
918 # Everything is permitted.
919 $extensionsList = '';
921 return $extensionsList;
925 * Get the descriptor of the fieldset that contains the file description
926 * input. The section is 'description'
928 * @return Array: descriptor array
930 protected function getDescriptionSection() {
931 if ( $this->mSessionKey
) {
932 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
934 $file = $stash->getFile( $this->mSessionKey
);
935 } catch ( MWException
$e ) {
941 $mto = $file->transform( array( 'width' => 120 ) );
942 $this->addHeaderText(
943 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
944 Html
::element( 'img', array(
945 'src' => $mto->getUrl(),
946 'class' => 'thumbimage',
947 ) ) . '</div>', 'description' );
954 'section' => 'description',
955 'id' => 'wpDestFile',
956 'label-message' => 'destfilename',
958 'default' => $this->mDestFile
,
959 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
960 'nodata' => strval( $this->mDestFile
) !== '',
962 'UploadDescription' => array(
963 'type' => 'textarea',
964 'section' => 'description',
965 'id' => 'wpUploadDescription',
966 'label-message' => $this->mForReUpload
967 ?
'filereuploadsummary'
968 : 'fileuploadsummary',
969 'default' => $this->mComment
,
970 'cols' => intval( $this->getUser()->getOption( 'cols' ) ),
974 if ( $this->mTextAfterSummary
) {
975 $descriptor['UploadFormTextAfterSummary'] = array(
977 'section' => 'description',
978 'default' => $this->mTextAfterSummary
,
983 $descriptor +
= array(
984 'EditTools' => array(
985 'type' => 'edittools',
986 'section' => 'description',
987 'message' => 'edittools-upload',
991 if ( $this->mForReUpload
) {
992 $descriptor['DestFile']['readonly'] = true;
994 $descriptor['License'] = array(
996 'class' => 'Licenses',
997 'section' => 'description',
999 'label-message' => 'license',
1003 global $wgUseCopyrightUpload;
1004 if ( $wgUseCopyrightUpload ) {
1005 $descriptor['UploadCopyStatus'] = array(
1007 'section' => 'description',
1008 'id' => 'wpUploadCopyStatus',
1009 'label-message' => 'filestatus',
1011 $descriptor['UploadSource'] = array(
1013 'section' => 'description',
1014 'id' => 'wpUploadSource',
1015 'label-message' => 'filesource',
1023 * Get the descriptor of the fieldset that contains the upload options,
1024 * such as "watch this file". The section is 'options'
1026 * @return Array: descriptor array
1028 protected function getOptionsSection() {
1029 $user = $this->getUser();
1030 if ( $user->isLoggedIn() ) {
1031 $descriptor = array(
1032 'Watchthis' => array(
1034 'id' => 'wpWatchthis',
1035 'label-message' => 'watchthisupload',
1036 'section' => 'options',
1037 'default' => $user->getOption( 'watchcreations' ),
1041 if ( !$this->mHideIgnoreWarning
) {
1042 $descriptor['IgnoreWarning'] = array(
1044 'id' => 'wpIgnoreWarning',
1045 'label-message' => 'ignorewarnings',
1046 'section' => 'options',
1050 $descriptor['DestFileWarningAck'] = array(
1052 'id' => 'wpDestFileWarningAck',
1053 'default' => $this->mDestWarningAck ?
'1' : '',
1056 if ( $this->mForReUpload
) {
1057 $descriptor['ForReUpload'] = array(
1059 'id' => 'wpForReUpload',
1068 * Add the upload JS and show the form.
1070 public function show() {
1071 $this->addUploadJS();
1076 * Add upload JS to the OutputPage
1078 protected function addUploadJS() {
1079 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1081 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1082 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1083 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1085 $scriptVars = array(
1086 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1087 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1088 'wgUploadAutoFill' => !$this->mForReUpload
&&
1089 // If we received mDestFile from the request, don't autofill
1090 // the wpDestFile textbox
1091 $this->mDestFile
=== '',
1092 'wgUploadSourceIds' => $this->mSourceIds
,
1093 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1094 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1095 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1098 $out = $this->getOutput();
1099 $out->addScript( Skin
::makeVariablesScript( $scriptVars ) );
1102 $out->addModules( array(
1103 'mediawiki.action.edit', // For <charinsert> support
1104 'mediawiki.legacy.upload', // Old form stuff...
1105 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1110 * Empty function; submission is handled elsewhere.
1112 * @return bool false
1114 function trySubmit() {
1121 * A form field that contains a radio box in the label
1123 class UploadSourceField
extends HTMLTextField
{
1124 function getLabelHtml( $cellAttributes = array() ) {
1125 $id = "wpSourceType{$this->mParams['upload-type']}";
1126 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1128 if ( !empty( $this->mParams
['radio'] ) ) {
1130 'name' => 'wpSourceType',
1133 'value' => $this->mParams
['upload-type'],
1135 if ( !empty( $this->mParams
['checked'] ) ) {
1136 $attribs['checked'] = 'checked';
1138 $label .= Html
::element( 'input', $attribs );
1141 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1144 function getSize() {
1145 return isset( $this->mParams
['size'] )
1146 ?
$this->mParams
['size']