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 $form = new UploadForm( array(
225 'watch' => $this->getWatchCheck(),
226 'forreupload' => $this->mForReUpload
,
227 'sessionkey' => $sessionKey,
228 'hideignorewarning' => $hideIgnoreWarning,
229 'destwarningack' => (bool)$this->mDestWarningAck
,
231 'description' => $this->mComment
,
232 'texttop' => $this->uploadFormTextTop
,
233 'textaftersummary' => $this->uploadFormTextAfterSummary
,
234 'destfile' => $this->mDesiredDestName
,
235 ), $this->getContext() );
236 $form->setTitle( $this->getTitle() );
238 # Check the token, but only if necessary
240 !$this->mTokenOk
&& !$this->mCancelUpload
&&
241 ( $this->mUpload
&& $this->mUploadClicked
)
243 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
246 # Give a notice if the user is uploading a file that has been deleted or moved
247 # Note that this is independent from the message 'filewasdeleted' that requires JS
248 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
249 $delNotice = ''; // empty by default
250 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
251 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
253 '', array( 'lim' => 10,
254 'conds' => array( "log_action != 'revision'" ),
255 'showIfEmpty' => false,
256 'msgKey' => array( 'upload-recreate-warning' ) )
259 $form->addPreText( $delNotice );
262 $form->addPreText( '<div id="uploadtext">' .
263 $this->msg( 'uploadtext', array( $this->mDesiredDestName
) )->parseAsBlock() .
265 # Add upload error message
266 $form->addPreText( $message );
269 $uploadFooter = $this->msg( 'uploadfooter' );
270 if ( !$uploadFooter->isDisabled() ) {
271 $form->addPostText( '<div id="mw-upload-footer-message">'
272 . $uploadFooter->parseAsBlock() . "</div>\n" );
279 * Shows the "view X deleted revivions link""
281 protected function showViewDeletedLinks() {
282 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
283 $user = $this->getUser();
284 // Show a subtitle link to deleted revisions (to sysops et al only)
285 if ( $title instanceof Title
) {
286 $count = $title->isDeleted();
287 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
288 $restorelink = Linker
::linkKnown(
289 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
290 $this->msg( 'restorelink' )->numParams( $count )->escaped()
292 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
293 ->rawParams( $restorelink )->parseAsBlock();
294 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
300 * Stashes the upload and shows the main upload form.
302 * Note: only errors that can be handled by changing the name or
303 * description should be redirected here. It should be assumed that the
304 * file itself is sane and has passed UploadBase::verifyFile. This
305 * essentially means that UploadBase::VERIFICATION_ERROR and
306 * UploadBase::EMPTY_FILE should not be passed here.
308 * @param string $message HTML message to be passed to mainUploadForm
310 protected function showRecoverableUploadError( $message ) {
311 $sessionKey = $this->mUpload
->stashSession();
312 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
313 '<div class="error">' . $message . "</div>\n";
315 $form = $this->getUploadForm( $message, $sessionKey );
316 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
317 $this->showUploadForm( $form );
320 * Stashes the upload, shows the main form, but adds a "continue anyway button".
321 * Also checks whether there are actually warnings to display.
323 * @param $warnings Array
324 * @return boolean true if warnings were displayed, false if there are no
325 * warnings and it should continue processing
327 protected function showUploadWarning( $warnings ) {
328 # If there are no warnings, or warnings we can ignore, return early.
329 # mDestWarningAck is set when some javascript has shown the warning
330 # to the user. mForReUpload is set when the user clicks the "upload a
332 if ( !$warnings ||
( count( $warnings ) == 1 &&
333 isset( $warnings['exists'] ) &&
334 ( $this->mDestWarningAck ||
$this->mForReUpload
) ) )
339 $sessionKey = $this->mUpload
->stashSession();
341 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
342 . '<ul class="warning">';
343 foreach ( $warnings as $warning => $args ) {
344 if ( $warning == 'badfilename' ) {
345 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
347 if ( $warning == 'exists' ) {
348 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
349 } elseif ( $warning == 'duplicate' ) {
350 $msg = $this->getDupeWarning( $args );
351 } elseif ( $warning == 'duplicate-archive' ) {
352 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
353 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
356 if ( $args === true ) {
358 } elseif ( !is_array( $args ) ) {
359 $args = array( $args );
361 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
363 $warningHtml .= $msg;
365 $warningHtml .= "</ul>\n";
366 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
368 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
369 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
370 $form->addButton( 'wpUploadIgnoreWarning', $this->msg( 'ignorewarning' )->text() );
371 $form->addButton( 'wpCancelUpload', $this->msg( 'reuploaddesc' )->text() );
373 $this->showUploadForm( $form );
375 # Indicate that we showed a form
380 * Show the upload form with error message, but do not stash the file.
382 * @param string $message HTML string
384 protected function showUploadError( $message ) {
385 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
386 '<div class="error">' . $message . "</div>\n";
387 $this->showUploadForm( $this->getUploadForm( $message ) );
392 * Checks are made in SpecialUpload::execute()
394 protected function processUpload() {
395 // Fetch the file if required
396 $status = $this->mUpload
->fetchFile();
397 if ( !$status->isOK() ) {
398 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
402 if ( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
403 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
404 // This code path is deprecated. If you want to break upload processing
405 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
406 // and UploadBase::verifyFile.
407 // If you use this hook to break uploading, the user will be returned
408 // an empty form with no error message whatsoever.
412 // Upload verification
413 $details = $this->mUpload
->verifyUpload();
414 if ( $details['status'] != UploadBase
::OK
) {
415 $this->processVerificationError( $details );
419 // Verify permissions for this title
420 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
421 if ( $permErrors !== true ) {
422 $code = array_shift( $permErrors[0] );
423 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
427 $this->mLocalFile
= $this->mUpload
->getLocalFile();
429 // Check warnings if necessary
430 if ( !$this->mIgnoreWarning
) {
431 $warnings = $this->mUpload
->checkWarnings();
432 if ( $this->showUploadWarning( $warnings ) ) {
437 // Get the page text if this is not a reupload
438 if ( !$this->mForReUpload
) {
439 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
440 $this->mCopyrightStatus
, $this->mCopyrightSource
);
444 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $this->getUser() );
445 if ( !$status->isGood() ) {
446 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
450 // Success, redirect to description page
451 $this->mUploadSuccessful
= true;
452 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
453 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
457 * Get the initial image page text based on a comment and optional file status information
458 * @param $comment string
459 * @param $license string
460 * @param $copyStatus string
461 * @param $source string
464 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
465 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
468 /* These messages are transcluded into the actual text of the description page.
469 * Thus, forcing them as content messages makes the upload to produce an int: template
470 * instead of hardcoding it there in the uploader language.
472 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
473 if ( in_array( $msgName, (array)$wgForceUIMsgAsContentMsg ) ) {
474 $msg[$msgName] = "{{int:$msgName}}";
476 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
480 if ( $wgUseCopyrightUpload ) {
482 if ( $license != '' ) {
483 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
485 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
486 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
488 '== ' . $msg['filesource'] . " ==\n" . $source;
490 if ( $license != '' ) {
491 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
492 $pageText = $filedesc .
493 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
495 $pageText = $comment;
502 * See if we should check the 'watch this page' checkbox on the form
503 * based on the user's preferences and whether we're being asked
504 * to create a new file or update an existing one.
506 * In the case where 'watch edits' is off but 'watch creations' is on,
507 * we'll leave the box unchecked.
509 * Note that the page target can be changed *on the form*, so our check
510 * state can get out of sync.
511 * @return Bool|String
513 protected function getWatchCheck() {
514 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
519 $local = wfLocalFile( $this->mDesiredDestName
);
520 if ( $local && $local->exists() ) {
521 // We're uploading a new version of an existing file.
522 // No creation, so don't watch it if we're not already.
523 return $this->getUser()->isWatched( $local->getTitle() );
525 // New page should get watched if that's our option.
526 return $this->getUser()->getOption( 'watchcreations' );
531 * Provides output to the user for a result of UploadBase::verifyUpload
533 * @param array $details result of UploadBase::verifyUpload
534 * @throws MWException
536 protected function processVerificationError( $details ) {
537 global $wgFileExtensions;
539 switch ( $details['status'] ) {
541 /** Statuses that only require name changing **/
542 case UploadBase
::MIN_LENGTH_PARTNAME
:
543 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
545 case UploadBase
::ILLEGAL_FILENAME
:
546 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
547 $details['filtered'] )->parse() );
549 case UploadBase
::FILENAME_TOO_LONG
:
550 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
552 case UploadBase
::FILETYPE_MISSING
:
553 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
555 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
556 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
559 /** Statuses that require reuploading **/
560 case UploadBase
::EMPTY_FILE
:
561 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
563 case UploadBase
::FILE_TOO_LARGE
:
564 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
566 case UploadBase
::FILETYPE_BADTYPE
:
567 $msg = $this->msg( 'filetype-banned-type' );
568 if ( isset( $details['blacklistedExt'] ) ) {
569 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
571 $msg->params( $details['finalExt'] );
573 $msg->params( $this->getLanguage()->commaList( $wgFileExtensions ),
574 count( $wgFileExtensions ) );
576 // Add PLURAL support for the first parameter. This results
577 // in a bit unlogical parameter sequence, but does not break
579 if ( isset( $details['blacklistedExt'] ) ) {
580 $msg->params( count( $details['blacklistedExt'] ) );
585 $this->showUploadError( $msg->parse() );
587 case UploadBase
::VERIFICATION_ERROR
:
588 unset( $details['status'] );
589 $code = array_shift( $details['details'] );
590 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
592 case UploadBase
::HOOK_ABORTED
:
593 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
594 $args = $details['error'];
595 $error = array_shift( $args );
597 $error = $details['error'];
601 $this->showUploadError( $this->msg( $error, $args )->parse() );
604 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
609 * Remove a temporarily kept file stashed by saveTempUploadedFile().
611 * @return Boolean: success
613 protected function unsaveUploadedFile() {
614 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
617 $success = $this->mUpload
->unsaveUploadedFile();
619 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
626 /*** Functions for formatting warnings ***/
629 * Formats a result of UploadBase::getExistsWarning as HTML
630 * This check is static and can be done pre-upload via AJAX
632 * @param array $exists the result of UploadBase::getExistsWarning
633 * @return String: empty string if there is no warning or an HTML fragment
635 public static function getExistsWarning( $exists ) {
640 $file = $exists['file'];
641 $filename = $file->getTitle()->getPrefixedText();
644 if ( $exists['warning'] == 'exists' ) {
646 $warning = wfMessage( 'fileexists', $filename )->parse();
647 } elseif ( $exists['warning'] == 'page-exists' ) {
648 // Page exists but file does not
649 $warning = wfMessage( 'filepageexists', $filename )->parse();
650 } elseif ( $exists['warning'] == 'exists-normalized' ) {
651 $warning = wfMessage( 'fileexists-extension', $filename,
652 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
653 } elseif ( $exists['warning'] == 'thumb' ) {
654 // Swapped argument order compared with other messages for backwards compatibility
655 $warning = wfMessage( 'fileexists-thumbnail-yes',
656 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
657 } elseif ( $exists['warning'] == 'thumb-name' ) {
658 // Image w/o '180px-' does not exists, but we do not like these filenames
659 $name = $file->getName();
660 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
661 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
662 } elseif ( $exists['warning'] == 'bad-prefix' ) {
663 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
664 } elseif ( $exists['warning'] == 'was-deleted' ) {
665 # If the file existed before and was deleted, warn the user of this
666 $ltitle = SpecialPage
::getTitleFor( 'Log' );
667 $llink = Linker
::linkKnown(
669 wfMessage( 'deletionlog' )->escaped(),
676 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
683 * Construct a warning and a gallery from an array of duplicate files.
684 * @param $dupes array
687 public function getDupeWarning( $dupes ) {
692 $gallery = ImageGalleryBase
::factory();
693 $gallery->setContext( $this->getContext() );
694 $gallery->setShowBytes( false );
695 foreach ( $dupes as $file ) {
696 $gallery->add( $file->getTitle() );
699 wfMessage( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
700 $gallery->toHtml() . "</li>\n";
703 protected function getGroupName() {
709 * Sub class of HTMLForm that provides the form section of SpecialUpload
711 class UploadForm
extends HTMLForm
{
713 protected $mForReUpload;
714 protected $mSessionKey;
715 protected $mHideIgnoreWarning;
716 protected $mDestWarningAck;
717 protected $mDestFile;
721 protected $mTextAfterSummary;
723 protected $mSourceIds;
725 protected $mMaxFileSize = array();
727 protected $mMaxUploadSize = array();
729 public function __construct( array $options = array(), IContextSource
$context = null ) {
730 $this->mWatch
= !empty( $options['watch'] );
731 $this->mForReUpload
= !empty( $options['forreupload'] );
732 $this->mSessionKey
= isset( $options['sessionkey'] )
733 ?
$options['sessionkey'] : '';
734 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
735 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
736 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
738 $this->mComment
= isset( $options['description'] ) ?
739 $options['description'] : '';
741 $this->mTextTop
= isset( $options['texttop'] )
742 ?
$options['texttop'] : '';
744 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
745 ?
$options['textaftersummary'] : '';
747 $sourceDescriptor = $this->getSourceSection();
748 $descriptor = $sourceDescriptor
749 +
$this->getDescriptionSection()
750 +
$this->getOptionsSection();
752 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
753 parent
::__construct( $descriptor, $context, 'upload' );
755 # Set some form properties
756 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
757 $this->setSubmitName( 'wpUpload' );
758 # Used message keys: 'accesskey-upload', 'tooltip-upload'
759 $this->setSubmitTooltip( 'upload' );
760 $this->setId( 'mw-upload-form' );
762 # Build a list of IDs for javascript insertion
763 $this->mSourceIds
= array();
764 foreach ( $sourceDescriptor as $field ) {
765 if ( !empty( $field['id'] ) ) {
766 $this->mSourceIds
[] = $field['id'];
773 * Get the descriptor of the fieldset that contains the file source
774 * selection. The section is 'source'
776 * @return Array: descriptor array
778 protected function getSourceSection() {
779 global $wgCopyUploadsFromSpecialUpload;
781 if ( $this->mSessionKey
) {
783 'SessionKey' => array(
785 'default' => $this->mSessionKey
,
787 'SourceType' => array(
789 'default' => 'Stash',
794 $canUploadByUrl = UploadFromUrl
::isEnabled()
795 && UploadFromUrl
::isAllowed( $this->getUser() )
796 && $wgCopyUploadsFromSpecialUpload;
797 $radio = $canUploadByUrl;
798 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
800 $descriptor = array();
801 if ( $this->mTextTop
) {
802 $descriptor['UploadFormTextTop'] = array(
804 'section' => 'source',
805 'default' => $this->mTextTop
,
810 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
811 # Limit to upload_max_filesize unless we are running under HipHop and
812 # that setting doesn't exist
813 if ( !wfIsHipHop() ) {
814 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
815 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
816 wfShorthandToInteger( ini_get( 'post_max_size' ) )
820 $descriptor['UploadFile'] = array(
821 'class' => 'UploadSourceField',
822 'section' => 'source',
824 'id' => 'wpUploadFile',
825 'label-message' => 'sourcefilename',
826 'upload-type' => 'File',
828 'help' => $this->msg( 'upload-maxfilesize',
829 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] ) )
831 $this->msg( 'word-separator' )->escaped() .
832 $this->msg( 'upload_source_file' )->escaped(),
833 'checked' => $selectedSourceType == 'file',
836 if ( $canUploadByUrl ) {
837 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
838 $descriptor['UploadFileURL'] = array(
839 'class' => 'UploadSourceField',
840 'section' => 'source',
841 'id' => 'wpUploadFileURL',
842 'label-message' => 'sourceurl',
843 'upload-type' => 'url',
845 'help' => $this->msg( 'upload-maxfilesize',
846 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] ) )
848 $this->msg( 'word-separator' )->escaped() .
849 $this->msg( 'upload_source_url' )->escaped(),
850 'checked' => $selectedSourceType == 'url',
853 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
855 $descriptor['Extensions'] = array(
857 'section' => 'source',
858 'default' => $this->getExtensionsMessage(),
865 * Get the messages indicating which extensions are preferred and prohibitted.
867 * @return String: HTML string containing the message
869 protected function getExtensionsMessage() {
870 # Print a list of allowed file extensions, if so configured. We ignore
871 # MIME type here, it's incomprehensible to most people and too long.
872 global $wgCheckFileExtensions, $wgStrictFileExtensions,
873 $wgFileExtensions, $wgFileBlacklist;
875 if ( $wgCheckFileExtensions ) {
876 if ( $wgStrictFileExtensions ) {
877 # Everything not permitted is banned
879 '<div id="mw-upload-permitted">' .
880 $this->msg( 'upload-permitted', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) )->parseAsBlock() .
883 # We have to list both preferred and prohibited
885 '<div id="mw-upload-preferred">' .
886 $this->msg( 'upload-preferred', $this->getContext()->getLanguage()->commaList( $wgFileExtensions ) )->parseAsBlock() .
888 '<div id="mw-upload-prohibited">' .
889 $this->msg( 'upload-prohibited', $this->getContext()->getLanguage()->commaList( $wgFileBlacklist ) )->parseAsBlock() .
893 # Everything is permitted.
894 $extensionsList = '';
896 return $extensionsList;
900 * Get the descriptor of the fieldset that contains the file description
901 * input. The section is 'description'
903 * @return Array: descriptor array
905 protected function getDescriptionSection() {
906 if ( $this->mSessionKey
) {
907 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
909 $file = $stash->getFile( $this->mSessionKey
);
910 } catch ( MWException
$e ) {
916 $mto = $file->transform( array( 'width' => 120 ) );
917 $this->addHeaderText(
918 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
919 Html
::element( 'img', array(
920 'src' => $mto->getUrl(),
921 'class' => 'thumbimage',
922 ) ) . '</div>', 'description' );
929 'section' => 'description',
930 'id' => 'wpDestFile',
931 'label-message' => 'destfilename',
933 'default' => $this->mDestFile
,
934 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
935 'nodata' => strval( $this->mDestFile
) !== '',
937 'UploadDescription' => array(
938 'type' => 'textarea',
939 'section' => 'description',
940 'id' => 'wpUploadDescription',
941 'label-message' => $this->mForReUpload
942 ?
'filereuploadsummary'
943 : 'fileuploadsummary',
944 'default' => $this->mComment
,
945 'cols' => $this->getUser()->getIntOption( 'cols' ),
949 if ( $this->mTextAfterSummary
) {
950 $descriptor['UploadFormTextAfterSummary'] = array(
952 'section' => 'description',
953 'default' => $this->mTextAfterSummary
,
958 $descriptor +
= array(
959 'EditTools' => array(
960 'type' => 'edittools',
961 'section' => 'description',
962 'message' => 'edittools-upload',
966 if ( $this->mForReUpload
) {
967 $descriptor['DestFile']['readonly'] = true;
969 $descriptor['License'] = array(
971 'class' => 'Licenses',
972 'section' => 'description',
974 'label-message' => 'license',
978 global $wgUseCopyrightUpload;
979 if ( $wgUseCopyrightUpload ) {
980 $descriptor['UploadCopyStatus'] = array(
982 'section' => 'description',
983 'id' => 'wpUploadCopyStatus',
984 'label-message' => 'filestatus',
986 $descriptor['UploadSource'] = array(
988 'section' => 'description',
989 'id' => 'wpUploadSource',
990 'label-message' => 'filesource',
998 * Get the descriptor of the fieldset that contains the upload options,
999 * such as "watch this file". The section is 'options'
1001 * @return Array: descriptor array
1003 protected function getOptionsSection() {
1004 $user = $this->getUser();
1005 if ( $user->isLoggedIn() ) {
1006 $descriptor = array(
1007 'Watchthis' => array(
1009 'id' => 'wpWatchthis',
1010 'label-message' => 'watchthisupload',
1011 'section' => 'options',
1012 'default' => $user->getOption( 'watchcreations' ),
1016 if ( !$this->mHideIgnoreWarning
) {
1017 $descriptor['IgnoreWarning'] = array(
1019 'id' => 'wpIgnoreWarning',
1020 'label-message' => 'ignorewarnings',
1021 'section' => 'options',
1025 $descriptor['DestFileWarningAck'] = array(
1027 'id' => 'wpDestFileWarningAck',
1028 'default' => $this->mDestWarningAck ?
'1' : '',
1031 if ( $this->mForReUpload
) {
1032 $descriptor['ForReUpload'] = array(
1034 'id' => 'wpForReUpload',
1043 * Add the upload JS and show the form.
1045 public function show() {
1046 $this->addUploadJS();
1051 * Add upload JS to the OutputPage
1053 protected function addUploadJS() {
1054 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1056 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1057 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1058 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1060 $scriptVars = array(
1061 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1062 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1063 'wgUploadAutoFill' => !$this->mForReUpload
&&
1064 // If we received mDestFile from the request, don't autofill
1065 // the wpDestFile textbox
1066 $this->mDestFile
=== '',
1067 'wgUploadSourceIds' => $this->mSourceIds
,
1068 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1069 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1070 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1073 $out = $this->getOutput();
1074 $out->addJsConfigVars( $scriptVars );
1076 $out->addModules( array(
1077 'mediawiki.action.edit', // For <charinsert> support
1078 'mediawiki.legacy.upload', // Old form stuff...
1079 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1084 * Empty function; submission is handled elsewhere.
1086 * @return bool false
1088 function trySubmit() {
1095 * A form field that contains a radio box in the label
1097 class UploadSourceField
extends HTMLTextField
{
1100 * @param $cellAttributes array
1103 function getLabelHtml( $cellAttributes = array() ) {
1104 $id = $this->mParams
['id'];
1105 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1107 if ( !empty( $this->mParams
['radio'] ) ) {
1109 'name' => 'wpSourceType',
1112 'value' => $this->mParams
['upload-type'],
1114 if ( !empty( $this->mParams
['checked'] ) ) {
1115 $attribs['checked'] = 'checked';
1117 $label .= Html
::element( 'input', $attribs );
1120 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1126 function getSize() {
1127 return isset( $this->mParams
['size'] )
1128 ?
$this->mParams
['size']