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;
79 * Initialize instance variables from request and create an Upload handler
81 protected function loadRequest() {
82 $this->mRequest
= $request = $this->getRequest();
83 $this->mSourceType
= $request->getVal( 'wpSourceType', 'file' );
84 $this->mUpload
= UploadBase
::createFromRequest( $request );
85 $this->mUploadClicked
= $request->wasPosted()
86 && ( $request->getCheck( 'wpUpload' )
87 ||
$request->getCheck( 'wpUploadIgnoreWarning' ) );
89 // Guess the desired name from the filename if not provided
90 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
91 if ( !$this->mDesiredDestName
&& $request->getFileName( 'wpUploadFile' ) !== null ) {
92 $this->mDesiredDestName
= $request->getFileName( 'wpUploadFile' );
94 $this->mLicense
= $request->getText( 'wpLicense' );
96 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
97 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
98 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
99 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
100 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
101 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
103 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
105 $commentDefault = '';
106 $commentMsg = wfMessage( 'upload-default-description' )->inContentLanguage();
107 if ( !$this->mForReUpload
&& !$commentMsg->isDisabled() ) {
108 $commentDefault = $commentMsg->plain();
110 $this->mComment
= $request->getText( 'wpUploadDescription', $commentDefault );
112 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
113 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
115 // If it was posted check for the token (no remote POST'ing with user credentials)
116 $token = $request->getVal( 'wpEditToken' );
117 $this->mTokenOk
= $this->getUser()->matchEditToken( $token );
119 $this->uploadFormTextTop
= '';
120 $this->uploadFormTextAfterSummary
= '';
124 * This page can be shown if uploading is enabled.
125 * Handle permission checking elsewhere in order to be able to show
126 * custom error messages.
128 * @param $user User object
131 public function userCanExecute( User
$user ) {
132 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
136 * Special page entry point
138 public function execute( $par ) {
140 $this->outputHeader();
142 # Check uploading enabled
143 if ( !UploadBase
::isEnabled() ) {
144 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
148 $user = $this->getUser();
149 $permissionRequired = UploadBase
::isAllowed( $user );
150 if ( $permissionRequired !== true ) {
151 throw new PermissionsError( $permissionRequired );
155 if ( $user->isBlocked() ) {
156 throw new UserBlockedError( $user->getBlock() );
159 # Check whether we actually want to allow changing stuff
160 $this->checkReadOnly();
162 $this->loadRequest();
164 # Unsave the temporary file in case this was a cancelled upload
165 if ( $this->mCancelUpload
) {
166 if ( !$this->unsaveUploadedFile() ) {
167 # Something went wrong, so unsaveUploadedFile showed a warning
172 # Process upload or show a form
174 $this->mTokenOk
&& !$this->mCancelUpload
&&
175 ( $this->mUpload
&& $this->mUploadClicked
)
177 $this->processUpload();
179 # Backwards compatibility hook
180 if ( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
181 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
184 $this->showUploadForm( $this->getUploadForm() );
188 if ( $this->mUpload
) {
189 $this->mUpload
->cleanupTempFile();
194 * Show the main upload form
196 * @param $form Mixed: an HTMLForm instance or HTML string to show
198 protected function showUploadForm( $form ) {
199 # Add links if file was previously deleted
200 if ( $this->mDesiredDestName
) {
201 $this->showViewDeletedLinks();
204 if ( $form instanceof HTMLForm
) {
207 $this->getOutput()->addHTML( $form );
213 * Get an UploadForm instance with title and text properly set.
215 * @param string $message HTML string to add to the form
216 * @param string $sessionKey session key in case this is a stashed upload
217 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
220 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
222 $context = new DerivativeContext( $this->getContext() );
223 $context->setTitle( $this->getPageTitle() ); // Remove subpage
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
,
237 # Check the token, but only if necessary
239 !$this->mTokenOk
&& !$this->mCancelUpload
&&
240 ( $this->mUpload
&& $this->mUploadClicked
)
242 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
245 # Give a notice if the user is uploading a file that has been deleted or moved
246 # Note that this is independent from the message 'filewasdeleted' that requires JS
247 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
248 $delNotice = ''; // empty by default
249 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
250 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
252 '', array( 'lim' => 10,
253 'conds' => array( "log_action != 'revision'" ),
254 'showIfEmpty' => false,
255 'msgKey' => array( 'upload-recreate-warning' ) )
258 $form->addPreText( $delNotice );
261 $form->addPreText( '<div id="uploadtext">' .
262 $this->msg( 'uploadtext', array( $this->mDesiredDestName
) )->parseAsBlock() .
264 # Add upload error message
265 $form->addPreText( $message );
268 $uploadFooter = $this->msg( 'uploadfooter' );
269 if ( !$uploadFooter->isDisabled() ) {
270 $form->addPostText( '<div id="mw-upload-footer-message">'
271 . $uploadFooter->parseAsBlock() . "</div>\n" );
278 * Shows the "view X deleted revivions link""
280 protected function showViewDeletedLinks() {
281 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
282 $user = $this->getUser();
283 // Show a subtitle link to deleted revisions (to sysops et al only)
284 if ( $title instanceof Title
) {
285 $count = $title->isDeleted();
286 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
287 $restorelink = Linker
::linkKnown(
288 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
289 $this->msg( 'restorelink' )->numParams( $count )->escaped()
291 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
292 ->rawParams( $restorelink )->parseAsBlock();
293 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
299 * Stashes the upload and shows the main upload form.
301 * Note: only errors that can be handled by changing the name or
302 * description should be redirected here. It should be assumed that the
303 * file itself is sane and has passed UploadBase::verifyFile. This
304 * essentially means that UploadBase::VERIFICATION_ERROR and
305 * UploadBase::EMPTY_FILE should not be passed here.
307 * @param string $message HTML message to be passed to mainUploadForm
309 protected function showRecoverableUploadError( $message ) {
310 $sessionKey = $this->mUpload
->stashSession();
311 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
312 '<div class="error">' . $message . "</div>\n";
314 $form = $this->getUploadForm( $message, $sessionKey );
315 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
316 $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 if ( $args === '' ) {
353 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
356 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
357 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
361 if ( $args === true ) {
363 } elseif ( !is_array( $args ) ) {
364 $args = array( $args );
366 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
368 $warningHtml .= $msg;
370 $warningHtml .= "</ul>\n";
371 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
373 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
374 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
375 $form->addButton( 'wpUploadIgnoreWarning', $this->msg( 'ignorewarning' )->text() );
376 $form->addButton( 'wpCancelUpload', $this->msg( 'reuploaddesc' )->text() );
378 $this->showUploadForm( $form );
380 # Indicate that we showed a form
385 * Show the upload form with error message, but do not stash the file.
387 * @param string $message HTML string
389 protected function showUploadError( $message ) {
390 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
391 '<div class="error">' . $message . "</div>\n";
392 $this->showUploadForm( $this->getUploadForm( $message ) );
397 * Checks are made in SpecialUpload::execute()
399 protected function processUpload() {
400 // Fetch the file if required
401 $status = $this->mUpload
->fetchFile();
402 if ( !$status->isOK() ) {
403 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
407 if ( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
408 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
409 // This code path is deprecated. If you want to break upload processing
410 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
411 // and UploadBase::verifyFile.
412 // If you use this hook to break uploading, the user will be returned
413 // an empty form with no error message whatsoever.
417 // Upload verification
418 $details = $this->mUpload
->verifyUpload();
419 if ( $details['status'] != UploadBase
::OK
) {
420 $this->processVerificationError( $details );
424 // Verify permissions for this title
425 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
426 if ( $permErrors !== true ) {
427 $code = array_shift( $permErrors[0] );
428 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
432 $this->mLocalFile
= $this->mUpload
->getLocalFile();
434 // Check warnings if necessary
435 if ( !$this->mIgnoreWarning
) {
436 $warnings = $this->mUpload
->checkWarnings();
437 if ( $this->showUploadWarning( $warnings ) ) {
442 // Get the page text if this is not a reupload
443 if ( !$this->mForReUpload
) {
444 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
445 $this->mCopyrightStatus
, $this->mCopyrightSource
);
449 $status = $this->mUpload
->performUpload( $this->mComment
, $pageText, $this->mWatchthis
, $this->getUser() );
450 if ( !$status->isGood() ) {
451 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
455 // Success, redirect to description page
456 $this->mUploadSuccessful
= true;
457 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
458 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
462 * Get the initial image page text based on a comment and optional file status information
463 * @param $comment string
464 * @param $license string
465 * @param $copyStatus string
466 * @param $source string
469 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
470 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
473 /* These messages are transcluded into the actual text of the description page.
474 * Thus, forcing them as content messages makes the upload to produce an int: template
475 * instead of hardcoding it there in the uploader language.
477 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
478 if ( in_array( $msgName, (array)$wgForceUIMsgAsContentMsg ) ) {
479 $msg[$msgName] = "{{int:$msgName}}";
481 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
485 if ( $wgUseCopyrightUpload ) {
487 if ( $license != '' ) {
488 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
490 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
491 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
493 '== ' . $msg['filesource'] . " ==\n" . $source;
495 if ( $license != '' ) {
496 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
497 $pageText = $filedesc .
498 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
500 $pageText = $comment;
507 * See if we should check the 'watch this page' checkbox on the form
508 * based on the user's preferences and whether we're being asked
509 * to create a new file or update an existing one.
511 * In the case where 'watch edits' is off but 'watch creations' is on,
512 * we'll leave the box unchecked.
514 * Note that the page target can be changed *on the form*, so our check
515 * state can get out of sync.
516 * @return Bool|String
518 protected function getWatchCheck() {
519 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
524 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
525 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
526 // Already watched, don't change that
530 $local = wfLocalFile( $this->mDesiredDestName
);
531 if ( $local && $local->exists() ) {
532 // We're uploading a new version of an existing file.
533 // No creation, so don't watch it if we're not already.
536 // New page should get watched if that's our option.
537 return $this->getUser()->getOption( 'watchcreations' );
542 * Provides output to the user for a result of UploadBase::verifyUpload
544 * @param array $details result of UploadBase::verifyUpload
545 * @throws MWException
547 protected function processVerificationError( $details ) {
548 global $wgFileExtensions;
550 switch ( $details['status'] ) {
552 /** Statuses that only require name changing **/
553 case UploadBase
::MIN_LENGTH_PARTNAME
:
554 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
556 case UploadBase
::ILLEGAL_FILENAME
:
557 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
558 $details['filtered'] )->parse() );
560 case UploadBase
::FILENAME_TOO_LONG
:
561 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
563 case UploadBase
::FILETYPE_MISSING
:
564 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
566 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
567 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
570 /** Statuses that require reuploading **/
571 case UploadBase
::EMPTY_FILE
:
572 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
574 case UploadBase
::FILE_TOO_LARGE
:
575 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
577 case UploadBase
::FILETYPE_BADTYPE
:
578 $msg = $this->msg( 'filetype-banned-type' );
579 if ( isset( $details['blacklistedExt'] ) ) {
580 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
582 $msg->params( $details['finalExt'] );
584 $extensions = array_unique( $wgFileExtensions );
585 $msg->params( $this->getLanguage()->commaList( $extensions ),
586 count( $extensions ) );
588 // Add PLURAL support for the first parameter. This results
589 // in a bit unlogical parameter sequence, but does not break
591 if ( isset( $details['blacklistedExt'] ) ) {
592 $msg->params( count( $details['blacklistedExt'] ) );
597 $this->showUploadError( $msg->parse() );
599 case UploadBase
::VERIFICATION_ERROR
:
600 unset( $details['status'] );
601 $code = array_shift( $details['details'] );
602 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
604 case UploadBase
::HOOK_ABORTED
:
605 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
606 $args = $details['error'];
607 $error = array_shift( $args );
609 $error = $details['error'];
613 $this->showUploadError( $this->msg( $error, $args )->parse() );
616 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
621 * Remove a temporarily kept file stashed by saveTempUploadedFile().
623 * @return Boolean: success
625 protected function unsaveUploadedFile() {
626 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
629 $success = $this->mUpload
->unsaveUploadedFile();
631 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
638 /*** Functions for formatting warnings ***/
641 * Formats a result of UploadBase::getExistsWarning as HTML
642 * This check is static and can be done pre-upload via AJAX
644 * @param array $exists the result of UploadBase::getExistsWarning
645 * @return String: empty string if there is no warning or an HTML fragment
647 public static function getExistsWarning( $exists ) {
652 $file = $exists['file'];
653 $filename = $file->getTitle()->getPrefixedText();
656 if ( $exists['warning'] == 'exists' ) {
658 $warning = wfMessage( 'fileexists', $filename )->parse();
659 } elseif ( $exists['warning'] == 'page-exists' ) {
660 // Page exists but file does not
661 $warning = wfMessage( 'filepageexists', $filename )->parse();
662 } elseif ( $exists['warning'] == 'exists-normalized' ) {
663 $warning = wfMessage( 'fileexists-extension', $filename,
664 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
665 } elseif ( $exists['warning'] == 'thumb' ) {
666 // Swapped argument order compared with other messages for backwards compatibility
667 $warning = wfMessage( 'fileexists-thumbnail-yes',
668 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
669 } elseif ( $exists['warning'] == 'thumb-name' ) {
670 // Image w/o '180px-' does not exists, but we do not like these filenames
671 $name = $file->getName();
672 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
673 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
674 } elseif ( $exists['warning'] == 'bad-prefix' ) {
675 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
676 } elseif ( $exists['warning'] == 'was-deleted' ) {
677 # If the file existed before and was deleted, warn the user of this
678 $ltitle = SpecialPage
::getTitleFor( 'Log' );
679 $llink = Linker
::linkKnown(
681 wfMessage( 'deletionlog' )->escaped(),
688 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
695 * Construct a warning and a gallery from an array of duplicate files.
696 * @param $dupes array
699 public function getDupeWarning( $dupes ) {
704 $gallery = ImageGalleryBase
::factory();
705 $gallery->setContext( $this->getContext() );
706 $gallery->setShowBytes( false );
707 foreach ( $dupes as $file ) {
708 $gallery->add( $file->getTitle() );
711 wfMessage( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
712 $gallery->toHtml() . "</li>\n";
715 protected function getGroupName() {
721 * Sub class of HTMLForm that provides the form section of SpecialUpload
723 class UploadForm
extends HTMLForm
{
725 protected $mForReUpload;
726 protected $mSessionKey;
727 protected $mHideIgnoreWarning;
728 protected $mDestWarningAck;
729 protected $mDestFile;
733 protected $mTextAfterSummary;
735 protected $mSourceIds;
737 protected $mMaxFileSize = array();
739 protected $mMaxUploadSize = array();
741 public function __construct( array $options = array(), IContextSource
$context = null ) {
742 $this->mWatch
= !empty( $options['watch'] );
743 $this->mForReUpload
= !empty( $options['forreupload'] );
744 $this->mSessionKey
= isset( $options['sessionkey'] )
745 ?
$options['sessionkey'] : '';
746 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
747 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
748 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
750 $this->mComment
= isset( $options['description'] ) ?
751 $options['description'] : '';
753 $this->mTextTop
= isset( $options['texttop'] )
754 ?
$options['texttop'] : '';
756 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
757 ?
$options['textaftersummary'] : '';
759 $sourceDescriptor = $this->getSourceSection();
760 $descriptor = $sourceDescriptor
761 +
$this->getDescriptionSection()
762 +
$this->getOptionsSection();
764 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
765 parent
::__construct( $descriptor, $context, 'upload' );
767 # Set some form properties
768 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
769 $this->setSubmitName( 'wpUpload' );
770 # Used message keys: 'accesskey-upload', 'tooltip-upload'
771 $this->setSubmitTooltip( 'upload' );
772 $this->setId( 'mw-upload-form' );
774 # Build a list of IDs for javascript insertion
775 $this->mSourceIds
= array();
776 foreach ( $sourceDescriptor as $field ) {
777 if ( !empty( $field['id'] ) ) {
778 $this->mSourceIds
[] = $field['id'];
785 * Get the descriptor of the fieldset that contains the file source
786 * selection. The section is 'source'
788 * @return Array: descriptor array
790 protected function getSourceSection() {
791 global $wgCopyUploadsFromSpecialUpload;
793 if ( $this->mSessionKey
) {
795 'SessionKey' => array(
797 'default' => $this->mSessionKey
,
799 'SourceType' => array(
801 'default' => 'Stash',
806 $canUploadByUrl = UploadFromUrl
::isEnabled()
807 && UploadFromUrl
::isAllowed( $this->getUser() )
808 && $wgCopyUploadsFromSpecialUpload;
809 $radio = $canUploadByUrl;
810 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
812 $descriptor = array();
813 if ( $this->mTextTop
) {
814 $descriptor['UploadFormTextTop'] = array(
816 'section' => 'source',
817 'default' => $this->mTextTop
,
822 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
823 # Limit to upload_max_filesize unless we are running under HipHop and
824 # that setting doesn't exist
826 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
827 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
828 wfShorthandToInteger( ini_get( 'post_max_size' ) )
832 $descriptor['UploadFile'] = array(
833 'class' => 'UploadSourceField',
834 'section' => 'source',
836 'id' => 'wpUploadFile',
837 'label-message' => 'sourcefilename',
838 'upload-type' => 'File',
840 'help' => $this->msg( 'upload-maxfilesize',
841 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] ) )
843 $this->msg( 'word-separator' )->escaped() .
844 $this->msg( 'upload_source_file' )->escaped(),
845 'checked' => $selectedSourceType == 'file',
848 if ( $canUploadByUrl ) {
849 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
850 $descriptor['UploadFileURL'] = array(
851 'class' => 'UploadSourceField',
852 'section' => 'source',
853 'id' => 'wpUploadFileURL',
854 'label-message' => 'sourceurl',
855 'upload-type' => 'url',
857 'help' => $this->msg( 'upload-maxfilesize',
858 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] ) )
860 $this->msg( 'word-separator' )->escaped() .
861 $this->msg( 'upload_source_url' )->escaped(),
862 'checked' => $selectedSourceType == 'url',
865 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
867 $descriptor['Extensions'] = array(
869 'section' => 'source',
870 'default' => $this->getExtensionsMessage(),
877 * Get the messages indicating which extensions are preferred and prohibitted.
879 * @return String: HTML string containing the message
881 protected function getExtensionsMessage() {
882 # Print a list of allowed file extensions, if so configured. We ignore
883 # MIME type here, it's incomprehensible to most people and too long.
884 global $wgCheckFileExtensions, $wgStrictFileExtensions,
885 $wgFileExtensions, $wgFileBlacklist;
887 if ( $wgCheckFileExtensions ) {
888 if ( $wgStrictFileExtensions ) {
889 # Everything not permitted is banned
891 '<div id="mw-upload-permitted">' .
892 $this->msg( 'upload-permitted', $this->getContext()->getLanguage()->commaList( array_unique( $wgFileExtensions ) ) )->parseAsBlock() .
895 # We have to list both preferred and prohibited
897 '<div id="mw-upload-preferred">' .
898 $this->msg( 'upload-preferred', $this->getContext()->getLanguage()->commaList( array_unique( $wgFileExtensions ) ) )->parseAsBlock() .
900 '<div id="mw-upload-prohibited">' .
901 $this->msg( 'upload-prohibited', $this->getContext()->getLanguage()->commaList( array_unique( $wgFileBlacklist ) ) )->parseAsBlock() .
905 # Everything is permitted.
906 $extensionsList = '';
908 return $extensionsList;
912 * Get the descriptor of the fieldset that contains the file description
913 * input. The section is 'description'
915 * @return Array: descriptor array
917 protected function getDescriptionSection() {
918 if ( $this->mSessionKey
) {
919 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
921 $file = $stash->getFile( $this->mSessionKey
);
922 } catch ( MWException
$e ) {
928 $mto = $file->transform( array( 'width' => 120 ) );
929 $this->addHeaderText(
930 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
931 Html
::element( 'img', array(
932 'src' => $mto->getUrl(),
933 'class' => 'thumbimage',
934 ) ) . '</div>', 'description' );
941 'section' => 'description',
942 'id' => 'wpDestFile',
943 'label-message' => 'destfilename',
945 'default' => $this->mDestFile
,
946 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
947 'nodata' => strval( $this->mDestFile
) !== '',
949 'UploadDescription' => array(
950 'type' => 'textarea',
951 'section' => 'description',
952 'id' => 'wpUploadDescription',
953 'label-message' => $this->mForReUpload
954 ?
'filereuploadsummary'
955 : 'fileuploadsummary',
956 'default' => $this->mComment
,
957 'cols' => $this->getUser()->getIntOption( 'cols' ),
961 if ( $this->mTextAfterSummary
) {
962 $descriptor['UploadFormTextAfterSummary'] = array(
964 'section' => 'description',
965 'default' => $this->mTextAfterSummary
,
970 $descriptor +
= array(
971 'EditTools' => array(
972 'type' => 'edittools',
973 'section' => 'description',
974 'message' => 'edittools-upload',
978 if ( $this->mForReUpload
) {
979 $descriptor['DestFile']['readonly'] = true;
981 $descriptor['License'] = array(
983 'class' => 'Licenses',
984 'section' => 'description',
986 'label-message' => 'license',
990 global $wgUseCopyrightUpload;
991 if ( $wgUseCopyrightUpload ) {
992 $descriptor['UploadCopyStatus'] = array(
994 'section' => 'description',
995 'id' => 'wpUploadCopyStatus',
996 'label-message' => 'filestatus',
998 $descriptor['UploadSource'] = array(
1000 'section' => 'description',
1001 'id' => 'wpUploadSource',
1002 'label-message' => 'filesource',
1010 * Get the descriptor of the fieldset that contains the upload options,
1011 * such as "watch this file". The section is 'options'
1013 * @return Array: descriptor array
1015 protected function getOptionsSection() {
1016 $user = $this->getUser();
1017 if ( $user->isLoggedIn() ) {
1018 $descriptor = array(
1019 'Watchthis' => array(
1021 'id' => 'wpWatchthis',
1022 'label-message' => 'watchthisupload',
1023 'section' => 'options',
1024 'default' => $this->mWatch
,
1028 if ( !$this->mHideIgnoreWarning
) {
1029 $descriptor['IgnoreWarning'] = array(
1031 'id' => 'wpIgnoreWarning',
1032 'label-message' => 'ignorewarnings',
1033 'section' => 'options',
1037 $descriptor['DestFileWarningAck'] = array(
1039 'id' => 'wpDestFileWarningAck',
1040 'default' => $this->mDestWarningAck ?
'1' : '',
1043 if ( $this->mForReUpload
) {
1044 $descriptor['ForReUpload'] = array(
1046 'id' => 'wpForReUpload',
1055 * Add the upload JS and show the form.
1057 public function show() {
1058 $this->addUploadJS();
1063 * Add upload JS to the OutputPage
1065 protected function addUploadJS() {
1066 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1068 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1069 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1070 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1072 $scriptVars = array(
1073 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1074 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1075 'wgUploadAutoFill' => !$this->mForReUpload
&&
1076 // If we received mDestFile from the request, don't autofill
1077 // the wpDestFile textbox
1078 $this->mDestFile
=== '',
1079 'wgUploadSourceIds' => $this->mSourceIds
,
1080 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1081 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1082 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1085 $out = $this->getOutput();
1086 $out->addJsConfigVars( $scriptVars );
1088 $out->addModules( array(
1089 'mediawiki.action.edit', // For <charinsert> support
1090 'mediawiki.legacy.upload', // Old form stuff...
1091 'mediawiki.special.upload', // Newer extras for thumbnail preview.
1096 * Empty function; submission is handled elsewhere.
1098 * @return bool false
1100 function trySubmit() {
1107 * A form field that contains a radio box in the label
1109 class UploadSourceField
extends HTMLTextField
{
1112 * @param $cellAttributes array
1115 function getLabelHtml( $cellAttributes = array() ) {
1116 if ( !empty( $this->mParams
['radio'] ) ) {
1117 $id = "wpSourceType{$this->mParams['upload-type']}";
1119 'name' => 'wpSourceType',
1122 'value' => $this->mParams
['upload-type'],
1124 if ( !empty( $this->mParams
['checked'] ) ) {
1125 $attribs['checked'] = 'checked';
1127 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1128 $label .= Html
::element( 'input', $attribs );
1130 $id = $this->mParams
['id'];
1131 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1133 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1139 function getSize() {
1140 return isset( $this->mParams
['size'] )
1141 ?
$this->mParams
['size']