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 ) {
156 $this->outputHeader();
158 # Check uploading enabled
159 if ( !UploadBase
::isEnabled() ) {
160 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
163 $this->addHelpLink( 'Help:Managing files' );
166 $user = $this->getUser();
167 $permissionRequired = UploadBase
::isAllowed( $user );
168 if ( $permissionRequired !== true ) {
169 throw new PermissionsError( $permissionRequired );
173 if ( $user->isBlocked() ) {
174 throw new UserBlockedError( $user->getBlock() );
177 # Check whether we actually want to allow changing stuff
178 $this->checkReadOnly();
180 $this->loadRequest();
182 # Unsave the temporary file in case this was a cancelled upload
183 if ( $this->mCancelUpload
) {
184 if ( !$this->unsaveUploadedFile() ) {
185 # Something went wrong, so unsaveUploadedFile showed a warning
190 # Process upload or show a form
192 $this->mTokenOk
&& !$this->mCancelUpload
&&
193 ( $this->mUpload
&& $this->mUploadClicked
)
195 $this->processUpload();
197 # Backwards compatibility hook
198 if ( !Hooks
::run( 'UploadForm:initial', array( &$this ) ) ) {
199 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
203 $this->showUploadForm( $this->getUploadForm() );
207 if ( $this->mUpload
) {
208 $this->mUpload
->cleanupTempFile();
213 * Show the main upload form
215 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
217 protected function showUploadForm( $form ) {
218 # Add links if file was previously deleted
219 if ( $this->mDesiredDestName
) {
220 $this->showViewDeletedLinks();
223 if ( $form instanceof HTMLForm
) {
226 $this->getOutput()->addHTML( $form );
231 * Get an UploadForm instance with title and text properly set.
233 * @param string $message HTML string to add to the form
234 * @param string $sessionKey Session key in case this is a stashed upload
235 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
238 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
240 $context = new DerivativeContext( $this->getContext() );
241 $context->setTitle( $this->getPageTitle() ); // Remove subpage
242 $form = new UploadForm( array(
243 'watch' => $this->getWatchCheck(),
244 'forreupload' => $this->mForReUpload
,
245 'sessionkey' => $sessionKey,
246 'hideignorewarning' => $hideIgnoreWarning,
247 'destwarningack' => (bool)$this->mDestWarningAck
,
249 'description' => $this->mComment
,
250 'texttop' => $this->uploadFormTextTop
,
251 'textaftersummary' => $this->uploadFormTextAfterSummary
,
252 'destfile' => $this->mDesiredDestName
,
255 # Check the token, but only if necessary
257 !$this->mTokenOk
&& !$this->mCancelUpload
&&
258 ( $this->mUpload
&& $this->mUploadClicked
)
260 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
263 # Give a notice if the user is uploading a file that has been deleted or moved
264 # Note that this is independent from the message 'filewasdeleted' that requires JS
265 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
266 $delNotice = ''; // empty by default
267 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
268 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
270 '', array( 'lim' => 10,
271 'conds' => array( "log_action != 'revision'" ),
272 'showIfEmpty' => false,
273 'msgKey' => array( 'upload-recreate-warning' ) )
276 $form->addPreText( $delNotice );
279 $form->addPreText( '<div id="uploadtext">' .
280 $this->msg( 'uploadtext', array( $this->mDesiredDestName
) )->parseAsBlock() .
282 # Add upload error message
283 $form->addPreText( $message );
286 $uploadFooter = $this->msg( 'uploadfooter' );
287 if ( !$uploadFooter->isDisabled() ) {
288 $form->addPostText( '<div id="mw-upload-footer-message">'
289 . $uploadFooter->parseAsBlock() . "</div>\n" );
296 * Shows the "view X deleted revivions link""
298 protected function showViewDeletedLinks() {
299 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
300 $user = $this->getUser();
301 // Show a subtitle link to deleted revisions (to sysops et al only)
302 if ( $title instanceof Title
) {
303 $count = $title->isDeleted();
304 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
305 $restorelink = Linker
::linkKnown(
306 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
307 $this->msg( 'restorelink' )->numParams( $count )->escaped()
309 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
310 ->rawParams( $restorelink )->parseAsBlock();
311 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
317 * Stashes the upload and shows the main upload form.
319 * Note: only errors that can be handled by changing the name or
320 * description should be redirected here. It should be assumed that the
321 * file itself is sane and has passed UploadBase::verifyFile. This
322 * essentially means that UploadBase::VERIFICATION_ERROR and
323 * UploadBase::EMPTY_FILE should not be passed here.
325 * @param string $message HTML message to be passed to mainUploadForm
327 protected function showRecoverableUploadError( $message ) {
328 $sessionKey = $this->mUpload
->stashSession();
329 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
330 '<div class="error">' . $message . "</div>\n";
332 $form = $this->getUploadForm( $message, $sessionKey );
333 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
334 $this->showUploadForm( $form );
338 * Stashes the upload, shows the main form, but adds a "continue anyway button".
339 * Also checks whether there are actually warnings to display.
341 * @param array $warnings
342 * @return bool True if warnings were displayed, false if there are no
343 * warnings and it should continue processing
345 protected function showUploadWarning( $warnings ) {
346 # If there are no warnings, or warnings we can ignore, return early.
347 # mDestWarningAck is set when some javascript has shown the warning
348 # to the user. mForReUpload is set when the user clicks the "upload a
350 if ( !$warnings ||
( count( $warnings ) == 1
351 && isset( $warnings['exists'] )
352 && ( $this->mDestWarningAck ||
$this->mForReUpload
) )
357 $sessionKey = $this->mUpload
->stashSession();
359 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
360 . '<ul class="warning">';
361 foreach ( $warnings as $warning => $args ) {
362 if ( $warning == 'badfilename' ) {
363 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
365 if ( $warning == 'exists' ) {
366 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
367 } elseif ( $warning == 'duplicate' ) {
368 $msg = $this->getDupeWarning( $args );
369 } elseif ( $warning == 'duplicate-archive' ) {
370 if ( $args === '' ) {
371 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
374 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
375 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
379 if ( $args === true ) {
381 } elseif ( !is_array( $args ) ) {
382 $args = array( $args );
384 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
386 $warningHtml .= $msg;
388 $warningHtml .= "</ul>\n";
389 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
391 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
392 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
393 $form->addButton( 'wpUploadIgnoreWarning', $this->msg( 'ignorewarning' )->text() );
394 $form->addButton( 'wpCancelUpload', $this->msg( 'reuploaddesc' )->text() );
396 $this->showUploadForm( $form );
398 # Indicate that we showed a form
403 * Show the upload form with error message, but do not stash the file.
405 * @param string $message HTML string
407 protected function showUploadError( $message ) {
408 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
409 '<div class="error">' . $message . "</div>\n";
410 $this->showUploadForm( $this->getUploadForm( $message ) );
415 * Checks are made in SpecialUpload::execute()
417 protected function processUpload() {
418 // Fetch the file if required
419 $status = $this->mUpload
->fetchFile();
420 if ( !$status->isOK() ) {
421 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
426 if ( !Hooks
::run( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
427 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
428 // This code path is deprecated. If you want to break upload processing
429 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
430 // and UploadBase::verifyFile.
431 // If you use this hook to break uploading, the user will be returned
432 // an empty form with no error message whatsoever.
436 // Upload verification
437 $details = $this->mUpload
->verifyUpload();
438 if ( $details['status'] != UploadBase
::OK
) {
439 $this->processVerificationError( $details );
444 // Verify permissions for this title
445 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
446 if ( $permErrors !== true ) {
447 $code = array_shift( $permErrors[0] );
448 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
453 $this->mLocalFile
= $this->mUpload
->getLocalFile();
455 // Check warnings if necessary
456 if ( !$this->mIgnoreWarning
) {
457 $warnings = $this->mUpload
->checkWarnings();
458 if ( $this->showUploadWarning( $warnings ) ) {
463 // Get the page text if this is not a reupload
464 if ( !$this->mForReUpload
) {
465 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
466 $this->mCopyrightStatus
, $this->mCopyrightSource
, $this->getConfig() );
471 $status = $this->mUpload
->performUpload(
478 if ( !$status->isGood() ) {
479 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
484 // Success, redirect to description page
485 $this->mUploadSuccessful
= true;
486 Hooks
::run( 'SpecialUploadComplete', array( &$this ) );
487 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
491 * Get the initial image page text based on a comment and optional file status information
492 * @param string $comment
493 * @param string $license
494 * @param string $copyStatus
495 * @param string $source
496 * @param Config $config Configuration object to load data from
499 public static function getInitialPageText( $comment = '', $license = '',
500 $copyStatus = '', $source = '', Config
$config = null
502 if ( $config === null ) {
503 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
504 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
508 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
509 /* These messages are transcluded into the actual text of the description page.
510 * Thus, forcing them as content messages makes the upload to produce an int: template
511 * instead of hardcoding it there in the uploader language.
513 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
514 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
515 $msg[$msgName] = "{{int:$msgName}}";
517 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
521 if ( $config->get( 'UseCopyrightUpload' ) ) {
523 if ( $license != '' ) {
524 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
526 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
527 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
529 '== ' . $msg['filesource'] . " ==\n" . $source;
531 if ( $license != '' ) {
532 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
533 $pageText = $filedesc .
534 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
536 $pageText = $comment;
544 * See if we should check the 'watch this page' checkbox on the form
545 * based on the user's preferences and whether we're being asked
546 * to create a new file or update an existing one.
548 * In the case where 'watch edits' is off but 'watch creations' is on,
549 * we'll leave the box unchecked.
551 * Note that the page target can be changed *on the form*, so our check
552 * state can get out of sync.
553 * @return bool|string
555 protected function getWatchCheck() {
556 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
561 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
562 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
563 // Already watched, don't change that
567 $local = wfLocalFile( $this->mDesiredDestName
);
568 if ( $local && $local->exists() ) {
569 // We're uploading a new version of an existing file.
570 // No creation, so don't watch it if we're not already.
573 // New page should get watched if that's our option.
574 return $this->getUser()->getOption( 'watchcreations' );
579 * Provides output to the user for a result of UploadBase::verifyUpload
581 * @param array $details Result of UploadBase::verifyUpload
582 * @throws MWException
584 protected function processVerificationError( $details ) {
585 switch ( $details['status'] ) {
587 /** Statuses that only require name changing **/
588 case UploadBase
::MIN_LENGTH_PARTNAME
:
589 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
591 case UploadBase
::ILLEGAL_FILENAME
:
592 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
593 $details['filtered'] )->parse() );
595 case UploadBase
::FILENAME_TOO_LONG
:
596 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
598 case UploadBase
::FILETYPE_MISSING
:
599 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
601 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
602 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
605 /** Statuses that require reuploading **/
606 case UploadBase
::EMPTY_FILE
:
607 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
609 case UploadBase
::FILE_TOO_LARGE
:
610 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
612 case UploadBase
::FILETYPE_BADTYPE
:
613 $msg = $this->msg( 'filetype-banned-type' );
614 if ( isset( $details['blacklistedExt'] ) ) {
615 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
617 $msg->params( $details['finalExt'] );
619 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
620 $msg->params( $this->getLanguage()->commaList( $extensions ),
621 count( $extensions ) );
623 // Add PLURAL support for the first parameter. This results
624 // in a bit unlogical parameter sequence, but does not break
626 if ( isset( $details['blacklistedExt'] ) ) {
627 $msg->params( count( $details['blacklistedExt'] ) );
632 $this->showUploadError( $msg->parse() );
634 case UploadBase
::VERIFICATION_ERROR
:
635 unset( $details['status'] );
636 $code = array_shift( $details['details'] );
637 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
639 case UploadBase
::HOOK_ABORTED
:
640 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
641 $args = $details['error'];
642 $error = array_shift( $args );
644 $error = $details['error'];
648 $this->showUploadError( $this->msg( $error, $args )->parse() );
651 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
656 * Remove a temporarily kept file stashed by saveTempUploadedFile().
658 * @return bool Success
660 protected function unsaveUploadedFile() {
661 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
664 $success = $this->mUpload
->unsaveUploadedFile();
666 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
674 /*** Functions for formatting warnings ***/
677 * Formats a result of UploadBase::getExistsWarning as HTML
678 * This check is static and can be done pre-upload via AJAX
680 * @param array $exists The result of UploadBase::getExistsWarning
681 * @return string Empty string if there is no warning or an HTML fragment
683 public static function getExistsWarning( $exists ) {
688 $file = $exists['file'];
689 $filename = $file->getTitle()->getPrefixedText();
692 if ( $exists['warning'] == 'exists' ) {
694 $warning = wfMessage( 'fileexists', $filename )->parse();
695 } elseif ( $exists['warning'] == 'page-exists' ) {
696 // Page exists but file does not
697 $warning = wfMessage( 'filepageexists', $filename )->parse();
698 } elseif ( $exists['warning'] == 'exists-normalized' ) {
699 $warning = wfMessage( 'fileexists-extension', $filename,
700 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
701 } elseif ( $exists['warning'] == 'thumb' ) {
702 // Swapped argument order compared with other messages for backwards compatibility
703 $warning = wfMessage( 'fileexists-thumbnail-yes',
704 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
705 } elseif ( $exists['warning'] == 'thumb-name' ) {
706 // Image w/o '180px-' does not exists, but we do not like these filenames
707 $name = $file->getName();
708 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
709 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
710 } elseif ( $exists['warning'] == 'bad-prefix' ) {
711 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
712 } elseif ( $exists['warning'] == 'was-deleted' ) {
713 # If the file existed before and was deleted, warn the user of this
714 $ltitle = SpecialPage
::getTitleFor( 'Log' );
715 $llink = Linker
::linkKnown(
717 wfMessage( 'deletionlog' )->escaped(),
724 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
731 * Construct a warning and a gallery from an array of duplicate files.
732 * @param array $dupes
735 public function getDupeWarning( $dupes ) {
740 $gallery = ImageGalleryBase
::factory( false, $this->getContext() );
741 $gallery->setShowBytes( false );
742 foreach ( $dupes as $file ) {
743 $gallery->add( $file->getTitle() );
747 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
748 $gallery->toHTML() . "</li>\n";
751 protected function getGroupName() {
756 * Should we rotate images in the preview on Special:Upload.
758 * This controls js: mw.config.get( 'wgFileCanRotate' )
760 * @todo What about non-BitmapHandler handled files?
762 public static function rotationEnabled() {
763 $bitmapHandler = new BitmapHandler();
764 return $bitmapHandler->autoRotateEnabled();
769 * Sub class of HTMLForm that provides the form section of SpecialUpload
771 class UploadForm
extends HTMLForm
{
773 protected $mForReUpload;
774 protected $mSessionKey;
775 protected $mHideIgnoreWarning;
776 protected $mDestWarningAck;
777 protected $mDestFile;
781 protected $mTextAfterSummary;
783 protected $mSourceIds;
785 protected $mMaxFileSize = array();
787 protected $mMaxUploadSize = array();
789 public function __construct( array $options = array(), IContextSource
$context = null ) {
790 if ( $context instanceof IContextSource
) {
791 $this->setContext( $context );
794 $this->mWatch
= !empty( $options['watch'] );
795 $this->mForReUpload
= !empty( $options['forreupload'] );
796 $this->mSessionKey
= isset( $options['sessionkey'] ) ?
$options['sessionkey'] : '';
797 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
798 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
799 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
801 $this->mComment
= isset( $options['description'] ) ?
802 $options['description'] : '';
804 $this->mTextTop
= isset( $options['texttop'] )
805 ?
$options['texttop'] : '';
807 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
808 ?
$options['textaftersummary'] : '';
810 $sourceDescriptor = $this->getSourceSection();
811 $descriptor = $sourceDescriptor
812 +
$this->getDescriptionSection()
813 +
$this->getOptionsSection();
815 Hooks
::run( 'UploadFormInitDescriptor', array( &$descriptor ) );
816 parent
::__construct( $descriptor, $context, 'upload' );
818 # Add a link to edit MediaWik:Licenses
819 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
820 $licensesLink = Linker
::link(
821 Title
::makeTitle( NS_MEDIAWIKI
, 'Licenses' ),
822 $this->msg( 'licenses-edit' )->escaped(),
824 array( 'action' => 'edit' )
826 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
827 $this->addFooterText( $editLicenses, 'description' );
830 # Set some form properties
831 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
832 $this->setSubmitName( 'wpUpload' );
833 # Used message keys: 'accesskey-upload', 'tooltip-upload'
834 $this->setSubmitTooltip( 'upload' );
835 $this->setId( 'mw-upload-form' );
837 # Build a list of IDs for javascript insertion
838 $this->mSourceIds
= array();
839 foreach ( $sourceDescriptor as $field ) {
840 if ( !empty( $field['id'] ) ) {
841 $this->mSourceIds
[] = $field['id'];
847 * Get the descriptor of the fieldset that contains the file source
848 * selection. The section is 'source'
850 * @return array Descriptor array
852 protected function getSourceSection() {
853 if ( $this->mSessionKey
) {
855 'SessionKey' => array(
857 'default' => $this->mSessionKey
,
859 'SourceType' => array(
861 'default' => 'Stash',
866 $canUploadByUrl = UploadFromUrl
::isEnabled()
867 && ( UploadFromUrl
::isAllowed( $this->getUser() ) === true )
868 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
869 $radio = $canUploadByUrl;
870 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
872 $descriptor = array();
873 if ( $this->mTextTop
) {
874 $descriptor['UploadFormTextTop'] = array(
876 'section' => 'source',
877 'default' => $this->mTextTop
,
882 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
883 # Limit to upload_max_filesize unless we are running under HipHop and
884 # that setting doesn't exist
886 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
887 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
888 wfShorthandToInteger( ini_get( 'post_max_size' ) )
892 $help = $this->msg( 'upload-maxfilesize',
893 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
896 // If the user can also upload by URL, there are 2 different file size limits.
897 // This extra message helps stress which limit corresponds to what.
898 if ( $canUploadByUrl ) {
899 $help .= $this->msg( 'word-separator' )->escaped();
900 $help .= $this->msg( 'upload_source_file' )->parse();
903 $descriptor['UploadFile'] = array(
904 'class' => 'UploadSourceField',
905 'section' => 'source',
907 'id' => 'wpUploadFile',
908 'radio-id' => 'wpSourceTypeFile',
909 'label-message' => 'sourcefilename',
910 'upload-type' => 'File',
913 'checked' => $selectedSourceType == 'file',
916 if ( $canUploadByUrl ) {
917 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
918 $descriptor['UploadFileURL'] = array(
919 'class' => 'UploadSourceField',
920 'section' => 'source',
921 'id' => 'wpUploadFileURL',
922 'radio-id' => 'wpSourceTypeurl',
923 'label-message' => 'sourceurl',
924 'upload-type' => 'url',
926 'help' => $this->msg( 'upload-maxfilesize',
927 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
929 $this->msg( 'word-separator' )->escaped() .
930 $this->msg( 'upload_source_url' )->parse(),
931 'checked' => $selectedSourceType == 'url',
934 Hooks
::run( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
936 $descriptor['Extensions'] = array(
938 'section' => 'source',
939 'default' => $this->getExtensionsMessage(),
947 * Get the messages indicating which extensions are preferred and prohibitted.
949 * @return string HTML string containing the message
951 protected function getExtensionsMessage() {
952 # Print a list of allowed file extensions, if so configured. We ignore
953 # MIME type here, it's incomprehensible to most people and too long.
954 $config = $this->getConfig();
956 if ( $config->get( 'CheckFileExtensions' ) ) {
957 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
958 if ( $config->get( 'StrictFileExtensions' ) ) {
959 # Everything not permitted is banned
961 '<div id="mw-upload-permitted">' .
962 $this->msg( 'upload-permitted' )
963 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
964 ->numParams( count( $fileExtensions ) )
968 # We have to list both preferred and prohibited
969 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
971 '<div id="mw-upload-preferred">' .
972 $this->msg( 'upload-preferred' )
973 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
974 ->numParams( count( $fileExtensions ) )
977 '<div id="mw-upload-prohibited">' .
978 $this->msg( 'upload-prohibited' )
979 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
980 ->numParams( count( $fileBlacklist ) )
985 # Everything is permitted.
986 $extensionsList = '';
989 return $extensionsList;
993 * Get the descriptor of the fieldset that contains the file description
994 * input. The section is 'description'
996 * @return array Descriptor array
998 protected function getDescriptionSection() {
999 $config = $this->getConfig();
1000 if ( $this->mSessionKey
) {
1001 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1003 $file = $stash->getFile( $this->mSessionKey
);
1004 } catch ( Exception
$e ) {
1010 $mto = $file->transform( array( 'width' => 120 ) );
1011 $this->addHeaderText(
1012 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1013 Html
::element( 'img', array(
1014 'src' => $mto->getUrl(),
1015 'class' => 'thumbimage',
1016 ) ) . '</div>', 'description' );
1020 $descriptor = array(
1021 'DestFile' => array(
1023 'section' => 'description',
1024 'id' => 'wpDestFile',
1025 'label-message' => 'destfilename',
1027 'default' => $this->mDestFile
,
1028 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1029 'nodata' => strval( $this->mDestFile
) !== '',
1031 'UploadDescription' => array(
1032 'type' => 'textarea',
1033 'section' => 'description',
1034 'id' => 'wpUploadDescription',
1035 'label-message' => $this->mForReUpload
1036 ?
'filereuploadsummary'
1037 : 'fileuploadsummary',
1038 'default' => $this->mComment
,
1039 'cols' => $this->getUser()->getIntOption( 'cols' ),
1043 if ( $this->mTextAfterSummary
) {
1044 $descriptor['UploadFormTextAfterSummary'] = array(
1046 'section' => 'description',
1047 'default' => $this->mTextAfterSummary
,
1052 $descriptor +
= array(
1053 'EditTools' => array(
1054 'type' => 'edittools',
1055 'section' => 'description',
1056 'message' => 'edittools-upload',
1060 if ( $this->mForReUpload
) {
1061 $descriptor['DestFile']['readonly'] = true;
1063 $descriptor['License'] = array(
1065 'class' => 'Licenses',
1066 'section' => 'description',
1067 'id' => 'wpLicense',
1068 'label-message' => 'license',
1072 if ( $config->get( 'UseCopyrightUpload' ) ) {
1073 $descriptor['UploadCopyStatus'] = array(
1075 'section' => 'description',
1076 'id' => 'wpUploadCopyStatus',
1077 'label-message' => 'filestatus',
1079 $descriptor['UploadSource'] = array(
1081 'section' => 'description',
1082 'id' => 'wpUploadSource',
1083 'label-message' => 'filesource',
1091 * Get the descriptor of the fieldset that contains the upload options,
1092 * such as "watch this file". The section is 'options'
1094 * @return array Descriptor array
1096 protected function getOptionsSection() {
1097 $user = $this->getUser();
1098 if ( $user->isLoggedIn() ) {
1099 $descriptor = array(
1100 'Watchthis' => array(
1102 'id' => 'wpWatchthis',
1103 'label-message' => 'watchthisupload',
1104 'section' => 'options',
1105 'default' => $this->mWatch
,
1109 if ( !$this->mHideIgnoreWarning
) {
1110 $descriptor['IgnoreWarning'] = array(
1112 'id' => 'wpIgnoreWarning',
1113 'label-message' => 'ignorewarnings',
1114 'section' => 'options',
1118 $descriptor['DestFileWarningAck'] = array(
1120 'id' => 'wpDestFileWarningAck',
1121 'default' => $this->mDestWarningAck ?
'1' : '',
1124 if ( $this->mForReUpload
) {
1125 $descriptor['ForReUpload'] = array(
1127 'id' => 'wpForReUpload',
1136 * Add the upload JS and show the form.
1138 public function show() {
1139 $this->addUploadJS();
1144 * Add upload JS to the OutputPage
1146 protected function addUploadJS() {
1147 $config = $this->getConfig();
1149 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1150 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1151 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1152 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1154 $scriptVars = array(
1155 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1156 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1157 'wgUploadAutoFill' => !$this->mForReUpload
&&
1158 // If we received mDestFile from the request, don't autofill
1159 // the wpDestFile textbox
1160 $this->mDestFile
=== '',
1161 'wgUploadSourceIds' => $this->mSourceIds
,
1162 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1163 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1164 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1165 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1166 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1167 'wgFileCanRotate' => SpecialUpload
::rotationEnabled(),
1170 $out = $this->getOutput();
1171 $out->addJsConfigVars( $scriptVars );
1173 $out->addModules( array(
1174 'mediawiki.action.edit', // For <charinsert> support
1175 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1180 * Empty function; submission is handled elsewhere.
1182 * @return bool False
1184 function trySubmit() {
1190 * A form field that contains a radio box in the label
1192 class UploadSourceField
extends HTMLTextField
{
1195 * @param array $cellAttributes
1198 function getLabelHtml( $cellAttributes = array() ) {
1199 $id = $this->mParams
['id'];
1200 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1202 if ( !empty( $this->mParams
['radio'] ) ) {
1203 if ( isset( $this->mParams
['radio-id'] ) ) {
1204 $radioId = $this->mParams
['radio-id'];
1206 // Old way. For the benefit of extensions that do not define
1207 // the 'radio-id' key.
1208 $radioId = 'wpSourceType' . $this->mParams
['upload-type'];
1212 'name' => 'wpSourceType',
1215 'value' => $this->mParams
['upload-type'],
1218 if ( !empty( $this->mParams
['checked'] ) ) {
1219 $attribs['checked'] = 'checked';
1222 $label .= Html
::element( 'input', $attribs );
1225 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1231 function getSize() {
1232 return isset( $this->mParams
['size'] )
1233 ?
$this->mParams
['size']