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' );
164 $user = $this->getUser();
165 $permissionRequired = UploadBase
::isAllowed( $user );
166 if ( $permissionRequired !== true ) {
167 throw new PermissionsError( $permissionRequired );
171 if ( $user->isBlocked() ) {
172 throw new UserBlockedError( $user->getBlock() );
175 # Check whether we actually want to allow changing stuff
176 $this->checkReadOnly();
178 $this->loadRequest();
180 # Unsave the temporary file in case this was a cancelled upload
181 if ( $this->mCancelUpload
) {
182 if ( !$this->unsaveUploadedFile() ) {
183 # Something went wrong, so unsaveUploadedFile showed a warning
188 # Process upload or show a form
190 $this->mTokenOk
&& !$this->mCancelUpload
&&
191 ( $this->mUpload
&& $this->mUploadClicked
)
193 $this->processUpload();
195 # Backwards compatibility hook
196 if ( !Hooks
::run( 'UploadForm:initial', array( &$this ) ) ) {
197 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
201 $this->showUploadForm( $this->getUploadForm() );
205 if ( $this->mUpload
) {
206 $this->mUpload
->cleanupTempFile();
211 * Show the main upload form
213 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
215 protected function showUploadForm( $form ) {
216 # Add links if file was previously deleted
217 if ( $this->mDesiredDestName
) {
218 $this->showViewDeletedLinks();
221 if ( $form instanceof HTMLForm
) {
224 $this->getOutput()->addHTML( $form );
229 * Get an UploadForm instance with title and text properly set.
231 * @param string $message HTML string to add to the form
232 * @param string $sessionKey Session key in case this is a stashed upload
233 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
236 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
238 $context = new DerivativeContext( $this->getContext() );
239 $context->setTitle( $this->getPageTitle() ); // Remove subpage
240 $form = new UploadForm( array(
241 'watch' => $this->getWatchCheck(),
242 'forreupload' => $this->mForReUpload
,
243 'sessionkey' => $sessionKey,
244 'hideignorewarning' => $hideIgnoreWarning,
245 'destwarningack' => (bool)$this->mDestWarningAck
,
247 'description' => $this->mComment
,
248 'texttop' => $this->uploadFormTextTop
,
249 'textaftersummary' => $this->uploadFormTextAfterSummary
,
250 'destfile' => $this->mDesiredDestName
,
253 # Check the token, but only if necessary
255 !$this->mTokenOk
&& !$this->mCancelUpload
&&
256 ( $this->mUpload
&& $this->mUploadClicked
)
258 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
261 # Give a notice if the user is uploading a file that has been deleted or moved
262 # Note that this is independent from the message 'filewasdeleted' that requires JS
263 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
264 $delNotice = ''; // empty by default
265 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
266 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
268 '', array( 'lim' => 10,
269 'conds' => array( "log_action != 'revision'" ),
270 'showIfEmpty' => false,
271 'msgKey' => array( 'upload-recreate-warning' ) )
274 $form->addPreText( $delNotice );
277 $form->addPreText( '<div id="uploadtext">' .
278 $this->msg( 'uploadtext', array( $this->mDesiredDestName
) )->parseAsBlock() .
280 # Add upload error message
281 $form->addPreText( $message );
284 $uploadFooter = $this->msg( 'uploadfooter' );
285 if ( !$uploadFooter->isDisabled() ) {
286 $form->addPostText( '<div id="mw-upload-footer-message">'
287 . $uploadFooter->parseAsBlock() . "</div>\n" );
294 * Shows the "view X deleted revivions link""
296 protected function showViewDeletedLinks() {
297 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
298 $user = $this->getUser();
299 // Show a subtitle link to deleted revisions (to sysops et al only)
300 if ( $title instanceof Title
) {
301 $count = $title->isDeleted();
302 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
303 $restorelink = Linker
::linkKnown(
304 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
305 $this->msg( 'restorelink' )->numParams( $count )->escaped()
307 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
308 ->rawParams( $restorelink )->parseAsBlock();
309 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
315 * Stashes the upload and shows the main upload form.
317 * Note: only errors that can be handled by changing the name or
318 * description should be redirected here. It should be assumed that the
319 * file itself is sane and has passed UploadBase::verifyFile. This
320 * essentially means that UploadBase::VERIFICATION_ERROR and
321 * UploadBase::EMPTY_FILE should not be passed here.
323 * @param string $message HTML message to be passed to mainUploadForm
325 protected function showRecoverableUploadError( $message ) {
326 $sessionKey = $this->mUpload
->stashSession();
327 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
328 '<div class="error">' . $message . "</div>\n";
330 $form = $this->getUploadForm( $message, $sessionKey );
331 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
332 $this->showUploadForm( $form );
336 * Stashes the upload, shows the main form, but adds a "continue anyway button".
337 * Also checks whether there are actually warnings to display.
339 * @param array $warnings
340 * @return bool True if warnings were displayed, false if there are no
341 * warnings and it should continue processing
343 protected function showUploadWarning( $warnings ) {
344 # If there are no warnings, or warnings we can ignore, return early.
345 # mDestWarningAck is set when some javascript has shown the warning
346 # to the user. mForReUpload is set when the user clicks the "upload a
348 if ( !$warnings ||
( count( $warnings ) == 1
349 && isset( $warnings['exists'] )
350 && ( $this->mDestWarningAck ||
$this->mForReUpload
) )
355 $sessionKey = $this->mUpload
->stashSession();
357 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
358 . '<ul class="warning">';
359 foreach ( $warnings as $warning => $args ) {
360 if ( $warning == 'badfilename' ) {
361 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
363 if ( $warning == 'exists' ) {
364 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
365 } elseif ( $warning == 'duplicate' ) {
366 $msg = $this->getDupeWarning( $args );
367 } elseif ( $warning == 'duplicate-archive' ) {
368 if ( $args === '' ) {
369 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
372 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
373 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
377 if ( $args === true ) {
379 } elseif ( !is_array( $args ) ) {
380 $args = array( $args );
382 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
384 $warningHtml .= $msg;
386 $warningHtml .= "</ul>\n";
387 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
389 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
390 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
391 $form->addButton( 'wpUploadIgnoreWarning', $this->msg( 'ignorewarning' )->text() );
392 $form->addButton( 'wpCancelUpload', $this->msg( 'reuploaddesc' )->text() );
394 $this->showUploadForm( $form );
396 # Indicate that we showed a form
401 * Show the upload form with error message, but do not stash the file.
403 * @param string $message HTML string
405 protected function showUploadError( $message ) {
406 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
407 '<div class="error">' . $message . "</div>\n";
408 $this->showUploadForm( $this->getUploadForm( $message ) );
413 * Checks are made in SpecialUpload::execute()
415 protected function processUpload() {
416 // Fetch the file if required
417 $status = $this->mUpload
->fetchFile();
418 if ( !$status->isOK() ) {
419 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
424 if ( !Hooks
::run( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
425 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
426 // This code path is deprecated. If you want to break upload processing
427 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
428 // and UploadBase::verifyFile.
429 // If you use this hook to break uploading, the user will be returned
430 // an empty form with no error message whatsoever.
434 // Upload verification
435 $details = $this->mUpload
->verifyUpload();
436 if ( $details['status'] != UploadBase
::OK
) {
437 $this->processVerificationError( $details );
442 // Verify permissions for this title
443 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
444 if ( $permErrors !== true ) {
445 $code = array_shift( $permErrors[0] );
446 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
451 $this->mLocalFile
= $this->mUpload
->getLocalFile();
453 // Check warnings if necessary
454 if ( !$this->mIgnoreWarning
) {
455 $warnings = $this->mUpload
->checkWarnings();
456 if ( $this->showUploadWarning( $warnings ) ) {
461 // Get the page text if this is not a reupload
462 if ( !$this->mForReUpload
) {
463 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
464 $this->mCopyrightStatus
, $this->mCopyrightSource
, $this->getConfig() );
469 $status = $this->mUpload
->performUpload(
476 if ( !$status->isGood() ) {
477 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
482 // Success, redirect to description page
483 $this->mUploadSuccessful
= true;
484 Hooks
::run( 'SpecialUploadComplete', array( &$this ) );
485 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
489 * Get the initial image page text based on a comment and optional file status information
490 * @param string $comment
491 * @param string $license
492 * @param string $copyStatus
493 * @param string $source
494 * @param Config $config Configuration object to load data from
497 public static function getInitialPageText( $comment = '', $license = '',
498 $copyStatus = '', $source = '', Config
$config = null
500 if ( $config === null ) {
501 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
502 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
506 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
507 /* These messages are transcluded into the actual text of the description page.
508 * Thus, forcing them as content messages makes the upload to produce an int: template
509 * instead of hardcoding it there in the uploader language.
511 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
512 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
513 $msg[$msgName] = "{{int:$msgName}}";
515 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
519 if ( $config->get( 'UseCopyrightUpload' ) ) {
521 if ( $license != '' ) {
522 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
524 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
525 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
527 '== ' . $msg['filesource'] . " ==\n" . $source;
529 if ( $license != '' ) {
530 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
531 $pageText = $filedesc .
532 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
534 $pageText = $comment;
542 * See if we should check the 'watch this page' checkbox on the form
543 * based on the user's preferences and whether we're being asked
544 * to create a new file or update an existing one.
546 * In the case where 'watch edits' is off but 'watch creations' is on,
547 * we'll leave the box unchecked.
549 * Note that the page target can be changed *on the form*, so our check
550 * state can get out of sync.
551 * @return bool|string
553 protected function getWatchCheck() {
554 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
559 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
560 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
561 // Already watched, don't change that
565 $local = wfLocalFile( $this->mDesiredDestName
);
566 if ( $local && $local->exists() ) {
567 // We're uploading a new version of an existing file.
568 // No creation, so don't watch it if we're not already.
571 // New page should get watched if that's our option.
572 return $this->getUser()->getOption( 'watchcreations' );
577 * Provides output to the user for a result of UploadBase::verifyUpload
579 * @param array $details Result of UploadBase::verifyUpload
580 * @throws MWException
582 protected function processVerificationError( $details ) {
583 switch ( $details['status'] ) {
585 /** Statuses that only require name changing **/
586 case UploadBase
::MIN_LENGTH_PARTNAME
:
587 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
589 case UploadBase
::ILLEGAL_FILENAME
:
590 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
591 $details['filtered'] )->parse() );
593 case UploadBase
::FILENAME_TOO_LONG
:
594 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
596 case UploadBase
::FILETYPE_MISSING
:
597 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
599 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
600 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
603 /** Statuses that require reuploading **/
604 case UploadBase
::EMPTY_FILE
:
605 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
607 case UploadBase
::FILE_TOO_LARGE
:
608 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
610 case UploadBase
::FILETYPE_BADTYPE
:
611 $msg = $this->msg( 'filetype-banned-type' );
612 if ( isset( $details['blacklistedExt'] ) ) {
613 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
615 $msg->params( $details['finalExt'] );
617 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
618 $msg->params( $this->getLanguage()->commaList( $extensions ),
619 count( $extensions ) );
621 // Add PLURAL support for the first parameter. This results
622 // in a bit unlogical parameter sequence, but does not break
624 if ( isset( $details['blacklistedExt'] ) ) {
625 $msg->params( count( $details['blacklistedExt'] ) );
630 $this->showUploadError( $msg->parse() );
632 case UploadBase
::VERIFICATION_ERROR
:
633 unset( $details['status'] );
634 $code = array_shift( $details['details'] );
635 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
637 case UploadBase
::HOOK_ABORTED
:
638 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
639 $args = $details['error'];
640 $error = array_shift( $args );
642 $error = $details['error'];
646 $this->showUploadError( $this->msg( $error, $args )->parse() );
649 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
654 * Remove a temporarily kept file stashed by saveTempUploadedFile().
656 * @return bool Success
658 protected function unsaveUploadedFile() {
659 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
662 $success = $this->mUpload
->unsaveUploadedFile();
664 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
672 /*** Functions for formatting warnings ***/
675 * Formats a result of UploadBase::getExistsWarning as HTML
676 * This check is static and can be done pre-upload via AJAX
678 * @param array $exists The result of UploadBase::getExistsWarning
679 * @return string Empty string if there is no warning or an HTML fragment
681 public static function getExistsWarning( $exists ) {
686 $file = $exists['file'];
687 $filename = $file->getTitle()->getPrefixedText();
690 if ( $exists['warning'] == 'exists' ) {
692 $warning = wfMessage( 'fileexists', $filename )->parse();
693 } elseif ( $exists['warning'] == 'page-exists' ) {
694 // Page exists but file does not
695 $warning = wfMessage( 'filepageexists', $filename )->parse();
696 } elseif ( $exists['warning'] == 'exists-normalized' ) {
697 $warning = wfMessage( 'fileexists-extension', $filename,
698 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
699 } elseif ( $exists['warning'] == 'thumb' ) {
700 // Swapped argument order compared with other messages for backwards compatibility
701 $warning = wfMessage( 'fileexists-thumbnail-yes',
702 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
703 } elseif ( $exists['warning'] == 'thumb-name' ) {
704 // Image w/o '180px-' does not exists, but we do not like these filenames
705 $name = $file->getName();
706 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
707 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
708 } elseif ( $exists['warning'] == 'bad-prefix' ) {
709 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
710 } elseif ( $exists['warning'] == 'was-deleted' ) {
711 # If the file existed before and was deleted, warn the user of this
712 $ltitle = SpecialPage
::getTitleFor( 'Log' );
713 $llink = Linker
::linkKnown(
715 wfMessage( 'deletionlog' )->escaped(),
722 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
729 * Construct a warning and a gallery from an array of duplicate files.
730 * @param array $dupes
733 public function getDupeWarning( $dupes ) {
738 $gallery = ImageGalleryBase
::factory( false, $this->getContext() );
739 $gallery->setShowBytes( false );
740 foreach ( $dupes as $file ) {
741 $gallery->add( $file->getTitle() );
745 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
746 $gallery->toHTML() . "</li>\n";
749 protected function getGroupName() {
754 * Should we rotate images in the preview on Special:Upload.
756 * This controls js: mw.config.get( 'wgFileCanRotate' )
758 * @todo What about non-BitmapHandler handled files?
760 public static function rotationEnabled() {
761 $bitmapHandler = new BitmapHandler();
762 return $bitmapHandler->autoRotateEnabled();
767 * Sub class of HTMLForm that provides the form section of SpecialUpload
769 class UploadForm
extends HTMLForm
{
771 protected $mForReUpload;
772 protected $mSessionKey;
773 protected $mHideIgnoreWarning;
774 protected $mDestWarningAck;
775 protected $mDestFile;
779 protected $mTextAfterSummary;
781 protected $mSourceIds;
783 protected $mMaxFileSize = array();
785 protected $mMaxUploadSize = array();
787 public function __construct( array $options = array(), IContextSource
$context = null ) {
788 $this->mWatch
= !empty( $options['watch'] );
789 $this->mForReUpload
= !empty( $options['forreupload'] );
790 $this->mSessionKey
= isset( $options['sessionkey'] ) ?
$options['sessionkey'] : '';
791 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
792 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
793 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
795 $this->mComment
= isset( $options['description'] ) ?
796 $options['description'] : '';
798 $this->mTextTop
= isset( $options['texttop'] )
799 ?
$options['texttop'] : '';
801 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
802 ?
$options['textaftersummary'] : '';
804 $sourceDescriptor = $this->getSourceSection();
805 $descriptor = $sourceDescriptor
806 +
$this->getDescriptionSection()
807 +
$this->getOptionsSection();
809 Hooks
::run( 'UploadFormInitDescriptor', array( &$descriptor ) );
810 parent
::__construct( $descriptor, $context, 'upload' );
812 # Add a link to edit MediaWik:Licenses
813 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
814 $licensesLink = Linker
::link(
815 Title
::makeTitle( NS_MEDIAWIKI
, 'Licenses' ),
816 $this->msg( 'licenses-edit' )->escaped(),
818 array( 'action' => 'edit' )
820 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
821 $this->addFooterText( $editLicenses, 'description' );
824 # Set some form properties
825 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
826 $this->setSubmitName( 'wpUpload' );
827 # Used message keys: 'accesskey-upload', 'tooltip-upload'
828 $this->setSubmitTooltip( 'upload' );
829 $this->setId( 'mw-upload-form' );
831 # Build a list of IDs for javascript insertion
832 $this->mSourceIds
= array();
833 foreach ( $sourceDescriptor as $field ) {
834 if ( !empty( $field['id'] ) ) {
835 $this->mSourceIds
[] = $field['id'];
841 * Get the descriptor of the fieldset that contains the file source
842 * selection. The section is 'source'
844 * @return array Descriptor array
846 protected function getSourceSection() {
847 if ( $this->mSessionKey
) {
849 'SessionKey' => array(
851 'default' => $this->mSessionKey
,
853 'SourceType' => array(
855 'default' => 'Stash',
860 $canUploadByUrl = UploadFromUrl
::isEnabled()
861 && ( UploadFromUrl
::isAllowed( $this->getUser() ) === true )
862 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
863 $radio = $canUploadByUrl;
864 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
866 $descriptor = array();
867 if ( $this->mTextTop
) {
868 $descriptor['UploadFormTextTop'] = array(
870 'section' => 'source',
871 'default' => $this->mTextTop
,
876 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
877 # Limit to upload_max_filesize unless we are running under HipHop and
878 # that setting doesn't exist
880 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
881 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
882 wfShorthandToInteger( ini_get( 'post_max_size' ) )
886 $descriptor['UploadFile'] = array(
887 'class' => 'UploadSourceField',
888 'section' => 'source',
890 'id' => 'wpUploadFile',
891 'radio-id' => 'wpSourceTypeFile',
892 'label-message' => 'sourcefilename',
893 'upload-type' => 'File',
895 'help' => $this->msg( 'upload-maxfilesize',
896 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
898 $this->msg( 'word-separator' )->escaped() .
899 $this->msg( 'upload_source_file' )->escaped(),
900 'checked' => $selectedSourceType == 'file',
903 if ( $canUploadByUrl ) {
904 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
905 $descriptor['UploadFileURL'] = array(
906 'class' => 'UploadSourceField',
907 'section' => 'source',
908 'id' => 'wpUploadFileURL',
909 'radio-id' => 'wpSourceTypeurl',
910 'label-message' => 'sourceurl',
911 'upload-type' => 'url',
913 'help' => $this->msg( 'upload-maxfilesize',
914 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
916 $this->msg( 'word-separator' )->escaped() .
917 $this->msg( 'upload_source_url' )->parse(),
918 'checked' => $selectedSourceType == 'url',
921 Hooks
::run( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
923 $descriptor['Extensions'] = array(
925 'section' => 'source',
926 'default' => $this->getExtensionsMessage(),
934 * Get the messages indicating which extensions are preferred and prohibitted.
936 * @return string HTML string containing the message
938 protected function getExtensionsMessage() {
939 # Print a list of allowed file extensions, if so configured. We ignore
940 # MIME type here, it's incomprehensible to most people and too long.
941 $config = $this->getConfig();
943 if ( $config->get( 'CheckFileExtensions' ) ) {
944 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
945 if ( $config->get( 'StrictFileExtensions' ) ) {
946 # Everything not permitted is banned
948 '<div id="mw-upload-permitted">' .
949 $this->msg( 'upload-permitted' )
950 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
951 ->numParams( count( $fileExtensions ) )
955 # We have to list both preferred and prohibited
956 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
958 '<div id="mw-upload-preferred">' .
959 $this->msg( 'upload-preferred' )
960 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
961 ->numParams( count( $fileExtensions ) )
964 '<div id="mw-upload-prohibited">' .
965 $this->msg( 'upload-prohibited' )
966 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
967 ->numParams( count( $fileBlacklist ) )
972 # Everything is permitted.
973 $extensionsList = '';
976 return $extensionsList;
980 * Get the descriptor of the fieldset that contains the file description
981 * input. The section is 'description'
983 * @return array Descriptor array
985 protected function getDescriptionSection() {
986 $config = $this->getConfig();
987 if ( $this->mSessionKey
) {
988 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
990 $file = $stash->getFile( $this->mSessionKey
);
991 } catch ( Exception
$e ) {
997 $mto = $file->transform( array( 'width' => 120 ) );
998 $this->addHeaderText(
999 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1000 Html
::element( 'img', array(
1001 'src' => $mto->getUrl(),
1002 'class' => 'thumbimage',
1003 ) ) . '</div>', 'description' );
1007 $descriptor = array(
1008 'DestFile' => array(
1010 'section' => 'description',
1011 'id' => 'wpDestFile',
1012 'label-message' => 'destfilename',
1014 'default' => $this->mDestFile
,
1015 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1016 'nodata' => strval( $this->mDestFile
) !== '',
1018 'UploadDescription' => array(
1019 'type' => 'textarea',
1020 'section' => 'description',
1021 'id' => 'wpUploadDescription',
1022 'label-message' => $this->mForReUpload
1023 ?
'filereuploadsummary'
1024 : 'fileuploadsummary',
1025 'default' => $this->mComment
,
1026 'cols' => $this->getUser()->getIntOption( 'cols' ),
1030 if ( $this->mTextAfterSummary
) {
1031 $descriptor['UploadFormTextAfterSummary'] = array(
1033 'section' => 'description',
1034 'default' => $this->mTextAfterSummary
,
1039 $descriptor +
= array(
1040 'EditTools' => array(
1041 'type' => 'edittools',
1042 'section' => 'description',
1043 'message' => 'edittools-upload',
1047 if ( $this->mForReUpload
) {
1048 $descriptor['DestFile']['readonly'] = true;
1050 $descriptor['License'] = array(
1052 'class' => 'Licenses',
1053 'section' => 'description',
1054 'id' => 'wpLicense',
1055 'label-message' => 'license',
1059 if ( $config->get( 'UseCopyrightUpload' ) ) {
1060 $descriptor['UploadCopyStatus'] = array(
1062 'section' => 'description',
1063 'id' => 'wpUploadCopyStatus',
1064 'label-message' => 'filestatus',
1066 $descriptor['UploadSource'] = array(
1068 'section' => 'description',
1069 'id' => 'wpUploadSource',
1070 'label-message' => 'filesource',
1078 * Get the descriptor of the fieldset that contains the upload options,
1079 * such as "watch this file". The section is 'options'
1081 * @return array Descriptor array
1083 protected function getOptionsSection() {
1084 $user = $this->getUser();
1085 if ( $user->isLoggedIn() ) {
1086 $descriptor = array(
1087 'Watchthis' => array(
1089 'id' => 'wpWatchthis',
1090 'label-message' => 'watchthisupload',
1091 'section' => 'options',
1092 'default' => $this->mWatch
,
1096 if ( !$this->mHideIgnoreWarning
) {
1097 $descriptor['IgnoreWarning'] = array(
1099 'id' => 'wpIgnoreWarning',
1100 'label-message' => 'ignorewarnings',
1101 'section' => 'options',
1105 $descriptor['DestFileWarningAck'] = array(
1107 'id' => 'wpDestFileWarningAck',
1108 'default' => $this->mDestWarningAck ?
'1' : '',
1111 if ( $this->mForReUpload
) {
1112 $descriptor['ForReUpload'] = array(
1114 'id' => 'wpForReUpload',
1123 * Add the upload JS and show the form.
1125 public function show() {
1126 $this->addUploadJS();
1131 * Add upload JS to the OutputPage
1133 protected function addUploadJS() {
1134 $config = $this->getConfig();
1136 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1137 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1138 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1139 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1141 $scriptVars = array(
1142 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1143 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1144 'wgUploadAutoFill' => !$this->mForReUpload
&&
1145 // If we received mDestFile from the request, don't autofill
1146 // the wpDestFile textbox
1147 $this->mDestFile
=== '',
1148 'wgUploadSourceIds' => $this->mSourceIds
,
1149 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1150 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1151 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1152 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1153 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1154 'wgFileCanRotate' => SpecialUpload
::rotationEnabled(),
1157 $out = $this->getOutput();
1158 $out->addJsConfigVars( $scriptVars );
1160 $out->addModules( array(
1161 'mediawiki.action.edit', // For <charinsert> support
1162 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1167 * Empty function; submission is handled elsewhere.
1169 * @return bool False
1171 function trySubmit() {
1177 * A form field that contains a radio box in the label
1179 class UploadSourceField
extends HTMLTextField
{
1182 * @param array $cellAttributes
1185 function getLabelHtml( $cellAttributes = array() ) {
1186 $id = $this->mParams
['id'];
1187 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1189 if ( !empty( $this->mParams
['radio'] ) ) {
1190 if ( isset( $this->mParams
['radio-id'] ) ) {
1191 $radioId = $this->mParams
['radio-id'];
1193 // Old way. For the benefit of extensions that do not define
1194 // the 'radio-id' key.
1195 $radioId = 'wpSourceType' . $this->mParams
['upload-type'];
1199 'name' => 'wpSourceType',
1202 'value' => $this->mParams
['upload-type'],
1205 if ( !empty( $this->mParams
['checked'] ) ) {
1206 $attribs['checked'] = 'checked';
1209 $label .= Html
::element( 'input', $attribs );
1212 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1218 function getSize() {
1219 return isset( $this->mParams
['size'] )
1220 ?
$this->mParams
['size']