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 WebRequest $request Data posted.
37 public function __construct( $request = null ) {
38 parent
::__construct( 'Upload', 'upload' );
41 /** Misc variables **/
43 /** @var WebRequest|FauxRequest The request this form is supposed to handle */
47 /** @var UploadBase */
52 public $mUploadClicked;
54 /** User input variables from the "description" section **/
56 /** @var string The requested target file name */
57 public $mDesiredDestName;
61 /** User input variables from the root section **/
63 public $mIgnoreWarning;
65 public $mCopyrightStatus;
66 public $mCopyrightSource;
68 /** Hidden variables **/
70 public $mDestWarningAck;
72 /** @var bool The user followed an "overwrite this file" link */
75 /** @var bool The user clicked "Cancel and return to upload form" button */
76 public $mCancelUpload;
79 /** @var bool Subclasses can use this to determine whether a file was uploaded */
80 public $mUploadSuccessful = false;
82 /** Text injection points for hooks not using HTMLForm **/
83 public $uploadFormTextTop;
84 public $uploadFormTextAfterSummary;
87 * Initialize instance variables from request and create an Upload handler
89 protected function loadRequest() {
90 $this->mRequest
= $request = $this->getRequest();
91 $this->mSourceType
= $request->getVal( 'wpSourceType', 'file' );
92 $this->mUpload
= UploadBase
::createFromRequest( $request );
93 $this->mUploadClicked
= $request->wasPosted()
94 && ( $request->getCheck( 'wpUpload' )
95 ||
$request->getCheck( 'wpUploadIgnoreWarning' ) );
97 // Guess the desired name from the filename if not provided
98 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
99 if ( !$this->mDesiredDestName
&& $request->getFileName( 'wpUploadFile' ) !== null ) {
100 $this->mDesiredDestName
= $request->getFileName( 'wpUploadFile' );
102 $this->mLicense
= $request->getText( 'wpLicense' );
104 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
105 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
106 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
107 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
108 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
109 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
111 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
113 $commentDefault = '';
114 $commentMsg = wfMessage( 'upload-default-description' )->inContentLanguage();
115 if ( !$this->mForReUpload
&& !$commentMsg->isDisabled() ) {
116 $commentDefault = $commentMsg->plain();
118 $this->mComment
= $request->getText( 'wpUploadDescription', $commentDefault );
120 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
121 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
123 // If it was posted check for the token (no remote POST'ing with user credentials)
124 $token = $request->getVal( 'wpEditToken' );
125 $this->mTokenOk
= $this->getUser()->matchEditToken( $token );
127 $this->uploadFormTextTop
= '';
128 $this->uploadFormTextAfterSummary
= '';
132 * This page can be shown if uploading is enabled.
133 * Handle permission checking elsewhere in order to be able to show
134 * custom error messages.
139 public function userCanExecute( User
$user ) {
140 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
144 * Special page entry point
146 * @throws ErrorPageError
149 * @throws MWException
150 * @throws PermissionsError
151 * @throws ReadOnlyError
152 * @throws UserBlockedError
154 public function execute( $par ) {
155 $this->useTransactionalTimeLimit();
158 $this->outputHeader();
160 # Check uploading enabled
161 if ( !UploadBase
::isEnabled() ) {
162 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
165 $this->addHelpLink( 'Help:Managing files' );
168 $user = $this->getUser();
169 $permissionRequired = UploadBase
::isAllowed( $user );
170 if ( $permissionRequired !== true ) {
171 throw new PermissionsError( $permissionRequired );
175 if ( $user->isBlocked() ) {
176 throw new UserBlockedError( $user->getBlock() );
179 # Check whether we actually want to allow changing stuff
180 $this->checkReadOnly();
182 $this->loadRequest();
184 # Unsave the temporary file in case this was a cancelled upload
185 if ( $this->mCancelUpload
) {
186 if ( !$this->unsaveUploadedFile() ) {
187 # Something went wrong, so unsaveUploadedFile showed a warning
192 # Process upload or show a form
194 $this->mTokenOk
&& !$this->mCancelUpload
&&
195 ( $this->mUpload
&& $this->mUploadClicked
)
197 $this->processUpload();
199 # Backwards compatibility hook
200 if ( !Hooks
::run( 'UploadForm:initial', array( &$this ) ) ) {
201 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
205 $this->showUploadForm( $this->getUploadForm() );
209 if ( $this->mUpload
) {
210 $this->mUpload
->cleanupTempFile();
215 * Show the main upload form
217 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
219 protected function showUploadForm( $form ) {
220 # Add links if file was previously deleted
221 if ( $this->mDesiredDestName
) {
222 $this->showViewDeletedLinks();
225 if ( $form instanceof HTMLForm
) {
228 $this->getOutput()->addHTML( $form );
233 * Get an UploadForm instance with title and text properly set.
235 * @param string $message HTML string to add to the form
236 * @param string $sessionKey Session key in case this is a stashed upload
237 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
240 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
242 $context = new DerivativeContext( $this->getContext() );
243 $context->setTitle( $this->getPageTitle() ); // Remove subpage
244 $form = new UploadForm( array(
245 'watch' => $this->getWatchCheck(),
246 'forreupload' => $this->mForReUpload
,
247 'sessionkey' => $sessionKey,
248 'hideignorewarning' => $hideIgnoreWarning,
249 'destwarningack' => (bool)$this->mDestWarningAck
,
251 'description' => $this->mComment
,
252 'texttop' => $this->uploadFormTextTop
,
253 'textaftersummary' => $this->uploadFormTextAfterSummary
,
254 'destfile' => $this->mDesiredDestName
,
257 # Check the token, but only if necessary
259 !$this->mTokenOk
&& !$this->mCancelUpload
&&
260 ( $this->mUpload
&& $this->mUploadClicked
)
262 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
265 # Give a notice if the user is uploading a file that has been deleted or moved
266 # Note that this is independent from the message 'filewasdeleted'
267 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
268 $delNotice = ''; // empty by default
269 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
270 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
272 '', array( 'lim' => 10,
273 'conds' => array( "log_action != 'revision'" ),
274 'showIfEmpty' => false,
275 'msgKey' => array( 'upload-recreate-warning' ) )
278 $form->addPreText( $delNotice );
281 $form->addPreText( '<div id="uploadtext">' .
282 $this->msg( 'uploadtext', array( $this->mDesiredDestName
) )->parseAsBlock() .
284 # Add upload error message
285 $form->addPreText( $message );
288 $uploadFooter = $this->msg( 'uploadfooter' );
289 if ( !$uploadFooter->isDisabled() ) {
290 $form->addPostText( '<div id="mw-upload-footer-message">'
291 . $uploadFooter->parseAsBlock() . "</div>\n" );
298 * Shows the "view X deleted revivions link""
300 protected function showViewDeletedLinks() {
301 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
302 $user = $this->getUser();
303 // Show a subtitle link to deleted revisions (to sysops et al only)
304 if ( $title instanceof Title
) {
305 $count = $title->isDeleted();
306 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
307 $restorelink = Linker
::linkKnown(
308 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
309 $this->msg( 'restorelink' )->numParams( $count )->escaped()
311 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
312 ->rawParams( $restorelink )->parseAsBlock();
313 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
319 * Stashes the upload and shows the main upload form.
321 * Note: only errors that can be handled by changing the name or
322 * description should be redirected here. It should be assumed that the
323 * file itself is sane and has passed UploadBase::verifyFile. This
324 * essentially means that UploadBase::VERIFICATION_ERROR and
325 * UploadBase::EMPTY_FILE should not be passed here.
327 * @param string $message HTML message to be passed to mainUploadForm
329 protected function showRecoverableUploadError( $message ) {
330 $sessionKey = $this->mUpload
->stashSession();
331 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
332 '<div class="error">' . $message . "</div>\n";
334 $form = $this->getUploadForm( $message, $sessionKey );
335 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
336 $this->showUploadForm( $form );
340 * Stashes the upload, shows the main form, but adds a "continue anyway button".
341 * Also checks whether there are actually warnings to display.
343 * @param array $warnings
344 * @return bool True if warnings were displayed, false if there are no
345 * warnings and it should continue processing
347 protected function showUploadWarning( $warnings ) {
348 # If there are no warnings, or warnings we can ignore, return early.
349 # mDestWarningAck is set when some javascript has shown the warning
350 # to the user. mForReUpload is set when the user clicks the "upload a
352 if ( !$warnings ||
( count( $warnings ) == 1
353 && isset( $warnings['exists'] )
354 && ( $this->mDestWarningAck ||
$this->mForReUpload
) )
359 $sessionKey = $this->mUpload
->stashSession();
361 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
362 . '<div class="warningbox"><ul>';
363 foreach ( $warnings as $warning => $args ) {
364 if ( $warning == 'badfilename' ) {
365 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
367 if ( $warning == 'exists' ) {
368 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
369 } elseif ( $warning == 'was-deleted' ) {
370 # If the file existed before and was deleted, warn the user of this
371 $ltitle = SpecialPage
::getTitleFor( 'Log' );
372 $llink = Linker
::linkKnown(
374 wfMessage( 'deletionlog' )->escaped(),
378 'page' => Title
::makeTitle( NS_FILE
, $args )->getPrefixedText(),
381 $msg = "\t<li>" . wfMessage( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
382 } elseif ( $warning == 'duplicate' ) {
383 $msg = $this->getDupeWarning( $args );
384 } elseif ( $warning == 'duplicate-archive' ) {
385 if ( $args === '' ) {
386 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
389 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
390 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
394 if ( $args === true ) {
396 } elseif ( !is_array( $args ) ) {
397 $args = array( $args );
399 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
401 $warningHtml .= $msg;
403 $warningHtml .= "</ul></div>\n";
404 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
406 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
407 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
408 $form->addButton( 'wpUploadIgnoreWarning', $this->msg( 'ignorewarning' )->text() );
409 $form->addButton( 'wpCancelUpload', $this->msg( 'reuploaddesc' )->text() );
411 $this->showUploadForm( $form );
413 # Indicate that we showed a form
418 * Show the upload form with error message, but do not stash the file.
420 * @param string $message HTML string
422 protected function showUploadError( $message ) {
423 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
424 '<div class="error">' . $message . "</div>\n";
425 $this->showUploadForm( $this->getUploadForm( $message ) );
430 * Checks are made in SpecialUpload::execute()
432 protected function processUpload() {
433 // Fetch the file if required
434 $status = $this->mUpload
->fetchFile();
435 if ( !$status->isOK() ) {
436 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
441 if ( !Hooks
::run( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
442 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
443 // This code path is deprecated. If you want to break upload processing
444 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
445 // and UploadBase::verifyFile.
446 // If you use this hook to break uploading, the user will be returned
447 // an empty form with no error message whatsoever.
451 // Upload verification
452 $details = $this->mUpload
->verifyUpload();
453 if ( $details['status'] != UploadBase
::OK
) {
454 $this->processVerificationError( $details );
459 // Verify permissions for this title
460 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
461 if ( $permErrors !== true ) {
462 $code = array_shift( $permErrors[0] );
463 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
468 $this->mLocalFile
= $this->mUpload
->getLocalFile();
470 // Check warnings if necessary
471 if ( !$this->mIgnoreWarning
) {
472 $warnings = $this->mUpload
->checkWarnings();
473 if ( $this->showUploadWarning( $warnings ) ) {
478 // Get the page text if this is not a reupload
479 if ( !$this->mForReUpload
) {
480 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
481 $this->mCopyrightStatus
, $this->mCopyrightSource
, $this->getConfig() );
486 $status = $this->mUpload
->performUpload(
493 if ( !$status->isGood() ) {
494 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
499 // Success, redirect to description page
500 $this->mUploadSuccessful
= true;
501 Hooks
::run( 'SpecialUploadComplete', array( &$this ) );
502 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
506 * Get the initial image page text based on a comment and optional file status information
507 * @param string $comment
508 * @param string $license
509 * @param string $copyStatus
510 * @param string $source
511 * @param Config $config Configuration object to load data from
514 public static function getInitialPageText( $comment = '', $license = '',
515 $copyStatus = '', $source = '', Config
$config = null
517 if ( $config === null ) {
518 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
519 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
523 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
524 /* These messages are transcluded into the actual text of the description page.
525 * Thus, forcing them as content messages makes the upload to produce an int: template
526 * instead of hardcoding it there in the uploader language.
528 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
529 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
530 $msg[$msgName] = "{{int:$msgName}}";
532 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
536 if ( $config->get( 'UseCopyrightUpload' ) ) {
538 if ( $license != '' ) {
539 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
541 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
542 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
544 '== ' . $msg['filesource'] . " ==\n" . $source;
546 if ( $license != '' ) {
547 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
548 $pageText = $filedesc .
549 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
551 $pageText = $comment;
559 * See if we should check the 'watch this page' checkbox on the form
560 * based on the user's preferences and whether we're being asked
561 * to create a new file or update an existing one.
563 * In the case where 'watch edits' is off but 'watch creations' is on,
564 * we'll leave the box unchecked.
566 * Note that the page target can be changed *on the form*, so our check
567 * state can get out of sync.
568 * @return bool|string
570 protected function getWatchCheck() {
571 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
576 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
577 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
578 // Already watched, don't change that
582 $local = wfLocalFile( $this->mDesiredDestName
);
583 if ( $local && $local->exists() ) {
584 // We're uploading a new version of an existing file.
585 // No creation, so don't watch it if we're not already.
588 // New page should get watched if that's our option.
589 return $this->getUser()->getOption( 'watchcreations' );
594 * Provides output to the user for a result of UploadBase::verifyUpload
596 * @param array $details Result of UploadBase::verifyUpload
597 * @throws MWException
599 protected function processVerificationError( $details ) {
600 switch ( $details['status'] ) {
602 /** Statuses that only require name changing **/
603 case UploadBase
::MIN_LENGTH_PARTNAME
:
604 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
606 case UploadBase
::ILLEGAL_FILENAME
:
607 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
608 $details['filtered'] )->parse() );
610 case UploadBase
::FILENAME_TOO_LONG
:
611 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
613 case UploadBase
::FILETYPE_MISSING
:
614 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
616 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
617 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
620 /** Statuses that require reuploading **/
621 case UploadBase
::EMPTY_FILE
:
622 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
624 case UploadBase
::FILE_TOO_LARGE
:
625 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
627 case UploadBase
::FILETYPE_BADTYPE
:
628 $msg = $this->msg( 'filetype-banned-type' );
629 if ( isset( $details['blacklistedExt'] ) ) {
630 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
632 $msg->params( $details['finalExt'] );
634 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
635 $msg->params( $this->getLanguage()->commaList( $extensions ),
636 count( $extensions ) );
638 // Add PLURAL support for the first parameter. This results
639 // in a bit unlogical parameter sequence, but does not break
641 if ( isset( $details['blacklistedExt'] ) ) {
642 $msg->params( count( $details['blacklistedExt'] ) );
647 $this->showUploadError( $msg->parse() );
649 case UploadBase
::VERIFICATION_ERROR
:
650 unset( $details['status'] );
651 $code = array_shift( $details['details'] );
652 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
654 case UploadBase
::HOOK_ABORTED
:
655 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
656 $args = $details['error'];
657 $error = array_shift( $args );
659 $error = $details['error'];
663 $this->showUploadError( $this->msg( $error, $args )->parse() );
666 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
671 * Remove a temporarily kept file stashed by saveTempUploadedFile().
673 * @return bool Success
675 protected function unsaveUploadedFile() {
676 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
679 $success = $this->mUpload
->unsaveUploadedFile();
681 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
689 /*** Functions for formatting warnings ***/
692 * Formats a result of UploadBase::getExistsWarning as HTML
693 * This check is static and can be done pre-upload via AJAX
695 * @param array $exists The result of UploadBase::getExistsWarning
696 * @return string Empty string if there is no warning or an HTML fragment
698 public static function getExistsWarning( $exists ) {
703 $file = $exists['file'];
704 $filename = $file->getTitle()->getPrefixedText();
707 if ( $exists['warning'] == 'exists' ) {
709 $warning = wfMessage( 'fileexists', $filename )->parse();
710 } elseif ( $exists['warning'] == 'page-exists' ) {
711 // Page exists but file does not
712 $warning = wfMessage( 'filepageexists', $filename )->parse();
713 } elseif ( $exists['warning'] == 'exists-normalized' ) {
714 $warning = wfMessage( 'fileexists-extension', $filename,
715 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
716 } elseif ( $exists['warning'] == 'thumb' ) {
717 // Swapped argument order compared with other messages for backwards compatibility
718 $warning = wfMessage( 'fileexists-thumbnail-yes',
719 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
720 } elseif ( $exists['warning'] == 'thumb-name' ) {
721 // Image w/o '180px-' does not exists, but we do not like these filenames
722 $name = $file->getName();
723 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
724 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
725 } elseif ( $exists['warning'] == 'bad-prefix' ) {
726 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
733 * Construct a warning and a gallery from an array of duplicate files.
734 * @param array $dupes
737 public function getDupeWarning( $dupes ) {
742 $gallery = ImageGalleryBase
::factory( false, $this->getContext() );
743 $gallery->setShowBytes( false );
744 foreach ( $dupes as $file ) {
745 $gallery->add( $file->getTitle() );
749 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
750 $gallery->toHTML() . "</li>\n";
753 protected function getGroupName() {
758 * Should we rotate images in the preview on Special:Upload.
760 * This controls js: mw.config.get( 'wgFileCanRotate' )
762 * @todo What about non-BitmapHandler handled files?
764 public static function rotationEnabled() {
765 $bitmapHandler = new BitmapHandler();
766 return $bitmapHandler->autoRotateEnabled();
771 * Sub class of HTMLForm that provides the form section of SpecialUpload
773 class UploadForm
extends HTMLForm
{
775 protected $mForReUpload;
776 protected $mSessionKey;
777 protected $mHideIgnoreWarning;
778 protected $mDestWarningAck;
779 protected $mDestFile;
783 protected $mTextAfterSummary;
785 protected $mSourceIds;
787 protected $mMaxFileSize = array();
789 protected $mMaxUploadSize = array();
791 public function __construct( array $options = array(), IContextSource
$context = null ) {
792 if ( $context instanceof IContextSource
) {
793 $this->setContext( $context );
796 $this->mWatch
= !empty( $options['watch'] );
797 $this->mForReUpload
= !empty( $options['forreupload'] );
798 $this->mSessionKey
= isset( $options['sessionkey'] ) ?
$options['sessionkey'] : '';
799 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
800 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
801 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
803 $this->mComment
= isset( $options['description'] ) ?
804 $options['description'] : '';
806 $this->mTextTop
= isset( $options['texttop'] )
807 ?
$options['texttop'] : '';
809 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
810 ?
$options['textaftersummary'] : '';
812 $sourceDescriptor = $this->getSourceSection();
813 $descriptor = $sourceDescriptor
814 +
$this->getDescriptionSection()
815 +
$this->getOptionsSection();
817 Hooks
::run( 'UploadFormInitDescriptor', array( &$descriptor ) );
818 parent
::__construct( $descriptor, $context, 'upload' );
820 # Add a link to edit MediaWik:Licenses
821 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
822 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
823 $licensesLink = Linker
::linkKnown(
824 $this->msg( 'licenses' )->inContentLanguage()->getTitle(),
825 $this->msg( 'licenses-edit' )->escaped(),
827 array( 'action' => 'edit' )
829 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
830 $this->addFooterText( $editLicenses, 'description' );
833 # Set some form properties
834 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
835 $this->setSubmitName( 'wpUpload' );
836 # Used message keys: 'accesskey-upload', 'tooltip-upload'
837 $this->setSubmitTooltip( 'upload' );
838 $this->setId( 'mw-upload-form' );
840 # Build a list of IDs for javascript insertion
841 $this->mSourceIds
= array();
842 foreach ( $sourceDescriptor as $field ) {
843 if ( !empty( $field['id'] ) ) {
844 $this->mSourceIds
[] = $field['id'];
850 * Get the descriptor of the fieldset that contains the file source
851 * selection. The section is 'source'
853 * @return array Descriptor array
855 protected function getSourceSection() {
856 if ( $this->mSessionKey
) {
858 'SessionKey' => array(
860 'default' => $this->mSessionKey
,
862 'SourceType' => array(
864 'default' => 'Stash',
869 $canUploadByUrl = UploadFromUrl
::isEnabled()
870 && ( UploadFromUrl
::isAllowed( $this->getUser() ) === true )
871 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
872 $radio = $canUploadByUrl;
873 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
875 $descriptor = array();
876 if ( $this->mTextTop
) {
877 $descriptor['UploadFormTextTop'] = array(
879 'section' => 'source',
880 'default' => $this->mTextTop
,
885 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
886 # Limit to upload_max_filesize unless we are running under HipHop and
887 # that setting doesn't exist
889 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
890 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
891 wfShorthandToInteger( ini_get( 'post_max_size' ) )
895 $help = $this->msg( 'upload-maxfilesize',
896 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
899 // If the user can also upload by URL, there are 2 different file size limits.
900 // This extra message helps stress which limit corresponds to what.
901 if ( $canUploadByUrl ) {
902 $help .= $this->msg( 'word-separator' )->escaped();
903 $help .= $this->msg( 'upload_source_file' )->parse();
906 $descriptor['UploadFile'] = array(
907 'class' => 'UploadSourceField',
908 'section' => 'source',
910 'id' => 'wpUploadFile',
911 'radio-id' => 'wpSourceTypeFile',
912 'label-message' => 'sourcefilename',
913 'upload-type' => 'File',
916 'checked' => $selectedSourceType == 'file',
919 if ( $canUploadByUrl ) {
920 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
921 $descriptor['UploadFileURL'] = array(
922 'class' => 'UploadSourceField',
923 'section' => 'source',
924 'id' => 'wpUploadFileURL',
925 'radio-id' => 'wpSourceTypeurl',
926 'label-message' => 'sourceurl',
927 'upload-type' => 'url',
929 'help' => $this->msg( 'upload-maxfilesize',
930 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
932 $this->msg( 'word-separator' )->escaped() .
933 $this->msg( 'upload_source_url' )->parse(),
934 'checked' => $selectedSourceType == 'url',
937 Hooks
::run( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
939 $descriptor['Extensions'] = array(
941 'section' => 'source',
942 'default' => $this->getExtensionsMessage(),
950 * Get the messages indicating which extensions are preferred and prohibitted.
952 * @return string HTML string containing the message
954 protected function getExtensionsMessage() {
955 # Print a list of allowed file extensions, if so configured. We ignore
956 # MIME type here, it's incomprehensible to most people and too long.
957 $config = $this->getConfig();
959 if ( $config->get( 'CheckFileExtensions' ) ) {
960 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
961 if ( $config->get( 'StrictFileExtensions' ) ) {
962 # Everything not permitted is banned
964 '<div id="mw-upload-permitted">' .
965 $this->msg( 'upload-permitted' )
966 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
967 ->numParams( count( $fileExtensions ) )
971 # We have to list both preferred and prohibited
972 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
974 '<div id="mw-upload-preferred">' .
975 $this->msg( 'upload-preferred' )
976 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
977 ->numParams( count( $fileExtensions ) )
980 '<div id="mw-upload-prohibited">' .
981 $this->msg( 'upload-prohibited' )
982 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
983 ->numParams( count( $fileBlacklist ) )
988 # Everything is permitted.
989 $extensionsList = '';
992 return $extensionsList;
996 * Get the descriptor of the fieldset that contains the file description
997 * input. The section is 'description'
999 * @return array Descriptor array
1001 protected function getDescriptionSection() {
1002 $config = $this->getConfig();
1003 if ( $this->mSessionKey
) {
1004 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1006 $file = $stash->getFile( $this->mSessionKey
);
1007 } catch ( Exception
$e ) {
1013 $mto = $file->transform( array( 'width' => 120 ) );
1014 $this->addHeaderText(
1015 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1016 Html
::element( 'img', array(
1017 'src' => $mto->getUrl(),
1018 'class' => 'thumbimage',
1019 ) ) . '</div>', 'description' );
1023 $descriptor = array(
1024 'DestFile' => array(
1026 'section' => 'description',
1027 'id' => 'wpDestFile',
1028 'label-message' => 'destfilename',
1030 'default' => $this->mDestFile
,
1031 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1032 'nodata' => strval( $this->mDestFile
) !== '',
1034 'UploadDescription' => array(
1035 'type' => 'textarea',
1036 'section' => 'description',
1037 'id' => 'wpUploadDescription',
1038 'label-message' => $this->mForReUpload
1039 ?
'filereuploadsummary'
1040 : 'fileuploadsummary',
1041 'default' => $this->mComment
,
1042 'cols' => $this->getUser()->getIntOption( 'cols' ),
1046 if ( $this->mTextAfterSummary
) {
1047 $descriptor['UploadFormTextAfterSummary'] = array(
1049 'section' => 'description',
1050 'default' => $this->mTextAfterSummary
,
1055 $descriptor +
= array(
1056 'EditTools' => array(
1057 'type' => 'edittools',
1058 'section' => 'description',
1059 'message' => 'edittools-upload',
1063 if ( $this->mForReUpload
) {
1064 $descriptor['DestFile']['readonly'] = true;
1066 $descriptor['License'] = array(
1068 'class' => 'Licenses',
1069 'section' => 'description',
1070 'id' => 'wpLicense',
1071 'label-message' => 'license',
1075 if ( $config->get( 'UseCopyrightUpload' ) ) {
1076 $descriptor['UploadCopyStatus'] = array(
1078 'section' => 'description',
1079 'id' => 'wpUploadCopyStatus',
1080 'label-message' => 'filestatus',
1082 $descriptor['UploadSource'] = array(
1084 'section' => 'description',
1085 'id' => 'wpUploadSource',
1086 'label-message' => 'filesource',
1094 * Get the descriptor of the fieldset that contains the upload options,
1095 * such as "watch this file". The section is 'options'
1097 * @return array Descriptor array
1099 protected function getOptionsSection() {
1100 $user = $this->getUser();
1101 if ( $user->isLoggedIn() ) {
1102 $descriptor = array(
1103 'Watchthis' => array(
1105 'id' => 'wpWatchthis',
1106 'label-message' => 'watchthisupload',
1107 'section' => 'options',
1108 'default' => $this->mWatch
,
1112 if ( !$this->mHideIgnoreWarning
) {
1113 $descriptor['IgnoreWarning'] = array(
1115 'id' => 'wpIgnoreWarning',
1116 'label-message' => 'ignorewarnings',
1117 'section' => 'options',
1121 $descriptor['DestFileWarningAck'] = array(
1123 'id' => 'wpDestFileWarningAck',
1124 'default' => $this->mDestWarningAck ?
'1' : '',
1127 if ( $this->mForReUpload
) {
1128 $descriptor['ForReUpload'] = array(
1130 'id' => 'wpForReUpload',
1139 * Add the upload JS and show the form.
1141 public function show() {
1142 $this->addUploadJS();
1147 * Add upload JS to the OutputPage
1149 protected function addUploadJS() {
1150 $config = $this->getConfig();
1152 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1153 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1154 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1155 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1157 $scriptVars = array(
1158 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1159 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1160 'wgUploadAutoFill' => !$this->mForReUpload
&&
1161 // If we received mDestFile from the request, don't autofill
1162 // the wpDestFile textbox
1163 $this->mDestFile
=== '',
1164 'wgUploadSourceIds' => $this->mSourceIds
,
1165 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1166 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1167 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1168 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1169 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1170 'wgFileCanRotate' => SpecialUpload
::rotationEnabled(),
1173 $out = $this->getOutput();
1174 $out->addJsConfigVars( $scriptVars );
1176 $out->addModules( array(
1177 'mediawiki.action.edit', // For <charinsert> support
1178 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1183 * Empty function; submission is handled elsewhere.
1185 * @return bool False
1187 function trySubmit() {
1193 * A form field that contains a radio box in the label
1195 class UploadSourceField
extends HTMLTextField
{
1198 * @param array $cellAttributes
1201 function getLabelHtml( $cellAttributes = array() ) {
1202 $id = $this->mParams
['id'];
1203 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1205 if ( !empty( $this->mParams
['radio'] ) ) {
1206 if ( isset( $this->mParams
['radio-id'] ) ) {
1207 $radioId = $this->mParams
['radio-id'];
1209 // Old way. For the benefit of extensions that do not define
1210 // the 'radio-id' key.
1211 $radioId = 'wpSourceType' . $this->mParams
['upload-type'];
1215 'name' => 'wpSourceType',
1218 'value' => $this->mParams
['upload-type'],
1221 if ( !empty( $this->mParams
['checked'] ) ) {
1222 $attribs['checked'] = 'checked';
1225 $label .= Html
::element( 'input', $attribs );
1228 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1234 function getSize() {
1235 return isset( $this->mParams
['size'] )
1236 ?
$this->mParams
['size']