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
147 public function execute( $par ) {
149 $this->outputHeader();
151 # Check uploading enabled
152 if ( !UploadBase
::isEnabled() ) {
153 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
157 $user = $this->getUser();
158 $permissionRequired = UploadBase
::isAllowed( $user );
159 if ( $permissionRequired !== true ) {
160 throw new PermissionsError( $permissionRequired );
164 if ( $user->isBlocked() ) {
165 throw new UserBlockedError( $user->getBlock() );
168 # Check whether we actually want to allow changing stuff
169 $this->checkReadOnly();
171 $this->loadRequest();
173 # Unsave the temporary file in case this was a cancelled upload
174 if ( $this->mCancelUpload
) {
175 if ( !$this->unsaveUploadedFile() ) {
176 # Something went wrong, so unsaveUploadedFile showed a warning
181 # Process upload or show a form
183 $this->mTokenOk
&& !$this->mCancelUpload
&&
184 ( $this->mUpload
&& $this->mUploadClicked
)
186 $this->processUpload();
188 # Backwards compatibility hook
189 if ( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
190 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
194 $this->showUploadForm( $this->getUploadForm() );
198 if ( $this->mUpload
) {
199 $this->mUpload
->cleanupTempFile();
204 * Show the main upload form
206 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
208 protected function showUploadForm( $form ) {
209 # Add links if file was previously deleted
210 if ( $this->mDesiredDestName
) {
211 $this->showViewDeletedLinks();
214 if ( $form instanceof HTMLForm
) {
217 $this->getOutput()->addHTML( $form );
222 * Get an UploadForm instance with title and text properly set.
224 * @param string $message HTML string to add to the form
225 * @param string $sessionKey Session key in case this is a stashed upload
226 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
229 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
231 $context = new DerivativeContext( $this->getContext() );
232 $context->setTitle( $this->getPageTitle() ); // Remove subpage
233 $form = new UploadForm( array(
234 'watch' => $this->getWatchCheck(),
235 'forreupload' => $this->mForReUpload
,
236 'sessionkey' => $sessionKey,
237 'hideignorewarning' => $hideIgnoreWarning,
238 'destwarningack' => (bool)$this->mDestWarningAck
,
240 'description' => $this->mComment
,
241 'texttop' => $this->uploadFormTextTop
,
242 'textaftersummary' => $this->uploadFormTextAfterSummary
,
243 'destfile' => $this->mDesiredDestName
,
246 # Check the token, but only if necessary
248 !$this->mTokenOk
&& !$this->mCancelUpload
&&
249 ( $this->mUpload
&& $this->mUploadClicked
)
251 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
254 # Give a notice if the user is uploading a file that has been deleted or moved
255 # Note that this is independent from the message 'filewasdeleted' that requires JS
256 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
257 $delNotice = ''; // empty by default
258 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
259 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
261 '', array( 'lim' => 10,
262 'conds' => array( "log_action != 'revision'" ),
263 'showIfEmpty' => false,
264 'msgKey' => array( 'upload-recreate-warning' ) )
267 $form->addPreText( $delNotice );
270 $form->addPreText( '<div id="uploadtext">' .
271 $this->msg( 'uploadtext', array( $this->mDesiredDestName
) )->parseAsBlock() .
273 # Add upload error message
274 $form->addPreText( $message );
277 $uploadFooter = $this->msg( 'uploadfooter' );
278 if ( !$uploadFooter->isDisabled() ) {
279 $form->addPostText( '<div id="mw-upload-footer-message">'
280 . $uploadFooter->parseAsBlock() . "</div>\n" );
287 * Shows the "view X deleted revivions link""
289 protected function showViewDeletedLinks() {
290 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
291 $user = $this->getUser();
292 // Show a subtitle link to deleted revisions (to sysops et al only)
293 if ( $title instanceof Title
) {
294 $count = $title->isDeleted();
295 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
296 $restorelink = Linker
::linkKnown(
297 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
298 $this->msg( 'restorelink' )->numParams( $count )->escaped()
300 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
301 ->rawParams( $restorelink )->parseAsBlock();
302 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
308 * Stashes the upload and shows the main upload form.
310 * Note: only errors that can be handled by changing the name or
311 * description should be redirected here. It should be assumed that the
312 * file itself is sane and has passed UploadBase::verifyFile. This
313 * essentially means that UploadBase::VERIFICATION_ERROR and
314 * UploadBase::EMPTY_FILE should not be passed here.
316 * @param string $message HTML message to be passed to mainUploadForm
318 protected function showRecoverableUploadError( $message ) {
319 $sessionKey = $this->mUpload
->stashSession();
320 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
321 '<div class="error">' . $message . "</div>\n";
323 $form = $this->getUploadForm( $message, $sessionKey );
324 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
325 $this->showUploadForm( $form );
329 * Stashes the upload, shows the main form, but adds a "continue anyway button".
330 * Also checks whether there are actually warnings to display.
332 * @param array $warnings
333 * @return bool True if warnings were displayed, false if there are no
334 * warnings and it should continue processing
336 protected function showUploadWarning( $warnings ) {
337 # If there are no warnings, or warnings we can ignore, return early.
338 # mDestWarningAck is set when some javascript has shown the warning
339 # to the user. mForReUpload is set when the user clicks the "upload a
341 if ( !$warnings ||
( count( $warnings ) == 1
342 && isset( $warnings['exists'] )
343 && ( $this->mDestWarningAck ||
$this->mForReUpload
) )
348 $sessionKey = $this->mUpload
->stashSession();
350 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
351 . '<ul class="warning">';
352 foreach ( $warnings as $warning => $args ) {
353 if ( $warning == 'badfilename' ) {
354 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
356 if ( $warning == 'exists' ) {
357 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
358 } elseif ( $warning == 'duplicate' ) {
359 $msg = $this->getDupeWarning( $args );
360 } elseif ( $warning == 'duplicate-archive' ) {
361 if ( $args === '' ) {
362 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
365 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
366 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
370 if ( $args === true ) {
372 } elseif ( !is_array( $args ) ) {
373 $args = array( $args );
375 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
377 $warningHtml .= $msg;
379 $warningHtml .= "</ul>\n";
380 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
382 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
383 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
384 $form->addButton( 'wpUploadIgnoreWarning', $this->msg( 'ignorewarning' )->text() );
385 $form->addButton( 'wpCancelUpload', $this->msg( 'reuploaddesc' )->text() );
387 $this->showUploadForm( $form );
389 # Indicate that we showed a form
394 * Show the upload form with error message, but do not stash the file.
396 * @param string $message HTML string
398 protected function showUploadError( $message ) {
399 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
400 '<div class="error">' . $message . "</div>\n";
401 $this->showUploadForm( $this->getUploadForm( $message ) );
406 * Checks are made in SpecialUpload::execute()
408 protected function processUpload() {
409 // Fetch the file if required
410 $status = $this->mUpload
->fetchFile();
411 if ( !$status->isOK() ) {
412 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
417 if ( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
418 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
419 // This code path is deprecated. If you want to break upload processing
420 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
421 // and UploadBase::verifyFile.
422 // If you use this hook to break uploading, the user will be returned
423 // an empty form with no error message whatsoever.
427 // Upload verification
428 $details = $this->mUpload
->verifyUpload();
429 if ( $details['status'] != UploadBase
::OK
) {
430 $this->processVerificationError( $details );
435 // Verify permissions for this title
436 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
437 if ( $permErrors !== true ) {
438 $code = array_shift( $permErrors[0] );
439 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
444 $this->mLocalFile
= $this->mUpload
->getLocalFile();
446 // Check warnings if necessary
447 if ( !$this->mIgnoreWarning
) {
448 $warnings = $this->mUpload
->checkWarnings();
449 if ( $this->showUploadWarning( $warnings ) ) {
454 // Get the page text if this is not a reupload
455 if ( !$this->mForReUpload
) {
456 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
457 $this->mCopyrightStatus
, $this->mCopyrightSource
);
462 $status = $this->mUpload
->performUpload(
469 if ( !$status->isGood() ) {
470 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
475 // Success, redirect to description page
476 $this->mUploadSuccessful
= true;
477 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
478 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
482 * Get the initial image page text based on a comment and optional file status information
483 * @param string $comment
484 * @param string $license
485 * @param string $copyStatus
486 * @param string $source
488 * @todo Use Config obj instead of globals
490 public static function getInitialPageText( $comment = '', $license = '',
491 $copyStatus = '', $source = ''
493 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
496 /* These messages are transcluded into the actual text of the description page.
497 * Thus, forcing them as content messages makes the upload to produce an int: template
498 * instead of hardcoding it there in the uploader language.
500 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
501 if ( in_array( $msgName, (array)$wgForceUIMsgAsContentMsg ) ) {
502 $msg[$msgName] = "{{int:$msgName}}";
504 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
508 if ( $wgUseCopyrightUpload ) {
510 if ( $license != '' ) {
511 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
513 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
514 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
516 '== ' . $msg['filesource'] . " ==\n" . $source;
518 if ( $license != '' ) {
519 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
520 $pageText = $filedesc .
521 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
523 $pageText = $comment;
531 * See if we should check the 'watch this page' checkbox on the form
532 * based on the user's preferences and whether we're being asked
533 * to create a new file or update an existing one.
535 * In the case where 'watch edits' is off but 'watch creations' is on,
536 * we'll leave the box unchecked.
538 * Note that the page target can be changed *on the form*, so our check
539 * state can get out of sync.
540 * @return bool|string
542 protected function getWatchCheck() {
543 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
548 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
549 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
550 // Already watched, don't change that
554 $local = wfLocalFile( $this->mDesiredDestName
);
555 if ( $local && $local->exists() ) {
556 // We're uploading a new version of an existing file.
557 // No creation, so don't watch it if we're not already.
560 // New page should get watched if that's our option.
561 return $this->getUser()->getOption( 'watchcreations' );
566 * Provides output to the user for a result of UploadBase::verifyUpload
568 * @param array $details Result of UploadBase::verifyUpload
569 * @throws MWException
571 protected function processVerificationError( $details ) {
572 switch ( $details['status'] ) {
574 /** Statuses that only require name changing **/
575 case UploadBase
::MIN_LENGTH_PARTNAME
:
576 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
578 case UploadBase
::ILLEGAL_FILENAME
:
579 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
580 $details['filtered'] )->parse() );
582 case UploadBase
::FILENAME_TOO_LONG
:
583 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
585 case UploadBase
::FILETYPE_MISSING
:
586 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
588 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
589 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
592 /** Statuses that require reuploading **/
593 case UploadBase
::EMPTY_FILE
:
594 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
596 case UploadBase
::FILE_TOO_LARGE
:
597 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
599 case UploadBase
::FILETYPE_BADTYPE
:
600 $msg = $this->msg( 'filetype-banned-type' );
601 if ( isset( $details['blacklistedExt'] ) ) {
602 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
604 $msg->params( $details['finalExt'] );
606 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
607 $msg->params( $this->getLanguage()->commaList( $extensions ),
608 count( $extensions ) );
610 // Add PLURAL support for the first parameter. This results
611 // in a bit unlogical parameter sequence, but does not break
613 if ( isset( $details['blacklistedExt'] ) ) {
614 $msg->params( count( $details['blacklistedExt'] ) );
619 $this->showUploadError( $msg->parse() );
621 case UploadBase
::VERIFICATION_ERROR
:
622 unset( $details['status'] );
623 $code = array_shift( $details['details'] );
624 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
626 case UploadBase
::HOOK_ABORTED
:
627 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
628 $args = $details['error'];
629 $error = array_shift( $args );
631 $error = $details['error'];
635 $this->showUploadError( $this->msg( $error, $args )->parse() );
638 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
643 * Remove a temporarily kept file stashed by saveTempUploadedFile().
645 * @return bool Success
647 protected function unsaveUploadedFile() {
648 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
651 $success = $this->mUpload
->unsaveUploadedFile();
653 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
661 /*** Functions for formatting warnings ***/
664 * Formats a result of UploadBase::getExistsWarning as HTML
665 * This check is static and can be done pre-upload via AJAX
667 * @param array $exists The result of UploadBase::getExistsWarning
668 * @return string Empty string if there is no warning or an HTML fragment
670 public static function getExistsWarning( $exists ) {
675 $file = $exists['file'];
676 $filename = $file->getTitle()->getPrefixedText();
679 if ( $exists['warning'] == 'exists' ) {
681 $warning = wfMessage( 'fileexists', $filename )->parse();
682 } elseif ( $exists['warning'] == 'page-exists' ) {
683 // Page exists but file does not
684 $warning = wfMessage( 'filepageexists', $filename )->parse();
685 } elseif ( $exists['warning'] == 'exists-normalized' ) {
686 $warning = wfMessage( 'fileexists-extension', $filename,
687 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
688 } elseif ( $exists['warning'] == 'thumb' ) {
689 // Swapped argument order compared with other messages for backwards compatibility
690 $warning = wfMessage( 'fileexists-thumbnail-yes',
691 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
692 } elseif ( $exists['warning'] == 'thumb-name' ) {
693 // Image w/o '180px-' does not exists, but we do not like these filenames
694 $name = $file->getName();
695 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
696 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
697 } elseif ( $exists['warning'] == 'bad-prefix' ) {
698 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
699 } elseif ( $exists['warning'] == 'was-deleted' ) {
700 # If the file existed before and was deleted, warn the user of this
701 $ltitle = SpecialPage
::getTitleFor( 'Log' );
702 $llink = Linker
::linkKnown(
704 wfMessage( 'deletionlog' )->escaped(),
711 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
718 * Construct a warning and a gallery from an array of duplicate files.
719 * @param array $dupes
722 public function getDupeWarning( $dupes ) {
727 $gallery = ImageGalleryBase
::factory( false, $this->getContext() );
728 $gallery->setShowBytes( false );
729 foreach ( $dupes as $file ) {
730 $gallery->add( $file->getTitle() );
734 wfMessage( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
735 $gallery->toHtml() . "</li>\n";
738 protected function getGroupName() {
743 * Should we rotate images in the preview on Special:Upload.
745 * This controls js: mw.config.get( 'wgFileCanRotate' )
747 * @todo What about non-BitmapHandler handled files?
749 static public function rotationEnabled() {
750 $bitmapHandler = new BitmapHandler();
751 return $bitmapHandler->autoRotateEnabled();
756 * Sub class of HTMLForm that provides the form section of SpecialUpload
758 class UploadForm
extends HTMLForm
{
760 protected $mForReUpload;
761 protected $mSessionKey;
762 protected $mHideIgnoreWarning;
763 protected $mDestWarningAck;
764 protected $mDestFile;
768 protected $mTextAfterSummary;
770 protected $mSourceIds;
772 protected $mMaxFileSize = array();
774 protected $mMaxUploadSize = array();
776 public function __construct( array $options = array(), IContextSource
$context = null ) {
777 $this->mWatch
= !empty( $options['watch'] );
778 $this->mForReUpload
= !empty( $options['forreupload'] );
779 $this->mSessionKey
= isset( $options['sessionkey'] ) ?
$options['sessionkey'] : '';
780 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
781 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
782 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
784 $this->mComment
= isset( $options['description'] ) ?
785 $options['description'] : '';
787 $this->mTextTop
= isset( $options['texttop'] )
788 ?
$options['texttop'] : '';
790 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
791 ?
$options['textaftersummary'] : '';
793 $sourceDescriptor = $this->getSourceSection();
794 $descriptor = $sourceDescriptor
795 +
$this->getDescriptionSection()
796 +
$this->getOptionsSection();
798 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
799 parent
::__construct( $descriptor, $context, 'upload' );
801 # Add a link to edit MediaWik:Licenses
802 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
803 $licensesLink = Linker
::link(
804 Title
::makeTitle( NS_MEDIAWIKI
, 'Licenses' ),
805 $this->msg( 'licenses-edit' )->escaped(),
807 array( 'action' => 'edit' )
809 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
810 $this->addFooterText( $editLicenses, 'description' );
813 # Set some form properties
814 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
815 $this->setSubmitName( 'wpUpload' );
816 # Used message keys: 'accesskey-upload', 'tooltip-upload'
817 $this->setSubmitTooltip( 'upload' );
818 $this->setId( 'mw-upload-form' );
820 # Build a list of IDs for javascript insertion
821 $this->mSourceIds
= array();
822 foreach ( $sourceDescriptor as $field ) {
823 if ( !empty( $field['id'] ) ) {
824 $this->mSourceIds
[] = $field['id'];
830 * Get the descriptor of the fieldset that contains the file source
831 * selection. The section is 'source'
833 * @return array Descriptor array
835 protected function getSourceSection() {
836 if ( $this->mSessionKey
) {
838 'SessionKey' => array(
840 'default' => $this->mSessionKey
,
842 'SourceType' => array(
844 'default' => 'Stash',
849 $canUploadByUrl = UploadFromUrl
::isEnabled()
850 && ( UploadFromUrl
::isAllowed( $this->getUser() ) === true )
851 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
852 $radio = $canUploadByUrl;
853 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
855 $descriptor = array();
856 if ( $this->mTextTop
) {
857 $descriptor['UploadFormTextTop'] = array(
859 'section' => 'source',
860 'default' => $this->mTextTop
,
865 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
866 # Limit to upload_max_filesize unless we are running under HipHop and
867 # that setting doesn't exist
869 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
870 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
871 wfShorthandToInteger( ini_get( 'post_max_size' ) )
875 $descriptor['UploadFile'] = array(
876 'class' => 'UploadSourceField',
877 'section' => 'source',
879 'id' => 'wpUploadFile',
880 'radio-id' => 'wpSourceTypeFile',
881 'label-message' => 'sourcefilename',
882 'upload-type' => 'File',
884 'help' => $this->msg( 'upload-maxfilesize',
885 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
887 $this->msg( 'word-separator' )->escaped() .
888 $this->msg( 'upload_source_file' )->escaped(),
889 'checked' => $selectedSourceType == 'file',
892 if ( $canUploadByUrl ) {
893 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
894 $descriptor['UploadFileURL'] = array(
895 'class' => 'UploadSourceField',
896 'section' => 'source',
897 'id' => 'wpUploadFileURL',
898 'radio-id' => 'wpSourceTypeurl',
899 'label-message' => 'sourceurl',
900 'upload-type' => 'url',
902 'help' => $this->msg( 'upload-maxfilesize',
903 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
905 $this->msg( 'word-separator' )->escaped() .
906 $this->msg( 'upload_source_url' )->escaped(),
907 'checked' => $selectedSourceType == 'url',
910 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
912 $descriptor['Extensions'] = array(
914 'section' => 'source',
915 'default' => $this->getExtensionsMessage(),
923 * Get the messages indicating which extensions are preferred and prohibitted.
925 * @return string HTML string containing the message
927 protected function getExtensionsMessage() {
928 # Print a list of allowed file extensions, if so configured. We ignore
929 # MIME type here, it's incomprehensible to most people and too long.
930 $config = $this->getConfig();
932 if ( $config->get( 'CheckFileExtensions' ) ) {
933 if ( $config->get( 'StrictFileExtensions' ) ) {
934 # Everything not permitted is banned
936 '<div id="mw-upload-permitted">' .
939 $this->getContext()->getLanguage()->commaList(
940 array_unique( $config->get( 'FileExtensions' ) )
945 # We have to list both preferred and prohibited
947 '<div id="mw-upload-preferred">' .
950 $this->getContext()->getLanguage()->commaList(
951 array_unique( $config->get( 'FileExtensions' ) )
955 '<div id="mw-upload-prohibited">' .
958 $this->getContext()->getLanguage()->commaList(
959 array_unique( $config->get( 'FileBlacklist' ) )
965 # Everything is permitted.
966 $extensionsList = '';
969 return $extensionsList;
973 * Get the descriptor of the fieldset that contains the file description
974 * input. The section is 'description'
976 * @return array Descriptor array
978 protected function getDescriptionSection() {
979 $config = $this->getConfig();
980 if ( $this->mSessionKey
) {
981 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash();
983 $file = $stash->getFile( $this->mSessionKey
);
984 } catch ( MWException
$e ) {
990 $mto = $file->transform( array( 'width' => 120 ) );
991 $this->addHeaderText(
992 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
993 Html
::element( 'img', array(
994 'src' => $mto->getUrl(),
995 'class' => 'thumbimage',
996 ) ) . '</div>', 'description' );
1000 $descriptor = array(
1001 'DestFile' => array(
1003 'section' => 'description',
1004 'id' => 'wpDestFile',
1005 'label-message' => 'destfilename',
1007 'default' => $this->mDestFile
,
1008 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1009 'nodata' => strval( $this->mDestFile
) !== '',
1011 'UploadDescription' => array(
1012 'type' => 'textarea',
1013 'section' => 'description',
1014 'id' => 'wpUploadDescription',
1015 'label-message' => $this->mForReUpload
1016 ?
'filereuploadsummary'
1017 : 'fileuploadsummary',
1018 'default' => $this->mComment
,
1019 'cols' => $this->getUser()->getIntOption( 'cols' ),
1023 if ( $this->mTextAfterSummary
) {
1024 $descriptor['UploadFormTextAfterSummary'] = array(
1026 'section' => 'description',
1027 'default' => $this->mTextAfterSummary
,
1032 $descriptor +
= array(
1033 'EditTools' => array(
1034 'type' => 'edittools',
1035 'section' => 'description',
1036 'message' => 'edittools-upload',
1040 if ( $this->mForReUpload
) {
1041 $descriptor['DestFile']['readonly'] = true;
1043 $descriptor['License'] = array(
1045 'class' => 'Licenses',
1046 'section' => 'description',
1047 'id' => 'wpLicense',
1048 'label-message' => 'license',
1052 if ( $config->get( 'UseCopyrightUpload' ) ) {
1053 $descriptor['UploadCopyStatus'] = array(
1055 'section' => 'description',
1056 'id' => 'wpUploadCopyStatus',
1057 'label-message' => 'filestatus',
1059 $descriptor['UploadSource'] = array(
1061 'section' => 'description',
1062 'id' => 'wpUploadSource',
1063 'label-message' => 'filesource',
1071 * Get the descriptor of the fieldset that contains the upload options,
1072 * such as "watch this file". The section is 'options'
1074 * @return array Descriptor array
1076 protected function getOptionsSection() {
1077 $user = $this->getUser();
1078 if ( $user->isLoggedIn() ) {
1079 $descriptor = array(
1080 'Watchthis' => array(
1082 'id' => 'wpWatchthis',
1083 'label-message' => 'watchthisupload',
1084 'section' => 'options',
1085 'default' => $this->mWatch
,
1089 if ( !$this->mHideIgnoreWarning
) {
1090 $descriptor['IgnoreWarning'] = array(
1092 'id' => 'wpIgnoreWarning',
1093 'label-message' => 'ignorewarnings',
1094 'section' => 'options',
1098 $descriptor['DestFileWarningAck'] = array(
1100 'id' => 'wpDestFileWarningAck',
1101 'default' => $this->mDestWarningAck ?
'1' : '',
1104 if ( $this->mForReUpload
) {
1105 $descriptor['ForReUpload'] = array(
1107 'id' => 'wpForReUpload',
1116 * Add the upload JS and show the form.
1118 public function show() {
1119 $this->addUploadJS();
1124 * Add upload JS to the OutputPage
1126 protected function addUploadJS() {
1127 $config = $this->getConfig();
1129 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1130 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1131 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1132 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1134 $scriptVars = array(
1135 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1136 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1137 'wgUploadAutoFill' => !$this->mForReUpload
&&
1138 // If we received mDestFile from the request, don't autofill
1139 // the wpDestFile textbox
1140 $this->mDestFile
=== '',
1141 'wgUploadSourceIds' => $this->mSourceIds
,
1142 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1143 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1144 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1145 'wgFileCanRotate' => SpecialUpload
::rotationEnabled(),
1148 $out = $this->getOutput();
1149 $out->addJsConfigVars( $scriptVars );
1151 $out->addModules( array(
1152 'mediawiki.action.edit', // For <charinsert> support
1153 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1158 * Empty function; submission is handled elsewhere.
1160 * @return bool False
1162 function trySubmit() {
1168 * A form field that contains a radio box in the label
1170 class UploadSourceField
extends HTMLTextField
{
1173 * @param array $cellAttributes
1176 function getLabelHtml( $cellAttributes = array() ) {
1177 $id = $this->mParams
['id'];
1178 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1180 if ( !empty( $this->mParams
['radio'] ) ) {
1181 if ( isset( $this->mParams
['radio-id'] ) ) {
1182 $radioId = $this->mParams
['radio-id'];
1184 // Old way. For the benefit of extensions that do not define
1185 // the 'radio-id' key.
1186 $radioId = 'wpSourceType' . $this->mParams
['upload-type'];
1190 'name' => 'wpSourceType',
1193 'value' => $this->mParams
['upload-type'],
1196 if ( !empty( $this->mParams
['checked'] ) ) {
1197 $attribs['checked'] = 'checked';
1200 $label .= Html
::element( 'input', $attribs );
1203 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1209 function getSize() {
1210 return isset( $this->mParams
['size'] )
1211 ?
$this->mParams
['size']