3 * Implements Special:Upload
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
21 * @ingroup SpecialPage
26 * Form for handling uploads and special page.
28 * @ingroup SpecialPage
31 class SpecialUpload
extends SpecialPage
{
33 * Constructor : initialise object
34 * Get data POSTed through the form and assign them to the object
35 * @param WebRequest $request Data posted.
37 public function __construct( $request = null ) {
38 parent
::__construct( 'Upload', 'upload' );
41 /** Misc variables **/
43 /** @var WebRequest|FauxRequest The request this form is supposed to handle */
47 /** @var UploadBase */
52 public $mUploadClicked;
54 /** User input variables from the "description" section **/
56 /** @var string The requested target file name */
57 public $mDesiredDestName;
61 /** User input variables from the root section **/
63 public $mIgnoreWarning;
65 public $mCopyrightStatus;
66 public $mCopyrightSource;
68 /** Hidden variables **/
70 public $mDestWarningAck;
72 /** @var bool The user followed an "overwrite this file" link */
75 /** @var bool The user clicked "Cancel and return to upload form" button */
76 public $mCancelUpload;
79 /** @var bool Subclasses can use this to determine whether a file was uploaded */
80 public $mUploadSuccessful = false;
82 /** Text injection points for hooks not using HTMLForm **/
83 public $uploadFormTextTop;
84 public $uploadFormTextAfterSummary;
87 * Initialize instance variables from request and create an Upload handler
89 protected function loadRequest() {
90 $this->mRequest
= $request = $this->getRequest();
91 $this->mSourceType
= $request->getVal( 'wpSourceType', 'file' );
92 $this->mUpload
= UploadBase
::createFromRequest( $request );
93 $this->mUploadClicked
= $request->wasPosted()
94 && ( $request->getCheck( 'wpUpload' )
95 ||
$request->getCheck( 'wpUploadIgnoreWarning' ) );
97 // Guess the desired name from the filename if not provided
98 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
99 if ( !$this->mDesiredDestName
&& $request->getFileName( 'wpUploadFile' ) !== null ) {
100 $this->mDesiredDestName
= $request->getFileName( 'wpUploadFile' );
102 $this->mLicense
= $request->getText( 'wpLicense' );
104 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
105 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' )
106 ||
$request->getCheck( 'wpUploadIgnoreWarning' );
107 $this->mWatchthis
= $request->getBool( 'wpWatchthis' ) && $this->getUser()->isLoggedIn();
108 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
109 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
111 $this->mForReUpload
= $request->getBool( 'wpForReUpload' ); // updating a file
113 $commentDefault = '';
114 $commentMsg = wfMessage( 'upload-default-description' )->inContentLanguage();
115 if ( !$this->mForReUpload
&& !$commentMsg->isDisabled() ) {
116 $commentDefault = $commentMsg->plain();
118 $this->mComment
= $request->getText( 'wpUploadDescription', $commentDefault );
120 $this->mCancelUpload
= $request->getCheck( 'wpCancelUpload' )
121 ||
$request->getCheck( 'wpReUpload' ); // b/w compat
123 // If it was posted check for the token (no remote POST'ing with user credentials)
124 $token = $request->getVal( 'wpEditToken' );
125 $this->mTokenOk
= $this->getUser()->matchEditToken( $token );
127 $this->uploadFormTextTop
= '';
128 $this->uploadFormTextAfterSummary
= '';
132 * This page can be shown if uploading is enabled.
133 * Handle permission checking elsewhere in order to be able to show
134 * custom error messages.
139 public function userCanExecute( User
$user ) {
140 return UploadBase
::isEnabled() && parent
::userCanExecute( $user );
144 * Special page entry point
146 * @throws ErrorPageError
149 * @throws MWException
150 * @throws PermissionsError
151 * @throws ReadOnlyError
152 * @throws UserBlockedError
154 public function execute( $par ) {
155 $this->useTransactionalTimeLimit();
158 $this->outputHeader();
160 # Check uploading enabled
161 if ( !UploadBase
::isEnabled() ) {
162 throw new ErrorPageError( 'uploaddisabled', 'uploaddisabledtext' );
165 $this->addHelpLink( 'Help:Managing files' );
168 $user = $this->getUser();
169 $permissionRequired = UploadBase
::isAllowed( $user );
170 if ( $permissionRequired !== true ) {
171 throw new PermissionsError( $permissionRequired );
175 if ( $user->isBlocked() ) {
176 throw new UserBlockedError( $user->getBlock() );
179 # Check whether we actually want to allow changing stuff
180 $this->checkReadOnly();
182 $this->loadRequest();
184 # Unsave the temporary file in case this was a cancelled upload
185 if ( $this->mCancelUpload
) {
186 if ( !$this->unsaveUploadedFile() ) {
187 # Something went wrong, so unsaveUploadedFile showed a warning
192 # Process upload or show a form
194 $this->mTokenOk
&& !$this->mCancelUpload
&&
195 ( $this->mUpload
&& $this->mUploadClicked
)
197 $this->processUpload();
199 # Backwards compatibility hook
200 if ( !Hooks
::run( 'UploadForm:initial', array( &$this ) ) ) {
201 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
205 $this->showUploadForm( $this->getUploadForm() );
209 if ( $this->mUpload
) {
210 $this->mUpload
->cleanupTempFile();
215 * Show the main upload form
217 * @param HTMLForm|string $form An HTMLForm instance or HTML string to show
219 protected function showUploadForm( $form ) {
220 # Add links if file was previously deleted
221 if ( $this->mDesiredDestName
) {
222 $this->showViewDeletedLinks();
225 if ( $form instanceof HTMLForm
) {
228 $this->getOutput()->addHTML( $form );
233 * Get an UploadForm instance with title and text properly set.
235 * @param string $message HTML string to add to the form
236 * @param string $sessionKey Session key in case this is a stashed upload
237 * @param bool $hideIgnoreWarning Whether to hide "ignore warning" check box
240 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
242 $context = new DerivativeContext( $this->getContext() );
243 $context->setTitle( $this->getPageTitle() ); // Remove subpage
244 $form = new UploadForm( array(
245 'watch' => $this->getWatchCheck(),
246 'forreupload' => $this->mForReUpload
,
247 'sessionkey' => $sessionKey,
248 'hideignorewarning' => $hideIgnoreWarning,
249 'destwarningack' => (bool)$this->mDestWarningAck
,
251 'description' => $this->mComment
,
252 'texttop' => $this->uploadFormTextTop
,
253 'textaftersummary' => $this->uploadFormTextAfterSummary
,
254 'destfile' => $this->mDesiredDestName
,
257 # Check the token, but only if necessary
259 !$this->mTokenOk
&& !$this->mCancelUpload
&&
260 ( $this->mUpload
&& $this->mUploadClicked
)
262 $form->addPreText( $this->msg( 'session_fail_preview' )->parse() );
265 # Give a notice if the user is uploading a file that has been deleted or moved
266 # Note that this is independent from the message 'filewasdeleted'
267 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
268 $delNotice = ''; // empty by default
269 if ( $desiredTitleObj instanceof Title
&& !$desiredTitleObj->exists() ) {
270 LogEventsList
::showLogExtract( $delNotice, array( 'delete', 'move' ),
272 '', array( 'lim' => 10,
273 'conds' => array( "log_action != 'revision'" ),
274 'showIfEmpty' => false,
275 'msgKey' => array( 'upload-recreate-warning' ) )
278 $form->addPreText( $delNotice );
281 $form->addPreText( '<div id="uploadtext">' .
282 $this->msg( 'uploadtext', array( $this->mDesiredDestName
) )->parseAsBlock() .
284 # Add upload error message
285 $form->addPreText( $message );
288 $uploadFooter = $this->msg( 'uploadfooter' );
289 if ( !$uploadFooter->isDisabled() ) {
290 $form->addPostText( '<div id="mw-upload-footer-message">'
291 . $uploadFooter->parseAsBlock() . "</div>\n" );
298 * Shows the "view X deleted revivions link""
300 protected function showViewDeletedLinks() {
301 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
302 $user = $this->getUser();
303 // Show a subtitle link to deleted revisions (to sysops et al only)
304 if ( $title instanceof Title
) {
305 $count = $title->isDeleted();
306 if ( $count > 0 && $user->isAllowed( 'deletedhistory' ) ) {
307 $restorelink = Linker
::linkKnown(
308 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
309 $this->msg( 'restorelink' )->numParams( $count )->escaped()
311 $link = $this->msg( $user->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted' )
312 ->rawParams( $restorelink )->parseAsBlock();
313 $this->getOutput()->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
319 * Stashes the upload and shows the main upload form.
321 * Note: only errors that can be handled by changing the name or
322 * description should be redirected here. It should be assumed that the
323 * file itself is sane and has passed UploadBase::verifyFile. This
324 * essentially means that UploadBase::VERIFICATION_ERROR and
325 * UploadBase::EMPTY_FILE should not be passed here.
327 * @param string $message HTML message to be passed to mainUploadForm
329 protected function showRecoverableUploadError( $message ) {
330 $sessionKey = $this->mUpload
->stashSession();
331 $message = '<h2>' . $this->msg( 'uploaderror' )->escaped() . "</h2>\n" .
332 '<div class="error">' . $message . "</div>\n";
334 $form = $this->getUploadForm( $message, $sessionKey );
335 $form->setSubmitText( $this->msg( 'upload-tryagain' )->escaped() );
336 $this->showUploadForm( $form );
340 * Stashes the upload, shows the main form, but adds a "continue anyway button".
341 * Also checks whether there are actually warnings to display.
343 * @param array $warnings
344 * @return bool True if warnings were displayed, false if there are no
345 * warnings and it should continue processing
347 protected function showUploadWarning( $warnings ) {
348 # If there are no warnings, or warnings we can ignore, return early.
349 # mDestWarningAck is set when some javascript has shown the warning
350 # to the user. mForReUpload is set when the user clicks the "upload a
352 if ( !$warnings ||
( count( $warnings ) == 1
353 && isset( $warnings['exists'] )
354 && ( $this->mDestWarningAck ||
$this->mForReUpload
) )
359 $sessionKey = $this->mUpload
->stashSession();
361 $warningHtml = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n"
362 . '<div class="warningbox"><ul>';
363 foreach ( $warnings as $warning => $args ) {
364 if ( $warning == 'badfilename' ) {
365 $this->mDesiredDestName
= Title
::makeTitle( NS_FILE
, $args )->getText();
367 if ( $warning == 'exists' ) {
368 $msg = "\t<li>" . self
::getExistsWarning( $args ) . "</li>\n";
369 } elseif ( $warning == 'was-deleted' ) {
370 # If the file existed before and was deleted, warn the user of this
371 $ltitle = SpecialPage
::getTitleFor( 'Log' );
372 $llink = Linker
::linkKnown(
374 wfMessage( 'deletionlog' )->escaped(),
378 'page' => Title
::makeTitle( NS_FILE
, $args )->getPrefixedText(),
381 $msg = "\t<li>" . wfMessage( 'filewasdeleted' )->rawParams( $llink )->parse() . "</li>\n";
382 } elseif ( $warning == 'duplicate' ) {
383 $msg = $this->getDupeWarning( $args );
384 } elseif ( $warning == 'duplicate-archive' ) {
385 if ( $args === '' ) {
386 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate-notitle' )->parse()
389 $msg = "\t<li>" . $this->msg( 'file-deleted-duplicate',
390 Title
::makeTitle( NS_FILE
, $args )->getPrefixedText() )->parse()
394 if ( $args === true ) {
396 } elseif ( !is_array( $args ) ) {
397 $args = array( $args );
399 $msg = "\t<li>" . $this->msg( $warning, $args )->parse() . "</li>\n";
401 $warningHtml .= $msg;
403 $warningHtml .= "</ul></div>\n";
404 $warningHtml .= $this->msg( 'uploadwarning-text' )->parseAsBlock();
406 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
407 $form->setSubmitText( $this->msg( 'upload-tryagain' )->text() );
408 $form->addButton( array(
409 'name' => 'wpUploadIgnoreWarning',
410 'value' => $this->msg( 'ignorewarning' )->text()
412 $form->addButton( array(
413 'name' => 'wpCancelUpload',
414 'value' => $this->msg( 'reuploaddesc' )->text()
417 $this->showUploadForm( $form );
419 # Indicate that we showed a form
424 * Show the upload form with error message, but do not stash the file.
426 * @param string $message HTML string
428 protected function showUploadError( $message ) {
429 $message = '<h2>' . $this->msg( 'uploadwarning' )->escaped() . "</h2>\n" .
430 '<div class="error">' . $message . "</div>\n";
431 $this->showUploadForm( $this->getUploadForm( $message ) );
436 * Checks are made in SpecialUpload::execute()
438 protected function processUpload() {
439 // Fetch the file if required
440 $status = $this->mUpload
->fetchFile();
441 if ( !$status->isOK() ) {
442 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
447 if ( !Hooks
::run( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
448 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
449 // This code path is deprecated. If you want to break upload processing
450 // do so by hooking into the appropriate hooks in UploadBase::verifyUpload
451 // and UploadBase::verifyFile.
452 // If you use this hook to break uploading, the user will be returned
453 // an empty form with no error message whatsoever.
457 // Upload verification
458 $details = $this->mUpload
->verifyUpload();
459 if ( $details['status'] != UploadBase
::OK
) {
460 $this->processVerificationError( $details );
465 // Verify permissions for this title
466 $permErrors = $this->mUpload
->verifyTitlePermissions( $this->getUser() );
467 if ( $permErrors !== true ) {
468 $code = array_shift( $permErrors[0] );
469 $this->showRecoverableUploadError( $this->msg( $code, $permErrors[0] )->parse() );
474 $this->mLocalFile
= $this->mUpload
->getLocalFile();
476 // Check warnings if necessary
477 if ( !$this->mIgnoreWarning
) {
478 $warnings = $this->mUpload
->checkWarnings();
479 if ( $this->showUploadWarning( $warnings ) ) {
484 // This is as late as we can throttle, after expected issues have been handled
485 if ( UploadBase
::isThrottled( $this->getUser() ) ) {
486 $this->showRecoverableUploadError(
487 $this->msg( 'actionthrottledtext' )->escaped()
492 // Get the page text if this is not a reupload
493 if ( !$this->mForReUpload
) {
494 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
495 $this->mCopyrightStatus
, $this->mCopyrightSource
, $this->getConfig() );
500 $status = $this->mUpload
->performUpload(
507 if ( !$status->isGood() ) {
508 $this->showUploadError( $this->getOutput()->parse( $status->getWikiText() ) );
513 // Success, redirect to description page
514 $this->mUploadSuccessful
= true;
515 Hooks
::run( 'SpecialUploadComplete', array( &$this ) );
516 $this->getOutput()->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
520 * Get the initial image page text based on a comment and optional file status information
521 * @param string $comment
522 * @param string $license
523 * @param string $copyStatus
524 * @param string $source
525 * @param Config $config Configuration object to load data from
528 public static function getInitialPageText( $comment = '', $license = '',
529 $copyStatus = '', $source = '', Config
$config = null
531 if ( $config === null ) {
532 wfDebug( __METHOD__
. ' called without a Config instance passed to it' );
533 $config = ConfigFactory
::getDefaultInstance()->makeConfig( 'main' );
537 $forceUIMsgAsContentMsg = (array)$config->get( 'ForceUIMsgAsContentMsg' );
538 /* These messages are transcluded into the actual text of the description page.
539 * Thus, forcing them as content messages makes the upload to produce an int: template
540 * instead of hardcoding it there in the uploader language.
542 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
543 if ( in_array( $msgName, $forceUIMsgAsContentMsg ) ) {
544 $msg[$msgName] = "{{int:$msgName}}";
546 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
550 if ( $config->get( 'UseCopyrightUpload' ) ) {
552 if ( $license != '' ) {
553 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
555 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
556 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
558 '== ' . $msg['filesource'] . " ==\n" . $source;
560 if ( $license != '' ) {
561 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
562 $pageText = $filedesc .
563 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
565 $pageText = $comment;
573 * See if we should check the 'watch this page' checkbox on the form
574 * based on the user's preferences and whether we're being asked
575 * to create a new file or update an existing one.
577 * In the case where 'watch edits' is off but 'watch creations' is on,
578 * we'll leave the box unchecked.
580 * Note that the page target can be changed *on the form*, so our check
581 * state can get out of sync.
582 * @return bool|string
584 protected function getWatchCheck() {
585 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
590 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
591 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
592 // Already watched, don't change that
596 $local = wfLocalFile( $this->mDesiredDestName
);
597 if ( $local && $local->exists() ) {
598 // We're uploading a new version of an existing file.
599 // No creation, so don't watch it if we're not already.
602 // New page should get watched if that's our option.
603 return $this->getUser()->getOption( 'watchcreations' );
608 * Provides output to the user for a result of UploadBase::verifyUpload
610 * @param array $details Result of UploadBase::verifyUpload
611 * @throws MWException
613 protected function processVerificationError( $details ) {
614 switch ( $details['status'] ) {
616 /** Statuses that only require name changing **/
617 case UploadBase
::MIN_LENGTH_PARTNAME
:
618 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
620 case UploadBase
::ILLEGAL_FILENAME
:
621 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
622 $details['filtered'] )->parse() );
624 case UploadBase
::FILENAME_TOO_LONG
:
625 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
627 case UploadBase
::FILETYPE_MISSING
:
628 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
630 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
631 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
634 /** Statuses that require reuploading **/
635 case UploadBase
::EMPTY_FILE
:
636 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
638 case UploadBase
::FILE_TOO_LARGE
:
639 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
641 case UploadBase
::FILETYPE_BADTYPE
:
642 $msg = $this->msg( 'filetype-banned-type' );
643 if ( isset( $details['blacklistedExt'] ) ) {
644 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
646 $msg->params( $details['finalExt'] );
648 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
649 $msg->params( $this->getLanguage()->commaList( $extensions ),
650 count( $extensions ) );
652 // Add PLURAL support for the first parameter. This results
653 // in a bit unlogical parameter sequence, but does not break
655 if ( isset( $details['blacklistedExt'] ) ) {
656 $msg->params( count( $details['blacklistedExt'] ) );
661 $this->showUploadError( $msg->parse() );
663 case UploadBase
::VERIFICATION_ERROR
:
664 unset( $details['status'] );
665 $code = array_shift( $details['details'] );
666 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
668 case UploadBase
::HOOK_ABORTED
:
669 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
670 $args = $details['error'];
671 $error = array_shift( $args );
673 $error = $details['error'];
677 $this->showUploadError( $this->msg( $error, $args )->parse() );
680 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
685 * Remove a temporarily kept file stashed by saveTempUploadedFile().
687 * @return bool Success
689 protected function unsaveUploadedFile() {
690 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
693 $success = $this->mUpload
->unsaveUploadedFile();
695 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
703 /*** Functions for formatting warnings ***/
706 * Formats a result of UploadBase::getExistsWarning as HTML
707 * This check is static and can be done pre-upload via AJAX
709 * @param array $exists The result of UploadBase::getExistsWarning
710 * @return string Empty string if there is no warning or an HTML fragment
712 public static function getExistsWarning( $exists ) {
717 $file = $exists['file'];
718 $filename = $file->getTitle()->getPrefixedText();
721 if ( $exists['warning'] == 'exists' ) {
723 $warning = wfMessage( 'fileexists', $filename )->parse();
724 } elseif ( $exists['warning'] == 'page-exists' ) {
725 // Page exists but file does not
726 $warning = wfMessage( 'filepageexists', $filename )->parse();
727 } elseif ( $exists['warning'] == 'exists-normalized' ) {
728 $warning = wfMessage( 'fileexists-extension', $filename,
729 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
730 } elseif ( $exists['warning'] == 'thumb' ) {
731 // Swapped argument order compared with other messages for backwards compatibility
732 $warning = wfMessage( 'fileexists-thumbnail-yes',
733 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
734 } elseif ( $exists['warning'] == 'thumb-name' ) {
735 // Image w/o '180px-' does not exists, but we do not like these filenames
736 $name = $file->getName();
737 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
738 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
739 } elseif ( $exists['warning'] == 'bad-prefix' ) {
740 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
747 * Construct a warning and a gallery from an array of duplicate files.
748 * @param array $dupes
751 public function getDupeWarning( $dupes ) {
756 $gallery = ImageGalleryBase
::factory( false, $this->getContext() );
757 $gallery->setShowBytes( false );
758 foreach ( $dupes as $file ) {
759 $gallery->add( $file->getTitle() );
763 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
764 $gallery->toHTML() . "</li>\n";
767 protected function getGroupName() {
772 * Should we rotate images in the preview on Special:Upload.
774 * This controls js: mw.config.get( 'wgFileCanRotate' )
776 * @todo What about non-BitmapHandler handled files?
778 public static function rotationEnabled() {
779 $bitmapHandler = new BitmapHandler();
780 return $bitmapHandler->autoRotateEnabled();
785 * Sub class of HTMLForm that provides the form section of SpecialUpload
787 class UploadForm
extends HTMLForm
{
789 protected $mForReUpload;
790 protected $mSessionKey;
791 protected $mHideIgnoreWarning;
792 protected $mDestWarningAck;
793 protected $mDestFile;
797 protected $mTextAfterSummary;
799 protected $mSourceIds;
801 protected $mMaxFileSize = array();
803 protected $mMaxUploadSize = array();
805 public function __construct( array $options = array(), IContextSource
$context = null ) {
806 if ( $context instanceof IContextSource
) {
807 $this->setContext( $context );
810 $this->mWatch
= !empty( $options['watch'] );
811 $this->mForReUpload
= !empty( $options['forreupload'] );
812 $this->mSessionKey
= isset( $options['sessionkey'] ) ?
$options['sessionkey'] : '';
813 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
814 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
815 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
817 $this->mComment
= isset( $options['description'] ) ?
818 $options['description'] : '';
820 $this->mTextTop
= isset( $options['texttop'] )
821 ?
$options['texttop'] : '';
823 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
824 ?
$options['textaftersummary'] : '';
826 $sourceDescriptor = $this->getSourceSection();
827 $descriptor = $sourceDescriptor
828 +
$this->getDescriptionSection()
829 +
$this->getOptionsSection();
831 Hooks
::run( 'UploadFormInitDescriptor', array( &$descriptor ) );
832 parent
::__construct( $descriptor, $context, 'upload' );
834 # Add a link to edit MediaWik:Licenses
835 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
836 $this->getOutput()->addModuleStyles( 'mediawiki.special' );
837 $licensesLink = Linker
::linkKnown(
838 $this->msg( 'licenses' )->inContentLanguage()->getTitle(),
839 $this->msg( 'licenses-edit' )->escaped(),
841 array( 'action' => 'edit' )
843 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
844 $this->addFooterText( $editLicenses, 'description' );
847 # Set some form properties
848 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
849 $this->setSubmitName( 'wpUpload' );
850 # Used message keys: 'accesskey-upload', 'tooltip-upload'
851 $this->setSubmitTooltip( 'upload' );
852 $this->setId( 'mw-upload-form' );
854 # Build a list of IDs for javascript insertion
855 $this->mSourceIds
= array();
856 foreach ( $sourceDescriptor as $field ) {
857 if ( !empty( $field['id'] ) ) {
858 $this->mSourceIds
[] = $field['id'];
864 * Get the descriptor of the fieldset that contains the file source
865 * selection. The section is 'source'
867 * @return array Descriptor array
869 protected function getSourceSection() {
870 if ( $this->mSessionKey
) {
872 'SessionKey' => array(
874 'default' => $this->mSessionKey
,
876 'SourceType' => array(
878 'default' => 'Stash',
883 $canUploadByUrl = UploadFromUrl
::isEnabled()
884 && ( UploadFromUrl
::isAllowed( $this->getUser() ) === true )
885 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
886 $radio = $canUploadByUrl;
887 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
889 $descriptor = array();
890 if ( $this->mTextTop
) {
891 $descriptor['UploadFormTextTop'] = array(
893 'section' => 'source',
894 'default' => $this->mTextTop
,
899 $this->mMaxUploadSize
['file'] = min(
900 UploadBase
::getMaxUploadSize( 'file' ),
901 UploadBase
::getMaxPhpUploadSize()
904 $help = $this->msg( 'upload-maxfilesize',
905 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
908 // If the user can also upload by URL, there are 2 different file size limits.
909 // This extra message helps stress which limit corresponds to what.
910 if ( $canUploadByUrl ) {
911 $help .= $this->msg( 'word-separator' )->escaped();
912 $help .= $this->msg( 'upload_source_file' )->parse();
915 $descriptor['UploadFile'] = array(
916 'class' => 'UploadSourceField',
917 'section' => 'source',
919 'id' => 'wpUploadFile',
920 'radio-id' => 'wpSourceTypeFile',
921 'label-message' => 'sourcefilename',
922 'upload-type' => 'File',
925 'checked' => $selectedSourceType == 'file',
928 if ( $canUploadByUrl ) {
929 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
930 $descriptor['UploadFileURL'] = array(
931 'class' => 'UploadSourceField',
932 'section' => 'source',
933 'id' => 'wpUploadFileURL',
934 'radio-id' => 'wpSourceTypeurl',
935 'label-message' => 'sourceurl',
936 'upload-type' => 'url',
938 'help' => $this->msg( 'upload-maxfilesize',
939 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
941 $this->msg( 'word-separator' )->escaped() .
942 $this->msg( 'upload_source_url' )->parse(),
943 'checked' => $selectedSourceType == 'url',
946 Hooks
::run( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
948 $descriptor['Extensions'] = array(
950 'section' => 'source',
951 'default' => $this->getExtensionsMessage(),
959 * Get the messages indicating which extensions are preferred and prohibitted.
961 * @return string HTML string containing the message
963 protected function getExtensionsMessage() {
964 # Print a list of allowed file extensions, if so configured. We ignore
965 # MIME type here, it's incomprehensible to most people and too long.
966 $config = $this->getConfig();
968 if ( $config->get( 'CheckFileExtensions' ) ) {
969 $fileExtensions = array_unique( $config->get( 'FileExtensions' ) );
970 if ( $config->get( 'StrictFileExtensions' ) ) {
971 # Everything not permitted is banned
973 '<div id="mw-upload-permitted">' .
974 $this->msg( 'upload-permitted' )
975 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
976 ->numParams( count( $fileExtensions ) )
980 # We have to list both preferred and prohibited
981 $fileBlacklist = array_unique( $config->get( 'FileBlacklist' ) );
983 '<div id="mw-upload-preferred">' .
984 $this->msg( 'upload-preferred' )
985 ->params( $this->getLanguage()->commaList( $fileExtensions ) )
986 ->numParams( count( $fileExtensions ) )
989 '<div id="mw-upload-prohibited">' .
990 $this->msg( 'upload-prohibited' )
991 ->params( $this->getLanguage()->commaList( $fileBlacklist ) )
992 ->numParams( count( $fileBlacklist ) )
997 # Everything is permitted.
998 $extensionsList = '';
1001 return $extensionsList;
1005 * Get the descriptor of the fieldset that contains the file description
1006 * input. The section is 'description'
1008 * @return array Descriptor array
1010 protected function getDescriptionSection() {
1011 $config = $this->getConfig();
1012 if ( $this->mSessionKey
) {
1013 $stash = RepoGroup
::singleton()->getLocalRepo()->getUploadStash( $this->getUser() );
1015 $file = $stash->getFile( $this->mSessionKey
);
1016 } catch ( Exception
$e ) {
1022 $mto = $file->transform( array( 'width' => 120 ) );
1023 $this->addHeaderText(
1024 '<div class="thumb t' . $wgContLang->alignEnd() . '">' .
1025 Html
::element( 'img', array(
1026 'src' => $mto->getUrl(),
1027 'class' => 'thumbimage',
1028 ) ) . '</div>', 'description' );
1032 $descriptor = array(
1033 'DestFile' => array(
1035 'section' => 'description',
1036 'id' => 'wpDestFile',
1037 'label-message' => 'destfilename',
1039 'default' => $this->mDestFile
,
1040 # @todo FIXME: Hack to work around poor handling of the 'default' option in HTMLForm
1041 'nodata' => strval( $this->mDestFile
) !== '',
1043 'UploadDescription' => array(
1044 'type' => 'textarea',
1045 'section' => 'description',
1046 'id' => 'wpUploadDescription',
1047 'label-message' => $this->mForReUpload
1048 ?
'filereuploadsummary'
1049 : 'fileuploadsummary',
1050 'default' => $this->mComment
,
1051 'cols' => $this->getUser()->getIntOption( 'cols' ),
1055 if ( $this->mTextAfterSummary
) {
1056 $descriptor['UploadFormTextAfterSummary'] = array(
1058 'section' => 'description',
1059 'default' => $this->mTextAfterSummary
,
1064 $descriptor +
= array(
1065 'EditTools' => array(
1066 'type' => 'edittools',
1067 'section' => 'description',
1068 'message' => 'edittools-upload',
1072 if ( $this->mForReUpload
) {
1073 $descriptor['DestFile']['readonly'] = true;
1075 $descriptor['License'] = array(
1077 'class' => 'Licenses',
1078 'section' => 'description',
1079 'id' => 'wpLicense',
1080 'label-message' => 'license',
1084 if ( $config->get( 'UseCopyrightUpload' ) ) {
1085 $descriptor['UploadCopyStatus'] = array(
1087 'section' => 'description',
1088 'id' => 'wpUploadCopyStatus',
1089 'label-message' => 'filestatus',
1091 $descriptor['UploadSource'] = array(
1093 'section' => 'description',
1094 'id' => 'wpUploadSource',
1095 'label-message' => 'filesource',
1103 * Get the descriptor of the fieldset that contains the upload options,
1104 * such as "watch this file". The section is 'options'
1106 * @return array Descriptor array
1108 protected function getOptionsSection() {
1109 $user = $this->getUser();
1110 if ( $user->isLoggedIn() ) {
1111 $descriptor = array(
1112 'Watchthis' => array(
1114 'id' => 'wpWatchthis',
1115 'label-message' => 'watchthisupload',
1116 'section' => 'options',
1117 'default' => $this->mWatch
,
1121 if ( !$this->mHideIgnoreWarning
) {
1122 $descriptor['IgnoreWarning'] = array(
1124 'id' => 'wpIgnoreWarning',
1125 'label-message' => 'ignorewarnings',
1126 'section' => 'options',
1130 $descriptor['DestFileWarningAck'] = array(
1132 'id' => 'wpDestFileWarningAck',
1133 'default' => $this->mDestWarningAck ?
'1' : '',
1136 if ( $this->mForReUpload
) {
1137 $descriptor['ForReUpload'] = array(
1139 'id' => 'wpForReUpload',
1148 * Add the upload JS and show the form.
1150 public function show() {
1151 $this->addUploadJS();
1156 * Add upload JS to the OutputPage
1158 protected function addUploadJS() {
1159 $config = $this->getConfig();
1161 $useAjaxDestCheck = $config->get( 'UseAjax' ) && $config->get( 'AjaxUploadDestCheck' );
1162 $useAjaxLicensePreview = $config->get( 'UseAjax' ) &&
1163 $config->get( 'AjaxLicensePreview' ) && $config->get( 'EnableAPI' );
1164 $this->mMaxUploadSize
['*'] = UploadBase
::getMaxUploadSize();
1166 $scriptVars = array(
1167 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1168 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1169 'wgUploadAutoFill' => !$this->mForReUpload
&&
1170 // If we received mDestFile from the request, don't autofill
1171 // the wpDestFile textbox
1172 $this->mDestFile
=== '',
1173 'wgUploadSourceIds' => $this->mSourceIds
,
1174 'wgCheckFileExtensions' => $config->get( 'CheckFileExtensions' ),
1175 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1176 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1177 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1178 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1179 'wgFileCanRotate' => SpecialUpload
::rotationEnabled(),
1182 $out = $this->getOutput();
1183 $out->addJsConfigVars( $scriptVars );
1185 $out->addModules( array(
1186 'mediawiki.action.edit', // For <charinsert> support
1187 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1192 * Empty function; submission is handled elsewhere.
1194 * @return bool False
1196 function trySubmit() {
1202 * A form field that contains a radio box in the label
1204 class UploadSourceField
extends HTMLTextField
{
1207 * @param array $cellAttributes
1210 function getLabelHtml( $cellAttributes = array() ) {
1211 $id = $this->mParams
['id'];
1212 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1214 if ( !empty( $this->mParams
['radio'] ) ) {
1215 if ( isset( $this->mParams
['radio-id'] ) ) {
1216 $radioId = $this->mParams
['radio-id'];
1218 // Old way. For the benefit of extensions that do not define
1219 // the 'radio-id' key.
1220 $radioId = 'wpSourceType' . $this->mParams
['upload-type'];
1224 'name' => 'wpSourceType',
1227 'value' => $this->mParams
['upload-type'],
1230 if ( !empty( $this->mParams
['checked'] ) ) {
1231 $attribs['checked'] = 'checked';
1234 $label .= Html
::element( 'input', $attribs );
1237 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1243 function getSize() {
1244 return isset( $this->mParams
['size'] )
1245 ?
$this->mParams
['size']