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->mLicense
= $request->getText( 'wpLicense' );
98 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
99 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
100 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
101 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
102 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
103 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
105 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
107 $commentDefault = '';
108 $commentMsg = wfMessage( 'upload-default-description' )->inContentLanguage();
109 if ( !$this->mForReUpload
&& !$commentMsg->isDisabled() ) {
110 $commentDefault = $commentMsg->plain();
112 $this->mComment
= $request->getText( 'wpUploadDescription', $commentDefault );
114 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
115 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
117 // If it was posted check for the token (no remote POST'ing with user credentials)
118 $token = $request->getVal( 'wpEditToken' );
119 $this->mTokenOk
= $this->getUser()->matchEditToken( $token );
121 $this->uploadFormTextTop
= '';
122 $this->uploadFormTextAfterSummary
= '';
126 * This page can be shown if uploading is enabled.
127 * Handle permission checking elsewhere in order to be able to show
128 * custom error messages.
130 * @param $user User object
133 public function userCanExecute( User
$user ) {
134 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
138 * Special page entry point
140 public function execute( $par ) {
142 $this->outputHeader();
144 # Check uploading enabled
145 if ( !UploadBase
::isEnabled() ) {
146 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
150 $user = $this->getUser();
151 $permissionRequired = UploadBase
::isAllowed( $user );
152 if ( $permissionRequired !== true ) {
153 throw new PermissionsError( $permissionRequired );
157 if ( $user->isBlocked() ) {
158 throw new UserBlockedError( $user->getBlock() );
161 # Check whether we actually want to allow changing stuff
162 $this->checkReadOnly();
164 $this->loadRequest();
166 # Unsave the temporary file in case this was a cancelled upload
167 if ( $this->mCancelUpload
) {
168 if ( !$this->unsaveUploadedFile() ) {
169 # Something went wrong, so unsaveUploadedFile showed a warning
174 # Process upload or show a form
176 $this->mTokenOk
&& !$this->mCancelUpload
&&
177 ( $this->mUpload
&& $this->mUploadClicked
)
179 $this->processUpload();
181 # Backwards compatibility hook
182 if ( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
183 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
186 $this->showUploadForm( $this->getUploadForm() );
190 if ( $this->mUpload
) {
191 $this->mUpload
->cleanupTempFile();
196 * Show the main upload form
198 * @param $form Mixed: an HTMLForm instance or HTML string to show
200 protected function showUploadForm( $form ) {
201 # Add links if file was previously deleted
202 if ( $this->mDesiredDestName
) {
203 $this->showViewDeletedLinks();
206 if ( $form instanceof HTMLForm
) {
209 $this->getOutput()->addHTML( $form );
215 * Get an UploadForm instance with title and text properly set.
217 * @param string $message HTML string to add to the form
218 * @param string $sessionKey session key in case this is a stashed upload
219 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
222 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
224 $context = new DerivativeContext( $this->getContext() );
225 $context->setTitle( $this->getTitle() ); // Remove subpage
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
,
239 # Check the token, but only if necessary
241 !$this->mTokenOk
&& !$this->mCancelUpload
&&
242 ( $this->mUpload
&& $this->mUploadClicked
)
244 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
247 # Give a notice if the user is uploading a file that has been deleted or moved
248 # Note that this is independent from the message 'filewasdeleted' that requires JS
249 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
250 $delNotice = ''; // empty by default
251 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
252 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
254 '', array( 'lim' => 10,
255 'conds' => array( "log_action != 'revision'" ),
256 'showIfEmpty' => false,
257 'msgKey' => array( 'upload-recreate-warning' ) )
260 $form->addPreText( $delNotice );
263 $form->addPreText( '<div id="uploadtext">' .
264 $this->msg( 'uploadtext', array( $this->mDesiredDestName
) )->parseAsBlock() .
266 # Add upload error message
267 $form->addPreText( $message );
270 $uploadFooter = $this->msg( 'uploadfooter' );
271 if ( !$uploadFooter->isDisabled() ) {
272 $form->addPostText( '<div id="mw-upload-footer-message">'
273 . $uploadFooter->parseAsBlock() . "</div>\n" );
280 * Shows the "view X deleted revivions link""
282 protected function showViewDeletedLinks() {
283 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
284 $user = $this->getUser();
285 // Show a subtitle link to deleted revisions (to sysops et al only)
286 if ( $title instanceof Title
) {
287 $count = $title->isDeleted();
288 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
289 $restorelink = Linker
::linkKnown(
290 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
291 $this->msg( 'restorelink' )->numParams( $count )->escaped()
293 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
294 ->rawParams( $restorelink )->parseAsBlock();
295 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
301 * Stashes the upload and shows the main upload form.
303 * Note: only errors that can be handled by changing the name or
304 * description should be redirected here. It should be assumed that the
305 * file itself is sane and has passed UploadBase::verifyFile. This
306 * essentially means that UploadBase::VERIFICATION_ERROR and
307 * UploadBase::EMPTY_FILE should not be passed here.
309 * @param string $message HTML message to be passed to mainUploadForm
311 protected function showRecoverableUploadError( $message ) {
312 $sessionKey = $this->mUpload
->stashSession();
313 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
314 '<div class="error">' . $message . "</div>\n";
316 $form = $this->getUploadForm( $message, $sessionKey );
317 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
318 $this->showUploadForm( $form );
321 * Stashes the upload, shows the main form, but adds a "continue anyway button".
322 * Also checks whether there are actually warnings to display.
324 * @param $warnings Array
325 * @return boolean true if warnings were displayed, false if there are no
326 * warnings and it should continue processing
328 protected function showUploadWarning( $warnings ) {
329 # If there are no warnings, or warnings we can ignore, return early.
330 # mDestWarningAck is set when some javascript has shown the warning
331 # to the user. mForReUpload is set when the user clicks the "upload a
333 if ( !$warnings ||
( count( $warnings ) == 1 &&
334 isset( $warnings['exists'] ) &&
335 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
340 $sessionKey = $this->mUpload
->stashSession();
342 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
343 . '<ul class="warning">';
344 foreach ( $warnings as $warning => $args ) {
345 if ( $warning == 'badfilename' ) {
346 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
348 if ( $warning == 'exists' ) {
349 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
350 } elseif ( $warning == 'duplicate' ) {
351 $msg = $this->getDupeWarning( $args );
352 } elseif ( $warning == 'duplicate-archive' ) {
353 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
354 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
357 if ( $args === true ) {
359 } elseif ( !is_array( $args ) ) {
360 $args = array( $args );
362 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
364 $warningHtml .= $msg;
366 $warningHtml .= "</ul>\n";
367 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
369 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
370 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
371 $form->addButton( 'wpUploadIgnoreWarning', $this->msg( 'ignorewarning' )->text() );
372 $form->addButton( 'wpCancelUpload', $this->msg( 'reuploaddesc' )->text() );
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 string $message HTML string
385 protected function showUploadError( $message ) {
386 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</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( $this->msg( $code, $permErrors[0] )->parse() );
428 $this->mLocalFile
= $this->mUpload
->getLocalFile();
430 // Check warnings if necessary
431 if ( !$this->mIgnoreWarning
) {
432 $warnings = $this->mUpload
->checkWarnings();
433 if ( $this->showUploadWarning( $warnings ) ) {
438 // Get the page text if this is not a reupload
439 if ( !$this->mForReUpload
) {
440 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
441 $this->mCopyrightStatus
, $this->mCopyrightSource
);
445 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $this->getUser() );
446 if ( !$status->isGood() ) {
447 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
451 // Success, redirect to description page
452 $this->mUploadSuccessful
= true;
453 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
454 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
458 * Get the initial image page text based on a comment and optional file status information
459 * @param $comment string
460 * @param $license string
461 * @param $copyStatus string
462 * @param $source string
465 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
466 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
469 /* These messages are transcluded into the actual text of the description page.
470 * Thus, forcing them as content messages makes the upload to produce an int: template
471 * instead of hardcoding it there in the uploader language.
473 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
474 if ( in_array( $msgName, (array)$wgForceUIMsgAsContentMsg ) ) {
475 $msg[$msgName] = "{{int:$msgName}}";
477 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
481 if ( $wgUseCopyrightUpload ) {
483 if ( $license != '' ) {
484 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
486 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
487 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
489 '== ' . $msg['filesource'] . " ==\n" . $source;
491 if ( $license != '' ) {
492 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
493 $pageText = $filedesc .
494 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
496 $pageText = $comment;
503 * See if we should check the 'watch this page' checkbox on the form
504 * based on the user's preferences and whether we're being asked
505 * to create a new file or update an existing one.
507 * In the case where 'watch edits' is off but 'watch creations' is on,
508 * we'll leave the box unchecked.
510 * Note that the page target can be changed *on the form*, so our check
511 * state can get out of sync.
512 * @return Bool|String
514 protected function getWatchCheck() {
515 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
520 $local = wfLocalFile( $this->mDesiredDestName
);
521 if ( $local && $local->exists() ) {
522 // We're uploading a new version of an existing file.
523 // No creation, so don't watch it if we're not already.
524 return $this->getUser()->isWatched( $local->getTitle() );
526 // New page should get watched if that's our option.
527 return $this->getUser()->getOption( 'watchcreations' );
532 * Provides output to the user for a result of UploadBase::verifyUpload
534 * @param array $details result of UploadBase::verifyUpload
535 * @throws MWException
537 protected function processVerificationError( $details ) {
538 global $wgFileExtensions;
540 switch ( $details['status'] ) {
542 /** Statuses that only require name changing **/
543 case UploadBase
::MIN_LENGTH_PARTNAME
:
544 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
546 case UploadBase
::ILLEGAL_FILENAME
:
547 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
548 $details['filtered'] )->parse() );
550 case UploadBase
::FILENAME_TOO_LONG
:
551 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
553 case UploadBase
::FILETYPE_MISSING
:
554 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
556 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
557 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
560 /** Statuses that require reuploading **/
561 case UploadBase
::EMPTY_FILE
:
562 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
564 case UploadBase
::FILE_TOO_LARGE
:
565 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
567 case UploadBase
::FILETYPE_BADTYPE
:
568 $msg = $this->msg( 'filetype-banned-type' );
569 if ( isset( $details['blacklistedExt'] ) ) {
570 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
572 $msg->params( $details['finalExt'] );
574 $extensions = array_unique( $wgFileExtensions );
575 $msg->params( $this->getLanguage()->commaList( $extensions ),
576 count( $extensions ) );
578 // Add PLURAL support for the first parameter. This results
579 // in a bit unlogical parameter sequence, but does not break
581 if ( isset( $details['blacklistedExt'] ) ) {
582 $msg->params( count( $details['blacklistedExt'] ) );
587 $this->showUploadError( $msg->parse() );
589 case UploadBase
::VERIFICATION_ERROR
:
590 unset( $details['status'] );
591 $code = array_shift( $details['details'] );
592 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
594 case UploadBase
::HOOK_ABORTED
:
595 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
596 $args = $details['error'];
597 $error = array_shift( $args );
599 $error = $details['error'];
603 $this->showUploadError( $this->msg( $error, $args )->parse() );
606 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
611 * Remove a temporarily kept file stashed by saveTempUploadedFile().
613 * @return Boolean: success
615 protected function unsaveUploadedFile() {
616 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
619 $success = $this->mUpload
->unsaveUploadedFile();
621 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
628 /*** Functions for formatting warnings ***/
631 * Formats a result of UploadBase::getExistsWarning as HTML
632 * This check is static and can be done pre-upload via AJAX
634 * @param array $exists the result of UploadBase::getExistsWarning
635 * @return String: empty string if there is no warning or an HTML fragment
637 public static function getExistsWarning( $exists ) {
642 $file = $exists['file'];
643 $filename = $file->getTitle()->getPrefixedText();
646 if ( $exists['warning'] == 'exists' ) {
648 $warning = wfMessage( 'fileexists', $filename )->parse();
649 } elseif ( $exists['warning'] == 'page-exists' ) {
650 // Page exists but file does not
651 $warning = wfMessage( 'filepageexists', $filename )->parse();
652 } elseif ( $exists['warning'] == 'exists-normalized' ) {
653 $warning = wfMessage( 'fileexists-extension', $filename,
654 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
655 } elseif ( $exists['warning'] == 'thumb' ) {
656 // Swapped argument order compared with other messages for backwards compatibility
657 $warning = wfMessage( 'fileexists-thumbnail-yes',
658 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
659 } elseif ( $exists['warning'] == 'thumb-name' ) {
660 // Image w/o '180px-' does not exists, but we do not like these filenames
661 $name = $file->getName();
662 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
663 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
664 } elseif ( $exists['warning'] == 'bad-prefix' ) {
665 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
666 } elseif ( $exists['warning'] == 'was-deleted' ) {
667 # If the file existed before and was deleted, warn the user of this
668 $ltitle = SpecialPage
::getTitleFor( 'Log' );
669 $llink = Linker
::linkKnown(
671 wfMessage( 'deletionlog' )->escaped(),
678 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
685 * Construct a warning and a gallery from an array of duplicate files.
686 * @param $dupes array
689 public function getDupeWarning( $dupes ) {
694 $gallery = ImageGalleryBase
::factory();
695 $gallery->setContext( $this->getContext() );
696 $gallery->setShowBytes( false );
697 foreach ( $dupes as $file ) {
698 $gallery->add( $file->getTitle() );
701 wfMessage( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
702 $gallery->toHtml() . "</li>\n";
705 protected function getGroupName() {
711 * Sub class of HTMLForm that provides the form section of SpecialUpload
713 class UploadForm
extends HTMLForm
{
715 protected $mForReUpload;
716 protected $mSessionKey;
717 protected $mHideIgnoreWarning;
718 protected $mDestWarningAck;
719 protected $mDestFile;
723 protected $mTextAfterSummary;
725 protected $mSourceIds;
727 protected $mMaxFileSize = array();
729 protected $mMaxUploadSize = array();
731 public function __construct( array $options = array(), IContextSource
$context = null ) {
732 $this->mWatch
= !empty( $options['watch'] );
733 $this->mForReUpload
= !empty( $options['forreupload'] );
734 $this->mSessionKey
= isset( $options['sessionkey'] )
735 ?
$options['sessionkey'] : '';
736 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
737 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
738 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
740 $this->mComment
= isset( $options['description'] ) ?
741 $options['description'] : '';
743 $this->mTextTop
= isset( $options['texttop'] )
744 ?
$options['texttop'] : '';
746 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
747 ?
$options['textaftersummary'] : '';
749 $sourceDescriptor = $this->getSourceSection();
750 $descriptor = $sourceDescriptor
751 +
$this->getDescriptionSection()
752 +
$this->getOptionsSection();
754 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
755 parent
::__construct( $descriptor, $context, 'upload' );
757 # Set some form properties
758 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
759 $this->setSubmitName( 'wpUpload' );
760 # Used message keys: 'accesskey-upload', 'tooltip-upload'
761 $this->setSubmitTooltip( 'upload' );
762 $this->setId( 'mw-upload-form' );
764 # Build a list of IDs for javascript insertion
765 $this->mSourceIds
= array();
766 foreach ( $sourceDescriptor as $field ) {
767 if ( !empty( $field['id'] ) ) {
768 $this->mSourceIds
[] = $field['id'];
775 * Get the descriptor of the fieldset that contains the file source
776 * selection. The section is 'source'
778 * @return Array: descriptor array
780 protected function getSourceSection() {
781 global $wgCopyUploadsFromSpecialUpload;
783 if ( $this->mSessionKey
) {
785 'SessionKey' => array(
787 'default' => $this->mSessionKey
,
789 'SourceType' => array(
791 'default' => 'Stash',
796 $canUploadByUrl = UploadFromUrl
::isEnabled()
797 && UploadFromUrl
::isAllowed( $this->getUser() )
798 && $wgCopyUploadsFromSpecialUpload;
799 $radio = $canUploadByUrl;
800 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
802 $descriptor = array();
803 if ( $this->mTextTop
) {
804 $descriptor['UploadFormTextTop'] = array(
806 'section' => 'source',
807 'default' => $this->mTextTop
,
812 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
813 # Limit to upload_max_filesize unless we are running under HipHop and
814 # that setting doesn't exist
815 if ( !wfIsHipHop() ) {
816 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
817 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
818 wfShorthandToInteger( ini_get( 'post_max_size' ) )
822 $descriptor['UploadFile'] = array(
823 'class' => 'UploadSourceField',
824 'section' => 'source',
826 'id' => 'wpUploadFile',
827 'label-message' => 'sourcefilename',
828 'upload-type' => 'File',
830 'help' => $this->msg( 'upload-maxfilesize',
831 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] ) )
833 $this->msg( 'word-separator' )->escaped() .
834 $this->msg( 'upload_source_file' )->escaped(),
835 'checked' => $selectedSourceType == 'file',
838 if ( $canUploadByUrl ) {
839 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
840 $descriptor['UploadFileURL'] = array(
841 'class' => 'UploadSourceField',
842 'section' => 'source',
843 'id' => 'wpUploadFileURL',
844 'label-message' => 'sourceurl',
845 'upload-type' => 'url',
847 'help' => $this->msg( 'upload-maxfilesize',
848 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] ) )
850 $this->msg( 'word-separator' )->escaped() .
851 $this->msg( 'upload_source_url' )->escaped(),
852 'checked' => $selectedSourceType == 'url',
855 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
857 $descriptor['Extensions'] = array(
859 'section' => 'source',
860 'default' => $this->getExtensionsMessage(),
867 * Get the messages indicating which extensions are preferred and prohibitted.
869 * @return String: HTML string containing the message
871 protected function getExtensionsMessage() {
872 # Print a list of allowed file extensions, if so configured. We ignore
873 # MIME type here, it's incomprehensible to most people and too long.
874 global $wgCheckFileExtensions, $wgStrictFileExtensions,
875 $wgFileExtensions, $wgFileBlacklist;
877 if ( $wgCheckFileExtensions ) {
878 if ( $wgStrictFileExtensions ) {
879 # Everything not permitted is banned
881 '<div id="mw-upload-permitted">' .
882 $this->msg( 'upload-permitted', $this->getContext()->getLanguage()->commaList( array_unique( $wgFileExtensions ) ) )->parseAsBlock() .
885 # We have to list both preferred and prohibited
887 '<div id="mw-upload-preferred">' .
888 $this->msg( 'upload-preferred', $this->getContext()->getLanguage()->commaList( array_unique( $wgFileExtensions ) ) )->parseAsBlock() .
890 '<div id="mw-upload-prohibited">' .
891 $this->msg( 'upload-prohibited', $this->getContext()->getLanguage()->commaList( array_unique( $wgFileBlacklist ) ) )->parseAsBlock() .
895 # Everything is permitted.
896 $extensionsList = '';
898 return $extensionsList;
902 * Get the descriptor of the fieldset that contains the file description
903 * input. The section is 'description'
905 * @return Array: descriptor array
907 protected function getDescriptionSection() {
908 if ( $this->mSessionKey
) {
909 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
911 $file = $stash->getFile( $this->mSessionKey
);
912 } catch ( MWException
$e ) {
918 $mto = $file->transform( array( 'width' => 120 ) );
919 $this->addHeaderText(
920 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
921 Html
::element( 'img', array(
922 'src' => $mto->getUrl(),
923 'class' => 'thumbimage',
924 ) ) . '</div>', 'description' );
931 'section' => 'description',
932 'id' => 'wpDestFile',
933 'label-message' => 'destfilename',
935 'default' => $this->mDestFile
,
936 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
937 'nodata' => strval( $this->mDestFile
) !== '',
939 'UploadDescription' => array(
940 'type' => 'textarea',
941 'section' => 'description',
942 'id' => 'wpUploadDescription',
943 'label-message' => $this->mForReUpload
944 ?
'filereuploadsummary'
945 : 'fileuploadsummary',
946 'default' => $this->mComment
,
947 'cols' => $this->getUser()->getIntOption( 'cols' ),
951 if ( $this->mTextAfterSummary
) {
952 $descriptor['UploadFormTextAfterSummary'] = array(
954 'section' => 'description',
955 'default' => $this->mTextAfterSummary
,
960 $descriptor +
= array(
961 'EditTools' => array(
962 'type' => 'edittools',
963 'section' => 'description',
964 'message' => 'edittools-upload',
968 if ( $this->mForReUpload
) {
969 $descriptor['DestFile']['readonly'] = true;
971 $descriptor['License'] = array(
973 'class' => 'Licenses',
974 'section' => 'description',
976 'label-message' => 'license',
980 global $wgUseCopyrightUpload;
981 if ( $wgUseCopyrightUpload ) {
982 $descriptor['UploadCopyStatus'] = array(
984 'section' => 'description',
985 'id' => 'wpUploadCopyStatus',
986 'label-message' => 'filestatus',
988 $descriptor['UploadSource'] = array(
990 'section' => 'description',
991 'id' => 'wpUploadSource',
992 'label-message' => 'filesource',
1000 * Get the descriptor of the fieldset that contains the upload options,
1001 * such as "watch this file". The section is 'options'
1003 * @return Array: descriptor array
1005 protected function getOptionsSection() {
1006 $user = $this->getUser();
1007 if ( $user->isLoggedIn() ) {
1008 $descriptor = array(
1009 'Watchthis' => array(
1011 'id' => 'wpWatchthis',
1012 'label-message' => 'watchthisupload',
1013 'section' => 'options',
1014 'default' => $user->getOption( 'watchcreations' ),
1018 if ( !$this->mHideIgnoreWarning
) {
1019 $descriptor['IgnoreWarning'] = array(
1021 'id' => 'wpIgnoreWarning',
1022 'label-message' => 'ignorewarnings',
1023 'section' => 'options',
1027 $descriptor['DestFileWarningAck'] = array(
1029 'id' => 'wpDestFileWarningAck',
1030 'default' => $this->mDestWarningAck ?
'1' : '',
1033 if ( $this->mForReUpload
) {
1034 $descriptor['ForReUpload'] = array(
1036 'id' => 'wpForReUpload',
1045 * Add the upload JS and show the form.
1047 public function show() {
1048 $this->addUploadJS();
1053 * Add upload JS to the OutputPage
1055 protected function addUploadJS() {
1056 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1058 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1059 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1060 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1062 $scriptVars = array(
1063 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1064 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1065 'wgUploadAutoFill' => !$this->mForReUpload
&&
1066 // If we received mDestFile from the request, don't autofill
1067 // the wpDestFile textbox
1068 $this->mDestFile
=== '',
1069 'wgUploadSourceIds' => $this->mSourceIds
,
1070 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1071 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1072 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1075 $out = $this->getOutput();
1076 $out->addJsConfigVars( $scriptVars );
1078 $out->addModules( array(
1079 'mediawiki.action.edit', // For <charinsert> support
1080 'mediawiki.legacy.upload', // Old form stuff...
1081 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1086 * Empty function; submission is handled elsewhere.
1088 * @return bool false
1090 function trySubmit() {
1097 * A form field that contains a radio box in the label
1099 class UploadSourceField
extends HTMLTextField
{
1102 * @param $cellAttributes array
1105 function getLabelHtml( $cellAttributes = array() ) {
1106 $id = $this->mParams
['id'];
1107 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1109 if ( !empty( $this->mParams
['radio'] ) ) {
1111 'name' => 'wpSourceType',
1114 'value' => $this->mParams
['upload-type'],
1116 if ( !empty( $this->mParams
['checked'] ) ) {
1117 $attribs['checked'] = 'checked';
1119 $label .= Html
::element( 'input', $attribs );
1122 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1128 function getSize() {
1129 return isset( $this->mParams
['size'] )
1130 ?
$this->mParams
['size']