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->getBlock() );
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
)
181 $this->processUpload();
183 # Backwards compatibility hook
184 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
185 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
188 $this->showUploadForm( $this->getUploadForm() );
192 if ( $this->mUpload
) {
193 $this->mUpload
->cleanupTempFile();
198 * Show the main upload form
200 * @param $form Mixed: an HTMLForm instance or HTML string to show
202 protected function showUploadForm( $form ) {
203 # Add links if file was previously deleted
204 if ( $this->mDesiredDestName
) {
205 $this->showViewDeletedLinks();
208 if ( $form instanceof HTMLForm
) {
211 $this->getOutput()->addHTML( $form );
217 * Get an UploadForm instance with title and text properly set.
219 * @param $message String: HTML string to add to the form
220 * @param $sessionKey String: session key in case this is a stashed upload
221 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
224 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
226 $form = new UploadForm( array(
227 'watch' => $this->getWatchCheck(),
228 'forreupload' => $this->mForReUpload
,
229 'sessionkey' => $sessionKey,
230 'hideignorewarning' => $hideIgnoreWarning,
231 'destwarningack' => (bool)$this->mDestWarningAck
,
233 'description' => $this->mComment
,
234 'texttop' => $this->uploadFormTextTop
,
235 'textaftersummary' => $this->uploadFormTextAfterSummary
,
236 'destfile' => $this->mDesiredDestName
,
237 ), $this->getContext() );
238 $form->setTitle( $this->getTitle() );
240 # Check the token, but only if necessary
242 !$this->mTokenOk
&& !$this->mCancelUpload
&&
243 ( $this->mUpload
&& $this->mUploadClicked
)
245 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
248 # Give a notice if the user is uploading a file that has been deleted or moved
249 # Note that this is independent from the message 'filewasdeleted' that requires JS
250 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
251 $delNotice = ''; // empty by default
252 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
253 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
255 '', array( 'lim' => 10,
256 'conds' => array( "log_action != 'revision'" ),
257 'showIfEmpty' => false,
258 'msgKey' => array( 'upload-recreate-warning' ) )
261 $form->addPreText( $delNotice );
264 $form->addPreText( '<div id="uploadtext">' .
265 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName
) ) .
267 # Add upload error message
268 $form->addPreText( $message );
271 $uploadFooter = wfMessage( 'uploadfooter' );
272 if ( !$uploadFooter->isDisabled() ) {
273 $form->addPostText( '<div id="mw-upload-footer-message">'
274 . $this->getOutput()->parse( $uploadFooter->plain() ) . "</div>\n" );
281 * Shows the "view X deleted revivions link""
283 protected function showViewDeletedLinks() {
284 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
285 $user = $this->getUser();
286 // Show a subtitle link to deleted revisions (to sysops et al only)
287 if( $title instanceof Title
) {
288 $count = $title->isDeleted();
289 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
291 $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
292 array( 'parse', 'replaceafter' ),
294 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
295 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
298 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
304 * Stashes the upload and shows the main upload form.
306 * Note: only errors that can be handled by changing the name or
307 * description should be redirected here. It should be assumed that the
308 * file itself is sane and has passed UploadBase::verifyFile. This
309 * essentially means that UploadBase::VERIFICATION_ERROR and
310 * UploadBase::EMPTY_FILE should not be passed here.
312 * @param $message String: HTML message to be passed to mainUploadForm
314 protected function showRecoverableUploadError( $message ) {
315 $sessionKey = $this->mUpload
->stashSession();
316 $message = '<h2>' . wfMsgHtml( 'uploaderror' ) . "</h2>\n" .
317 '<div class="error">' . $message . "</div>\n";
319 $form = $this->getUploadForm( $message, $sessionKey );
320 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
321 $this->showUploadForm( $form );
324 * Stashes the upload, shows the main form, but adds an "continue anyway button".
325 * Also checks whether there are actually warnings to display.
327 * @param $warnings Array
328 * @return boolean true if warnings were displayed, false if there are no
329 * warnings and the should continue processing like there was no warning
331 protected function showUploadWarning( $warnings ) {
332 # If there are no warnings, or warnings we can ignore, return early.
333 # mDestWarningAck is set when some javascript has shown the warning
334 # to the user. mForReUpload is set when the user clicks the "upload a
336 if ( !$warnings ||
( count( $warnings ) == 1 &&
337 isset( $warnings['exists'] ) &&
338 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
343 $sessionKey = $this->mUpload
->stashSession();
345 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
346 . '<ul class="warning">';
347 foreach( $warnings as $warning => $args ) {
348 if( $warning == 'exists' ) {
349 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
350 } elseif( $warning == 'duplicate' ) {
351 $msg = self
::getDupeWarning( $args );
352 } elseif( $warning == 'duplicate-archive' ) {
353 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
354 array( Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() ) )
357 if ( $args === true ) {
359 } elseif ( !is_array( $args ) ) {
360 $args = array( $args );
362 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
364 $warningHtml .= $msg;
366 $warningHtml .= "</ul>\n";
367 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
369 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
370 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
371 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
372 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
374 $this->showUploadForm( $form );
376 # Indicate that we showed a form
381 * Show the upload form with error message, but do not stash the file.
383 * @param $message string HTML string
385 protected function showUploadError( $message ) {
386 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
387 '<div class="error">' . $message . "</div>\n";
388 $this->showUploadForm( $this->getUploadForm( $message ) );
393 * Checks are made in SpecialUpload::execute()
395 protected function processUpload() {
396 // Fetch the file if required
397 $status = $this->mUpload
->fetchFile();
398 if( !$status->isOK() ) {
399 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
403 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
404 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
405 // This code path is deprecated. If you want to break upload processing
406 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
407 // and UploadBase::verifyFile.
408 // If you use this hook to break uploading, the user will be returned
409 // an empty form with no error message whatsoever.
413 // Upload verification
414 $details = $this->mUpload
->verifyUpload();
415 if ( $details['status'] != UploadBase
::OK
) {
416 $this->processVerificationError( $details );
420 // Verify permissions for this title
421 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
422 if( $permErrors !== true ) {
423 $code = array_shift( $permErrors[0] );
424 $this->showRecoverableUploadError( wfMsgExt( $code,
425 'parseinline', $permErrors[0] ) );
429 $this->mLocalFile
= $this->mUpload
->getLocalFile();
431 // Check warnings if necessary
432 if( !$this->mIgnoreWarning
) {
433 $warnings = $this->mUpload
->checkWarnings();
434 if( $this->showUploadWarning( $warnings ) ) {
439 // Get the page text if this is not a reupload
440 if( !$this->mForReUpload
) {
441 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
442 $this->mCopyrightStatus
, $this->mCopyrightSource
);
446 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $this->getUser() );
447 if ( !$status->isGood() ) {
448 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
452 // Success, redirect to description page
453 $this->mUploadSuccessful
= true;
454 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
455 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
459 * Get the initial image page text based on a comment and optional file status information
460 * @param $comment string
461 * @param $license string
462 * @param $copyStatus string
463 * @param $source string
466 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
467 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
468 $wgForceUIMsgAsContentMsg = (array) $wgForceUIMsgAsContentMsg;
471 /* These messages are transcluded into the actual text of the description page.
472 * Thus, forcing them as content messages makes the upload to produce an int: template
473 * instead of hardcoding it there in the uploader language.
475 foreach( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
476 if ( in_array( $msgName, $wgForceUIMsgAsContentMsg ) ) {
477 $msg[$msgName] = "{{int:$msgName}}";
479 $msg[$msgName] = wfMsgForContent( $msgName );
483 if ( $wgUseCopyrightUpload ) {
485 if ( $license != '' ) {
486 $licensetxt = '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
488 $pageText = '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n" .
489 '== ' . $msg[ 'filestatus' ] . " ==\n" . $copyStatus . "\n" .
491 '== ' . $msg[ 'filesource' ] . " ==\n" . $source;
493 if ( $license != '' ) {
494 $filedesc = $comment == '' ?
'' : '== ' . $msg[ 'filedesc' ] . " ==\n" . $comment . "\n";
495 $pageText = $filedesc .
496 '== ' . $msg[ 'license-header' ] . " ==\n" . '{{' . $license . '}}' . "\n";
498 $pageText = $comment;
505 * See if we should check the 'watch this page' checkbox on the form
506 * based on the user's preferences and whether we're being asked
507 * to create a new file or update an existing one.
509 * In the case where 'watch edits' is off but 'watch creations' is on,
510 * we'll leave the box unchecked.
512 * Note that the page target can be changed *on the form*, so our check
513 * state can get out of sync.
514 * @return Bool|String
516 protected function getWatchCheck() {
517 if( $this->getUser()->getOption( 'watchdefault' ) ) {
522 $local = wfLocalFile( $this->mDesiredDestName
);
523 if( $local && $local->exists() ) {
524 // We're uploading a new version of an existing file.
525 // No creation, so don't watch it if we're not already.
526 return $local->getTitle()->userIsWatching();
528 // New page should get watched if that's our option.
529 return $this->getUser()->getOption( 'watchcreations' );
535 * Provides output to the user for a result of UploadBase::verifyUpload
537 * @param $details Array: result of UploadBase::verifyUpload
539 protected function processVerificationError( $details ) {
540 global $wgFileExtensions;
542 switch( $details['status'] ) {
544 /** Statuses that only require name changing **/
545 case UploadBase
::MIN_LENGTH_PARTNAME
:
546 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
548 case UploadBase
::ILLEGAL_FILENAME
:
549 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
550 'parseinline', $details['filtered'] ) );
552 case UploadBase
::FILENAME_TOO_LONG
:
553 $this->showRecoverableUploadError( wfMsgHtml( 'filename-toolong' ) );
555 case UploadBase
::FILETYPE_MISSING
:
556 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
559 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
560 $this->showRecoverableUploadError( wfMsgExt( 'windows-nonascii-filename',
564 /** Statuses that require reuploading **/
565 case UploadBase
::EMPTY_FILE
:
566 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
568 case UploadBase
::FILE_TOO_LARGE
:
569 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
571 case UploadBase
::FILETYPE_BADTYPE
:
572 $msg = wfMessage( 'filetype-banned-type' );
573 if ( isset( $details['blacklistedExt'] ) ) {
574 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
576 $msg->params( $details['finalExt'] );
578 $msg->params( $this->getLanguage()->commaList( $wgFileExtensions ),
579 count( $wgFileExtensions ) );
581 // Add PLURAL support for the first parameter. This results
582 // in a bit unlogical parameter sequence, but does not break
584 if ( isset( $details['blacklistedExt'] ) ) {
585 $msg->params( count( $details['blacklistedExt'] ) );
590 $this->showUploadError( $msg->parse() );
592 case UploadBase
::VERIFICATION_ERROR
:
593 unset( $details['status'] );
594 $code = array_shift( $details['details'] );
595 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
597 case UploadBase
::HOOK_ABORTED
:
598 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
599 $args = $details['error'];
600 $error = array_shift( $args );
602 $error = $details['error'];
606 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
609 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
614 * Remove a temporarily kept file stashed by saveTempUploadedFile().
616 * @return Boolean: success
618 protected function unsaveUploadedFile() {
619 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
622 $success = $this->mUpload
->unsaveUploadedFile();
624 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
631 /*** Functions for formatting warnings ***/
634 * Formats a result of UploadBase::getExistsWarning as HTML
635 * This check is static and can be done pre-upload via AJAX
637 * @param $exists Array: the result of UploadBase::getExistsWarning
638 * @return String: empty string if there is no warning or an HTML fragment
640 public static function getExistsWarning( $exists ) {
645 $file = $exists['file'];
646 $filename = $file->getTitle()->getPrefixedText();
649 if( $exists['warning'] == 'exists' ) {
651 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
652 } elseif( $exists['warning'] == 'page-exists' ) {
653 // Page exists but file does not
654 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
655 } elseif ( $exists['warning'] == 'exists-normalized' ) {
656 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
657 $exists['normalizedFile']->getTitle()->getPrefixedText() );
658 } elseif ( $exists['warning'] == 'thumb' ) {
659 // Swapped argument order compared with other messages for backwards compatibility
660 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
661 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
662 } elseif ( $exists['warning'] == 'thumb-name' ) {
663 // Image w/o '180px-' does not exists, but we do not like these filenames
664 $name = $file->getName();
665 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
666 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
667 } elseif ( $exists['warning'] == 'bad-prefix' ) {
668 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
669 } elseif ( $exists['warning'] == 'was-deleted' ) {
670 # If the file existed before and was deleted, warn the user of this
671 $ltitle = SpecialPage
::getTitleFor( 'Log' );
672 $llink = Linker
::linkKnown(
674 wfMsgHtml( 'deletionlog' ),
681 $warning = wfMsgExt( 'filewasdeleted', array( 'parse', 'replaceafter' ), $llink );
688 * Get a list of warnings
690 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
691 * @return Array: list of warning messages
693 public static function ajaxGetExistsWarning( $filename ) {
694 $file = wfFindFile( $filename );
696 // Force local file so we have an object to do further checks against
697 // if there isn't an exact match...
698 $file = wfLocalFile( $filename );
702 $exists = UploadBase
::getExistsWarning( $file );
703 $warning = self
::getExistsWarning( $exists );
704 if ( $warning !== '' ) {
705 $s = "<div>$warning</div>";
712 * Construct a warning and a gallery from an array of duplicate files.
713 * @param $dupes array
716 public static function getDupeWarning( $dupes ) {
720 foreach( $dupes as $file ) {
721 $title = $file->getTitle();
722 $msg .= $title->getPrefixedText() .
723 '|' . $title->getText() . "\n";
725 $msg .= '</gallery>';
727 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
728 $wgOut->parse( $msg ) .
738 * Sub class of HTMLForm that provides the form section of SpecialUpload
740 class UploadForm
extends HTMLForm
{
742 protected $mForReUpload;
743 protected $mSessionKey;
744 protected $mHideIgnoreWarning;
745 protected $mDestWarningAck;
746 protected $mDestFile;
750 protected $mTextAfterSummary;
752 protected $mSourceIds;
754 protected $mMaxFileSize = array();
756 protected $mMaxUploadSize = array();
758 public function __construct( array $options = array(), IContextSource
$context = null ) {
759 $this->mWatch
= !empty( $options['watch'] );
760 $this->mForReUpload
= !empty( $options['forreupload'] );
761 $this->mSessionKey
= isset( $options['sessionkey'] )
762 ?
$options['sessionkey'] : '';
763 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
764 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
765 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
767 $this->mComment
= isset( $options['description'] ) ?
768 $options['description'] : '';
770 $this->mTextTop
= isset( $options['texttop'] )
771 ?
$options['texttop'] : '';
773 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
774 ?
$options['textaftersummary'] : '';
776 $sourceDescriptor = $this->getSourceSection();
777 $descriptor = $sourceDescriptor
778 +
$this->getDescriptionSection()
779 +
$this->getOptionsSection();
781 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
782 parent
::__construct( $descriptor, $context, 'upload' );
784 # Set some form properties
785 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
786 $this->setSubmitName( 'wpUpload' );
787 # Used message keys: 'accesskey-upload', 'tooltip-upload'
788 $this->setSubmitTooltip( 'upload' );
789 $this->setId( 'mw-upload-form' );
791 # Build a list of IDs for javascript insertion
792 $this->mSourceIds
= array();
793 foreach ( $sourceDescriptor as $field ) {
794 if ( !empty( $field['id'] ) ) {
795 $this->mSourceIds
[] = $field['id'];
802 * Get the descriptor of the fieldset that contains the file source
803 * selection. The section is 'source'
805 * @return Array: descriptor array
807 protected function getSourceSection() {
808 if ( $this->mSessionKey
) {
810 'SessionKey' => array(
812 'default' => $this->mSessionKey
,
814 'SourceType' => array(
816 'default' => 'Stash',
821 $canUploadByUrl = UploadFromUrl
::isEnabled() && UploadFromUrl
::isAllowed( $this->getUser() );
822 $radio = $canUploadByUrl;
823 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
825 $descriptor = array();
826 if ( $this->mTextTop
) {
827 $descriptor['UploadFormTextTop'] = array(
829 'section' => 'source',
830 'default' => $this->mTextTop
,
835 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
836 # Limit to upload_max_filesize unless we are running under HipHop and
837 # that setting doesn't exist
838 if ( !wfIsHipHop() ) {
839 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
840 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ) );
843 $descriptor['UploadFile'] = array(
844 'class' => 'UploadSourceField',
845 'section' => 'source',
847 'id' => 'wpUploadFile',
848 'label-message' => 'sourcefilename',
849 'upload-type' => 'File',
851 'help' => wfMsgExt( 'upload-maxfilesize',
852 array( 'parseinline', 'escapenoentities' ),
853 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
854 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
855 'checked' => $selectedSourceType == 'file',
857 if ( $canUploadByUrl ) {
858 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
859 $descriptor['UploadFileURL'] = array(
860 'class' => 'UploadSourceField',
861 'section' => 'source',
862 'id' => 'wpUploadFileURL',
863 'label-message' => 'sourceurl',
864 'upload-type' => 'url',
866 'help' => wfMsgExt( 'upload-maxfilesize',
867 array( 'parseinline', 'escapenoentities' ),
868 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
869 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
870 'checked' => $selectedSourceType == 'url',
873 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
875 $descriptor['Extensions'] = array(
877 'section' => 'source',
878 'default' => $this->getExtensionsMessage(),
885 * Get the messages indicating which extensions are preferred and prohibitted.
887 * @return String: HTML string containing the message
889 protected function getExtensionsMessage() {
890 # Print a list of allowed file extensions, if so configured. We ignore
891 # MIME type here, it's incomprehensible to most people and too long.
892 global $wgCheckFileExtensions, $wgStrictFileExtensions,
893 $wgFileExtensions, $wgFileBlacklist;
895 if( $wgCheckFileExtensions ) {
896 if( $wgStrictFileExtensions ) {
897 # Everything not permitted is banned
899 '<div id="mw-upload-permitted">' .
900 wfMsgExt( 'upload-permitted', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) ) .
903 # We have to list both preferred and prohibited
905 '<div id="mw-upload-preferred">' .
906 wfMsgExt( 'upload-preferred', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) ) .
908 '<div id="mw-upload-prohibited">' .
909 wfMsgExt( 'upload-prohibited', 'parse', $this->getContext()->getLanguage()->commaList( $wgFileBlacklist ) ) .
913 # Everything is permitted.
914 $extensionsList = '';
916 return $extensionsList;
920 * Get the descriptor of the fieldset that contains the file description
921 * input. The section is 'description'
923 * @return Array: descriptor array
925 protected function getDescriptionSection() {
926 if ( $this->mSessionKey
) {
927 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
929 $file = $stash->getFile( $this->mSessionKey
);
930 } catch ( MWException
$e ) {
936 $mto = $file->transform( array( 'width' => 120 ) );
937 $this->addHeaderText(
938 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
939 Html
::element( 'img', array(
940 'src' => $mto->getUrl(),
941 'class' => 'thumbimage',
942 ) ) . '</div>', 'description' );
949 'section' => 'description',
950 'id' => 'wpDestFile',
951 'label-message' => 'destfilename',
953 'default' => $this->mDestFile
,
954 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
955 'nodata' => strval( $this->mDestFile
) !== '',
957 'UploadDescription' => array(
958 'type' => 'textarea',
959 'section' => 'description',
960 'id' => 'wpUploadDescription',
961 'label-message' => $this->mForReUpload
962 ?
'filereuploadsummary'
963 : 'fileuploadsummary',
964 'default' => $this->mComment
,
965 'cols' => intval( $this->getUser()->getOption( 'cols' ) ),
969 if ( $this->mTextAfterSummary
) {
970 $descriptor['UploadFormTextAfterSummary'] = array(
972 'section' => 'description',
973 'default' => $this->mTextAfterSummary
,
978 $descriptor +
= array(
979 'EditTools' => array(
980 'type' => 'edittools',
981 'section' => 'description',
982 'message' => 'edittools-upload',
986 if ( $this->mForReUpload
) {
987 $descriptor['DestFile']['readonly'] = true;
989 $descriptor['License'] = array(
991 'class' => 'Licenses',
992 'section' => 'description',
994 'label-message' => 'license',
998 global $wgUseCopyrightUpload;
999 if ( $wgUseCopyrightUpload ) {
1000 $descriptor['UploadCopyStatus'] = array(
1002 'section' => 'description',
1003 'id' => 'wpUploadCopyStatus',
1004 'label-message' => 'filestatus',
1006 $descriptor['UploadSource'] = array(
1008 'section' => 'description',
1009 'id' => 'wpUploadSource',
1010 'label-message' => 'filesource',
1018 * Get the descriptor of the fieldset that contains the upload options,
1019 * such as "watch this file". The section is 'options'
1021 * @return Array: descriptor array
1023 protected function getOptionsSection() {
1024 $user = $this->getUser();
1025 if ( $user->isLoggedIn() ) {
1026 $descriptor = array(
1027 'Watchthis' => array(
1029 'id' => 'wpWatchthis',
1030 'label-message' => 'watchthisupload',
1031 'section' => 'options',
1032 'default' => $user->getOption( 'watchcreations' ),
1036 if ( !$this->mHideIgnoreWarning
) {
1037 $descriptor['IgnoreWarning'] = array(
1039 'id' => 'wpIgnoreWarning',
1040 'label-message' => 'ignorewarnings',
1041 'section' => 'options',
1045 $descriptor['DestFileWarningAck'] = array(
1047 'id' => 'wpDestFileWarningAck',
1048 'default' => $this->mDestWarningAck ?
'1' : '',
1051 if ( $this->mForReUpload
) {
1052 $descriptor['ForReUpload'] = array(
1054 'id' => 'wpForReUpload',
1063 * Add the upload JS and show the form.
1065 public function show() {
1066 $this->addUploadJS();
1071 * Add upload JS to the OutputPage
1073 protected function addUploadJS() {
1074 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1076 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1077 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1078 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1080 $scriptVars = array(
1081 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1082 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1083 'wgUploadAutoFill' => !$this->mForReUpload
&&
1084 // If we received mDestFile from the request, don't autofill
1085 // the wpDestFile textbox
1086 $this->mDestFile
=== '',
1087 'wgUploadSourceIds' => $this->mSourceIds
,
1088 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1089 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1090 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1093 $out = $this->getOutput();
1094 $out->addJsConfigVars( $scriptVars );
1097 $out->addModules( array(
1098 'mediawiki.action.edit', // For <charinsert> support
1099 'mediawiki.legacy.upload', // Old form stuff...
1100 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1105 * Empty function; submission is handled elsewhere.
1107 * @return bool false
1109 function trySubmit() {
1116 * A form field that contains a radio box in the label
1118 class UploadSourceField
extends HTMLTextField
{
1121 * @param $cellAttributes array
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 );
1147 function getSize() {
1148 return isset( $this->mParams
['size'] )
1149 ?
$this->mParams
['size']