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
);
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
495 * @todo Use Config obj instead of globals
497 public static function getInitialPageText( $comment = '', $license = '',
498 $copyStatus = '', $source = ''
500 global $wgUseCopyrightUpload, $wgForceUIMsgAsContentMsg;
503 /* These messages are transcluded into the actual text of the description page.
504 * Thus, forcing them as content messages makes the upload to produce an int: template
505 * instead of hardcoding it there in the uploader language.
507 foreach ( array( 'license-header', 'filedesc', 'filestatus', 'filesource' ) as $msgName ) {
508 if ( in_array( $msgName, (array)$wgForceUIMsgAsContentMsg ) ) {
509 $msg[$msgName] = "{{int:$msgName}}";
511 $msg[$msgName] = wfMessage( $msgName )->inContentLanguage()->text();
515 if ( $wgUseCopyrightUpload ) {
517 if ( $license != '' ) {
518 $licensetxt = '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
520 $pageText = '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n" .
521 '== ' . $msg['filestatus'] . " ==\n" . $copyStatus . "\n" .
523 '== ' . $msg['filesource'] . " ==\n" . $source;
525 if ( $license != '' ) {
526 $filedesc = $comment == '' ?
'' : '== ' . $msg['filedesc'] . " ==\n" . $comment . "\n";
527 $pageText = $filedesc .
528 '== ' . $msg['license-header'] . " ==\n" . '{{' . $license . '}}' . "\n";
530 $pageText = $comment;
538 * See if we should check the 'watch this page' checkbox on the form
539 * based on the user's preferences and whether we're being asked
540 * to create a new file or update an existing one.
542 * In the case where 'watch edits' is off but 'watch creations' is on,
543 * we'll leave the box unchecked.
545 * Note that the page target can be changed *on the form*, so our check
546 * state can get out of sync.
547 * @return bool|string
549 protected function getWatchCheck() {
550 if ( $this->getUser()->getOption( 'watchdefault' ) ) {
555 $desiredTitleObj = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
556 if ( $desiredTitleObj instanceof Title
&& $this->getUser()->isWatched( $desiredTitleObj ) ) {
557 // Already watched, don't change that
561 $local = wfLocalFile( $this->mDesiredDestName
);
562 if ( $local && $local->exists() ) {
563 // We're uploading a new version of an existing file.
564 // No creation, so don't watch it if we're not already.
567 // New page should get watched if that's our option.
568 return $this->getUser()->getOption( 'watchcreations' );
573 * Provides output to the user for a result of UploadBase::verifyUpload
575 * @param array $details Result of UploadBase::verifyUpload
576 * @throws MWException
578 protected function processVerificationError( $details ) {
579 switch ( $details['status'] ) {
581 /** Statuses that only require name changing **/
582 case UploadBase
::MIN_LENGTH_PARTNAME
:
583 $this->showRecoverableUploadError( $this->msg( 'minlength1' )->escaped() );
585 case UploadBase
::ILLEGAL_FILENAME
:
586 $this->showRecoverableUploadError( $this->msg( 'illegalfilename',
587 $details['filtered'] )->parse() );
589 case UploadBase
::FILENAME_TOO_LONG
:
590 $this->showRecoverableUploadError( $this->msg( 'filename-toolong' )->escaped() );
592 case UploadBase
::FILETYPE_MISSING
:
593 $this->showRecoverableUploadError( $this->msg( 'filetype-missing' )->parse() );
595 case UploadBase
::WINDOWS_NONASCII_FILENAME
:
596 $this->showRecoverableUploadError( $this->msg( 'windows-nonascii-filename' )->parse() );
599 /** Statuses that require reuploading **/
600 case UploadBase
::EMPTY_FILE
:
601 $this->showUploadError( $this->msg( 'emptyfile' )->escaped() );
603 case UploadBase
::FILE_TOO_LARGE
:
604 $this->showUploadError( $this->msg( 'largefileserver' )->escaped() );
606 case UploadBase
::FILETYPE_BADTYPE
:
607 $msg = $this->msg( 'filetype-banned-type' );
608 if ( isset( $details['blacklistedExt'] ) ) {
609 $msg->params( $this->getLanguage()->commaList( $details['blacklistedExt'] ) );
611 $msg->params( $details['finalExt'] );
613 $extensions = array_unique( $this->getConfig()->get( 'FileExtensions' ) );
614 $msg->params( $this->getLanguage()->commaList( $extensions ),
615 count( $extensions ) );
617 // Add PLURAL support for the first parameter. This results
618 // in a bit unlogical parameter sequence, but does not break
620 if ( isset( $details['blacklistedExt'] ) ) {
621 $msg->params( count( $details['blacklistedExt'] ) );
626 $this->showUploadError( $msg->parse() );
628 case UploadBase
::VERIFICATION_ERROR
:
629 unset( $details['status'] );
630 $code = array_shift( $details['details'] );
631 $this->showUploadError( $this->msg( $code, $details['details'] )->parse() );
633 case UploadBase
::HOOK_ABORTED
:
634 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
635 $args = $details['error'];
636 $error = array_shift( $args );
638 $error = $details['error'];
642 $this->showUploadError( $this->msg( $error, $args )->parse() );
645 throw new MWException( __METHOD__
. ": Unknown value `{$details['status']}`" );
650 * Remove a temporarily kept file stashed by saveTempUploadedFile().
652 * @return bool Success
654 protected function unsaveUploadedFile() {
655 if ( !( $this->mUpload
instanceof UploadFromStash
) ) {
658 $success = $this->mUpload
->unsaveUploadedFile();
660 $this->getOutput()->showFileDeleteError( $this->mUpload
->getTempPath() );
668 /*** Functions for formatting warnings ***/
671 * Formats a result of UploadBase::getExistsWarning as HTML
672 * This check is static and can be done pre-upload via AJAX
674 * @param array $exists The result of UploadBase::getExistsWarning
675 * @return string Empty string if there is no warning or an HTML fragment
677 public static function getExistsWarning( $exists ) {
682 $file = $exists['file'];
683 $filename = $file->getTitle()->getPrefixedText();
686 if ( $exists['warning'] == 'exists' ) {
688 $warning = wfMessage( 'fileexists', $filename )->parse();
689 } elseif ( $exists['warning'] == 'page-exists' ) {
690 // Page exists but file does not
691 $warning = wfMessage( 'filepageexists', $filename )->parse();
692 } elseif ( $exists['warning'] == 'exists-normalized' ) {
693 $warning = wfMessage( 'fileexists-extension', $filename,
694 $exists['normalizedFile']->getTitle()->getPrefixedText() )->parse();
695 } elseif ( $exists['warning'] == 'thumb' ) {
696 // Swapped argument order compared with other messages for backwards compatibility
697 $warning = wfMessage( 'fileexists-thumbnail-yes',
698 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename )->parse();
699 } elseif ( $exists['warning'] == 'thumb-name' ) {
700 // Image w/o '180px-' does not exists, but we do not like these filenames
701 $name = $file->getName();
702 $badPart = substr( $name, 0, strpos( $name, '-' ) +
1 );
703 $warning = wfMessage( 'file-thumbnail-no', $badPart )->parse();
704 } elseif ( $exists['warning'] == 'bad-prefix' ) {
705 $warning = wfMessage( 'filename-bad-prefix', $exists['prefix'] )->parse();
706 } elseif ( $exists['warning'] == 'was-deleted' ) {
707 # If the file existed before and was deleted, warn the user of this
708 $ltitle = SpecialPage
::getTitleFor( 'Log' );
709 $llink = Linker
::linkKnown(
711 wfMessage( 'deletionlog' )->escaped(),
718 $warning = wfMessage( 'filewasdeleted' )->rawParams( $llink )->parseAsBlock();
725 * Construct a warning and a gallery from an array of duplicate files.
726 * @param array $dupes
729 public function getDupeWarning( $dupes ) {
734 $gallery = ImageGalleryBase
::factory( false, $this->getContext() );
735 $gallery->setShowBytes( false );
736 foreach ( $dupes as $file ) {
737 $gallery->add( $file->getTitle() );
741 $this->msg( 'file-exists-duplicate' )->numParams( count( $dupes ) )->parse() .
742 $gallery->toHTML() . "</li>\n";
745 protected function getGroupName() {
750 * Should we rotate images in the preview on Special:Upload.
752 * This controls js: mw.config.get( 'wgFileCanRotate' )
754 * @todo What about non-BitmapHandler handled files?
756 public static function rotationEnabled() {
757 $bitmapHandler = new BitmapHandler();
758 return $bitmapHandler->autoRotateEnabled();
763 * Sub class of HTMLForm that provides the form section of SpecialUpload
765 class UploadForm
extends HTMLForm
{
767 protected $mForReUpload;
768 protected $mSessionKey;
769 protected $mHideIgnoreWarning;
770 protected $mDestWarningAck;
771 protected $mDestFile;
775 protected $mTextAfterSummary;
777 protected $mSourceIds;
779 protected $mMaxFileSize = array();
781 protected $mMaxUploadSize = array();
783 public function __construct( array $options = array(), IContextSource
$context = null ) {
784 $this->mWatch
= !empty( $options['watch'] );
785 $this->mForReUpload
= !empty( $options['forreupload'] );
786 $this->mSessionKey
= isset( $options['sessionkey'] ) ?
$options['sessionkey'] : '';
787 $this->mHideIgnoreWarning
= !empty( $options['hideignorewarning'] );
788 $this->mDestWarningAck
= !empty( $options['destwarningack'] );
789 $this->mDestFile
= isset( $options['destfile'] ) ?
$options['destfile'] : '';
791 $this->mComment
= isset( $options['description'] ) ?
792 $options['description'] : '';
794 $this->mTextTop
= isset( $options['texttop'] )
795 ?
$options['texttop'] : '';
797 $this->mTextAfterSummary
= isset( $options['textaftersummary'] )
798 ?
$options['textaftersummary'] : '';
800 $sourceDescriptor = $this->getSourceSection();
801 $descriptor = $sourceDescriptor
802 +
$this->getDescriptionSection()
803 +
$this->getOptionsSection();
805 Hooks
::run( 'UploadFormInitDescriptor', array( &$descriptor ) );
806 parent
::__construct( $descriptor, $context, 'upload' );
808 # Add a link to edit MediaWik:Licenses
809 if ( $this->getUser()->isAllowed( 'editinterface' ) ) {
810 $licensesLink = Linker
::link(
811 Title
::makeTitle( NS_MEDIAWIKI
, 'Licenses' ),
812 $this->msg( 'licenses-edit' )->escaped(),
814 array( 'action' => 'edit' )
816 $editLicenses = '<p class="mw-upload-editlicenses">' . $licensesLink . '</p>';
817 $this->addFooterText( $editLicenses, 'description' );
820 # Set some form properties
821 $this->setSubmitText( $this->msg( 'uploadbtn' )->text() );
822 $this->setSubmitName( 'wpUpload' );
823 # Used message keys: 'accesskey-upload', 'tooltip-upload'
824 $this->setSubmitTooltip( 'upload' );
825 $this->setId( 'mw-upload-form' );
827 # Build a list of IDs for javascript insertion
828 $this->mSourceIds
= array();
829 foreach ( $sourceDescriptor as $field ) {
830 if ( !empty( $field['id'] ) ) {
831 $this->mSourceIds
[] = $field['id'];
837 * Get the descriptor of the fieldset that contains the file source
838 * selection. The section is 'source'
840 * @return array Descriptor array
842 protected function getSourceSection() {
843 if ( $this->mSessionKey
) {
845 'SessionKey' => array(
847 'default' => $this->mSessionKey
,
849 'SourceType' => array(
851 'default' => 'Stash',
856 $canUploadByUrl = UploadFromUrl
::isEnabled()
857 && ( UploadFromUrl
::isAllowed( $this->getUser() ) === true )
858 && $this->getConfig()->get( 'CopyUploadsFromSpecialUpload' );
859 $radio = $canUploadByUrl;
860 $selectedSourceType = strtolower( $this->getRequest()->getText( 'wpSourceType', 'File' ) );
862 $descriptor = array();
863 if ( $this->mTextTop
) {
864 $descriptor['UploadFormTextTop'] = array(
866 'section' => 'source',
867 'default' => $this->mTextTop
,
872 $this->mMaxUploadSize
['file'] = UploadBase
::getMaxUploadSize( 'file' );
873 # Limit to upload_max_filesize unless we are running under HipHop and
874 # that setting doesn't exist
876 $this->mMaxUploadSize
['file'] = min( $this->mMaxUploadSize
['file'],
877 wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ),
878 wfShorthandToInteger( ini_get( 'post_max_size' ) )
882 $descriptor['UploadFile'] = array(
883 'class' => 'UploadSourceField',
884 'section' => 'source',
886 'id' => 'wpUploadFile',
887 'radio-id' => 'wpSourceTypeFile',
888 'label-message' => 'sourcefilename',
889 'upload-type' => 'File',
891 'help' => $this->msg( 'upload-maxfilesize',
892 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['file'] )
894 $this->msg( 'word-separator' )->escaped() .
895 $this->msg( 'upload_source_file' )->escaped(),
896 'checked' => $selectedSourceType == 'file',
899 if ( $canUploadByUrl ) {
900 $this->mMaxUploadSize
['url'] = UploadBase
::getMaxUploadSize( 'url' );
901 $descriptor['UploadFileURL'] = array(
902 'class' => 'UploadSourceField',
903 'section' => 'source',
904 'id' => 'wpUploadFileURL',
905 'radio-id' => 'wpSourceTypeurl',
906 'label-message' => 'sourceurl',
907 'upload-type' => 'url',
909 'help' => $this->msg( 'upload-maxfilesize',
910 $this->getContext()->getLanguage()->formatSize( $this->mMaxUploadSize
['url'] )
912 $this->msg( 'word-separator' )->escaped() .
913 $this->msg( 'upload_source_url' )->parse(),
914 'checked' => $selectedSourceType == 'url',
917 Hooks
::run( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
919 $descriptor['Extensions'] = array(
921 'section' => 'source',
922 'default' => $this->getExtensionsMessage(),
930 * Get the messages indicating which extensions are preferred and prohibitted.
932 * @return string HTML string containing the message
934 protected function getExtensionsMessage() {
935 # Print a list of allowed file extensions, if so configured. We ignore
936 # MIME type here, it's incomprehensible to most people and too long.
937 $config = $this->getConfig();
939 if ( $config->get( 'CheckFileExtensions' ) ) {
940 if ( $config->get( 'StrictFileExtensions' ) ) {
941 # Everything not permitted is banned
943 '<div id="mw-upload-permitted">' .
946 $this->getContext()->getLanguage()->commaList(
947 array_unique( $config->get( 'FileExtensions' ) )
952 # We have to list both preferred and prohibited
954 '<div id="mw-upload-preferred">' .
957 $this->getContext()->getLanguage()->commaList(
958 array_unique( $config->get( 'FileExtensions' ) )
962 '<div id="mw-upload-prohibited">' .
965 $this->getContext()->getLanguage()->commaList(
966 array_unique( $config->get( '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();
990 $file = $stash->getFile( $this->mSessionKey
);
991 } catch ( MWException
$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 'wgStrictFileExtensions' => $config->get( 'StrictFileExtensions' ),
1150 'wgFileExtensions' => array_values( array_unique( $config->get( 'FileExtensions' ) ) ),
1151 'wgCapitalizeUploads' => MWNamespace
::isCapitalized( NS_FILE
),
1152 'wgMaxUploadSize' => $this->mMaxUploadSize
,
1153 'wgFileCanRotate' => SpecialUpload
::rotationEnabled(),
1156 $out = $this->getOutput();
1157 $out->addJsConfigVars( $scriptVars );
1159 $out->addModules( array(
1160 'mediawiki.action.edit', // For <charinsert> support
1161 'mediawiki.special.upload', // Extras for thumbnail and license preview.
1166 * Empty function; submission is handled elsewhere.
1168 * @return bool False
1170 function trySubmit() {
1176 * A form field that contains a radio box in the label
1178 class UploadSourceField
extends HTMLTextField
{
1181 * @param array $cellAttributes
1184 function getLabelHtml( $cellAttributes = array() ) {
1185 $id = $this->mParams
['id'];
1186 $label = Html
::rawElement( 'label', array( 'for' => $id ), $this->mLabel
);
1188 if ( !empty( $this->mParams
['radio'] ) ) {
1189 if ( isset( $this->mParams
['radio-id'] ) ) {
1190 $radioId = $this->mParams
['radio-id'];
1192 // Old way. For the benefit of extensions that do not define
1193 // the 'radio-id' key.
1194 $radioId = 'wpSourceType' . $this->mParams
['upload-type'];
1198 'name' => 'wpSourceType',
1201 'value' => $this->mParams
['upload-type'],
1204 if ( !empty( $this->mParams
['checked'] ) ) {
1205 $attribs['checked'] = 'checked';
1208 $label .= Html
::element( 'input', $attribs );
1211 return Html
::rawElement( 'td', array( 'class' => 'mw-label' ) +
$cellAttributes, $label );
1217 function getSize() {
1218 return isset( $this->mParams
['size'] )
1219 ?
$this->mParams
['size']