Move things along the DROP TABLE.
[mediawiki.git] / includes / specials / SpecialUpload.php
bloba4aa086a1be12aea076e5276b68bf67ca6b22912
1 <?php
2 /**
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License as published by
6 * the Free Software Foundation; either version 2 of the License, or
7 * (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 * http://www.gnu.org/copyleft/gpl.html
20 /**
21 * @file
22 * @ingroup SpecialPage
23 * @ingroup Upload
25 * Form for handling uploads and special page.
28 class SpecialUpload extends SpecialPage {
29 /**
30 * Constructor : initialise object
31 * Get data POSTed through the form and assign them to the object
32 * @param $request WebRequest : data posted.
34 public function __construct( $request = null ) {
35 global $wgRequest;
37 parent::__construct( 'Upload', 'upload' );
39 $this->loadRequest( is_null( $request ) ? $wgRequest : $request );
42 /** Misc variables **/
43 protected $mRequest; // The WebRequest or FauxRequest this form is supposed to handle
44 protected $mSourceType;
45 protected $mUpload;
46 protected $mLocalFile;
47 protected $mUploadClicked;
49 /** User input variables from the "description" section **/
50 public $mDesiredDestName; // The requested target file name
51 protected $mComment;
52 protected $mLicense;
54 /** User input variables from the root section **/
55 protected $mIgnoreWarning;
56 protected $mWatchThis;
57 protected $mCopyrightStatus;
58 protected $mCopyrightSource;
60 /** Hidden variables **/
61 protected $mDestWarningAck;
62 protected $mForReUpload; // The user followed an "overwrite this file" link
63 protected $mCancelUpload; // The user clicked "Cancel and return to upload form" button
64 protected $mTokenOk;
65 protected $mUploadSuccessful = false; // Subclasses can use this to determine whether a file was uploaded
67 /** Text injection points for hooks not using HTMLForm **/
68 public $uploadFormTextTop;
69 public $uploadFormTextAfterSummary;
71 /**
72 * Initialize instance variables from request and create an Upload handler
74 * @param $request WebRequest: the request to extract variables from
76 protected function loadRequest( $request ) {
77 global $wgUser;
79 $this->mRequest = $request;
80 $this->mSourceType = $request->getVal( 'wpSourceType', 'file' );
81 $this->mUpload = UploadBase::createFromRequest( $request );
82 $this->mUploadClicked = $request->wasPosted()
83 && ( $request->getCheck( 'wpUpload' )
84 || $request->getCheck( 'wpUploadIgnoreWarning' ) );
86 // Guess the desired name from the filename if not provided
87 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
88 if( !$this->mDesiredDestName && $request->getFileName( 'wpUploadFile' ) !== null ) {
89 $this->mDesiredDestName = $request->getFileName( 'wpUploadFile' );
91 $this->mComment = $request->getText( 'wpUploadDescription' );
92 $this->mLicense = $request->getText( 'wpLicense' );
95 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
96 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' )
97 || $request->getCheck( 'wpUploadIgnoreWarning' );
98 $this->mWatchthis = $request->getBool( 'wpWatchthis' ) && $wgUser->isLoggedIn();
99 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
100 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
103 $this->mForReUpload = $request->getBool( 'wpForReUpload' ); // updating a file
104 $this->mCancelUpload = $request->getCheck( 'wpCancelUpload' )
105 || $request->getCheck( 'wpReUpload' ); // b/w compat
107 // If it was posted check for the token (no remote POST'ing with user credentials)
108 $token = $request->getVal( 'wpEditToken' );
109 if( $this->mSourceType == 'file' && $token == null ) {
110 // Skip token check for file uploads as that can't be faked via JS...
111 // Some client-side tools don't expect to need to send wpEditToken
112 // with their submissions, as that's new in 1.16.
113 $this->mTokenOk = true;
114 } else {
115 $this->mTokenOk = $wgUser->matchEditToken( $token );
118 $this->uploadFormTextTop = '';
119 $this->uploadFormTextAfterSummary = '';
123 * This page can be shown if uploading is enabled.
124 * Handle permission checking elsewhere in order to be able to show
125 * custom error messages.
127 * @param $user User object
128 * @return Boolean
130 public function userCanExecute( $user ) {
131 return UploadBase::isEnabled() && parent::userCanExecute( $user );
135 * Special page entry point
137 public function execute( $par ) {
138 global $wgUser, $wgOut;
140 $this->setHeaders();
141 $this->outputHeader();
143 # Check uploading enabled
144 if( !UploadBase::isEnabled() ) {
145 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
146 return;
149 # Check permissions
150 global $wgGroupPermissions;
151 $permissionRequired = UploadBase::isAllowed( $wgUser );
152 if( $permissionRequired !== true ) {
153 if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
154 || $wgGroupPermissions['autoconfirmed']['upload'] ) ) {
155 // Custom message if logged-in users without any special rights can upload
156 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
157 } else {
158 $wgOut->permissionRequired( $permissionRequired );
160 return;
163 # Check blocks
164 if( $wgUser->isBlocked() ) {
165 $wgOut->blockedPage();
166 return;
169 # Check whether we actually want to allow changing stuff
170 if( wfReadOnly() ) {
171 $wgOut->readOnlyPage();
172 return;
175 # Unsave the temporary file in case this was a cancelled upload
176 if ( $this->mCancelUpload ) {
177 if ( !$this->unsaveUploadedFile() ) {
178 # Something went wrong, so unsaveUploadedFile showed a warning
179 return;
183 # Process upload or show a form
184 if (
185 $this->mTokenOk && !$this->mCancelUpload &&
186 ( $this->mUpload && $this->mUploadClicked )
189 $this->processUpload();
190 } else {
191 # Backwards compatibility hook
192 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) ) {
193 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
194 return;
198 $this->showUploadForm( $this->getUploadForm() );
201 # Cleanup
202 if ( $this->mUpload ) {
203 $this->mUpload->cleanupTempFile();
208 * Show the main upload form
210 * @param $form Mixed: an HTMLForm instance or HTML string to show
212 protected function showUploadForm( $form ) {
213 # Add links if file was previously deleted
214 if ( !$this->mDesiredDestName ) {
215 $this->showViewDeletedLinks();
218 if ( $form instanceof HTMLForm ) {
219 $form->show();
220 } else {
221 global $wgOut;
222 $wgOut->addHTML( $form );
228 * Get an UploadForm instance with title and text properly set.
230 * @param $message String: HTML string to add to the form
231 * @param $sessionKey String: session key in case this is a stashed upload
232 * @param $hideIgnoreWarning Boolean: whether to hide "ignore warning" check box
233 * @return UploadForm
235 protected function getUploadForm( $message = '', $sessionKey = '', $hideIgnoreWarning = false ) {
236 global $wgOut;
238 # Initialize form
239 $form = new UploadForm( array(
240 'watch' => $this->getWatchCheck(),
241 'forreupload' => $this->mForReUpload,
242 'sessionkey' => $sessionKey,
243 'hideignorewarning' => $hideIgnoreWarning,
244 'destwarningack' => (bool)$this->mDestWarningAck,
246 'texttop' => $this->uploadFormTextTop,
247 'textaftersummary' => $this->uploadFormTextAfterSummary,
248 'destfile' => $this->mDesiredDestName,
249 ) );
250 $form->setTitle( $this->getTitle() );
252 # Check the token, but only if necessary
254 !$this->mTokenOk && !$this->mCancelUpload &&
255 ( $this->mUpload && $this->mUploadClicked )
258 $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
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::newFromText( $this->mDesiredDestName, NS_FILE );
264 $delNotice = ''; // empty by default
265 if ( $desiredTitleObj instanceof Title && !$desiredTitleObj->exists() ) {
266 LogEventsList::showLogExtract( $delNotice, array( 'delete', 'move' ),
267 $desiredTitleObj->getPrefixedText(),
268 '', array( 'lim' => 10,
269 'conds' => array( "log_action != 'revision'" ),
270 'showIfEmpty' => false,
271 'msgKey' => array( 'upload-recreate-warning' ) )
274 $form->addPreText( $delNotice );
276 # Add text to form
277 $form->addPreText( '<div id="uploadtext">' .
278 wfMsgExt( 'uploadtext', 'parse', array( $this->mDesiredDestName ) ) .
279 '</div>' );
280 # Add upload error message
281 $form->addPreText( $message );
283 # Add footer to form
284 $uploadFooter = wfMsgNoTrans( 'uploadfooter' );
285 if ( $uploadFooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadFooter ) ) {
286 $form->addPostText( '<div id="mw-upload-footer-message">'
287 . $wgOut->parse( $uploadFooter ) . "</div>\n" );
290 return $form;
295 * Shows the "view X deleted revivions link""
297 protected function showViewDeletedLinks() {
298 global $wgOut, $wgUser;
300 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
301 // Show a subtitle link to deleted revisions (to sysops et al only)
302 if( $title instanceof Title ) {
303 $count = $title->isDeleted();
304 if ( $count > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
305 $link = wfMsgExt(
306 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
307 array( 'parse', 'replaceafter' ),
308 $wgUser->getSkin()->linkKnown(
309 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
310 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
313 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
317 // Show the relevant lines from deletion log (for still deleted files only)
318 if( $title instanceof Title && $title->isDeletedQuick() && !$title->exists() ) {
319 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
324 * Stashes the upload and shows the main upload form.
326 * Note: only errors that can be handled by changing the name or
327 * description should be redirected here. It should be assumed that the
328 * file itself is sane and has passed UploadBase::verifyFile. This
329 * essentially means that UploadBase::VERIFICATION_ERROR and
330 * UploadBase::EMPTY_FILE should not be passed here.
332 * @param $message String: HTML message to be passed to mainUploadForm
334 protected function showRecoverableUploadError( $message ) {
335 $sessionKey = $this->mUpload->stashSession();
336 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
337 '<div class="error">' . $message . "</div>\n";
339 $form = $this->getUploadForm( $message, $sessionKey );
340 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
341 $this->showUploadForm( $form );
344 * Stashes the upload, shows the main form, but adds an "continue anyway button".
345 * Also checks whether there are actually warnings to display.
347 * @param $warnings Array
348 * @return boolean true if warnings were displayed, false if there are no
349 * warnings and the should continue processing like there was no warning
351 protected function showUploadWarning( $warnings ) {
352 # If there are no warnings, or warnings we can ignore, return early.
353 # mDestWarningAck is set when some javascript has shown the warning
354 # to the user. mForReUpload is set when the user clicks the "upload a
355 # new version" link.
356 if ( !$warnings || ( count( $warnings ) == 1 &&
357 isset( $warnings['exists'] ) &&
358 ( $this->mDestWarningAck || $this->mForReUpload ) ) )
360 return false;
363 $sessionKey = $this->mUpload->stashSession();
365 $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n"
366 . '<ul class="warning">';
367 foreach( $warnings as $warning => $args ) {
368 $msg = '';
369 if( $warning == 'exists' ) {
370 $msg = "\t<li>" . self::getExistsWarning( $args ) . "</li>\n";
371 } elseif( $warning == 'duplicate' ) {
372 $msg = self::getDupeWarning( $args );
373 } elseif( $warning == 'duplicate-archive' ) {
374 $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline',
375 array( Title::makeTitle( NS_FILE, $args )->getPrefixedText() ) )
376 . "</li>\n";
377 } else {
378 if ( $args === true ) {
379 $args = array();
380 } elseif ( !is_array( $args ) ) {
381 $args = array( $args );
383 $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
385 $warningHtml .= $msg;
387 $warningHtml .= "</ul>\n";
388 $warningHtml .= wfMsgExt( 'uploadwarning-text', 'parse' );
390 $form = $this->getUploadForm( $warningHtml, $sessionKey, /* $hideIgnoreWarning */ true );
391 $form->setSubmitText( wfMsg( 'upload-tryagain' ) );
392 $form->addButton( 'wpUploadIgnoreWarning', wfMsg( 'ignorewarning' ) );
393 $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
395 $this->showUploadForm( $form );
397 # Indicate that we showed a form
398 return true;
402 * Show the upload form with error message, but do not stash the file.
404 * @param $message HTML string
406 protected function showUploadError( $message ) {
407 $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
408 '<div class="error">' . $message . "</div>\n";
409 $this->showUploadForm( $this->getUploadForm( $message ) );
413 * Do the upload.
414 * Checks are made in SpecialUpload::execute()
416 protected function processUpload() {
417 global $wgUser, $wgOut;
419 // Fetch the file if required
420 $status = $this->mUpload->fetchFile();
421 if( !$status->isOK() ) {
422 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
423 return;
426 // Deprecated backwards compatibility hook
427 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) ) {
428 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
429 // Return without notifying the user of an error. This sucks, but
430 // this was the previous behaviour as well, and as this hook is
431 // deprecated we're not going to do anything about it.
432 return;
436 // Upload verification
437 $details = $this->mUpload->verifyUpload();
438 if ( $details['status'] != UploadBase::OK ) {
439 $this->processVerificationError( $details );
440 return;
443 // Verify permissions for this title
444 $permErrors = $this->mUpload->verifyPermissions( $wgUser );
445 if( $permErrors !== true ) {
446 $code = array_shift( $permErrors[0] );
447 $this->showRecoverableUploadError( wfMsgExt( $code,
448 'parseinline', $permErrors[0] ) );
449 return;
452 $this->mLocalFile = $this->mUpload->getLocalFile();
454 // Check warnings if necessary
455 if( !$this->mIgnoreWarning ) {
456 $warnings = $this->mUpload->checkWarnings();
457 if( $this->showUploadWarning( $warnings ) ) {
458 return;
462 // Get the page text if this is not a reupload
463 if( !$this->mForReUpload ) {
464 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
465 $this->mCopyrightStatus, $this->mCopyrightSource );
466 } else {
467 $pageText = false;
469 $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $wgUser );
470 if ( !$status->isGood() ) {
471 $this->showUploadError( $wgOut->parse( $status->getWikiText() ) );
472 return;
475 // Success, redirect to description page
476 $this->mUploadSuccessful = true;
477 wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
478 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
482 * Get the initial image page text based on a comment and optional file status information
484 public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
485 global $wgUseCopyrightUpload;
486 if ( $wgUseCopyrightUpload ) {
487 $licensetxt = '';
488 if ( $license != '' ) {
489 $licensetxt = '== ' . wfMsgForContent( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
491 $pageText = '== ' . wfMsgForContent( 'filedesc' ) . " ==\n" . $comment . "\n" .
492 '== ' . wfMsgForContent( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
493 "$licensetxt" .
494 '== ' . wfMsgForContent( 'filesource' ) . " ==\n" . $source;
495 } else {
496 if ( $license != '' ) {
497 $filedesc = $comment == '' ? '' : '== ' . wfMsgForContent( 'filedesc' ) . " ==\n" . $comment . "\n";
498 $pageText = $filedesc .
499 '== ' . wfMsgForContent( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
500 } else {
501 $pageText = $comment;
504 return $pageText;
508 * See if we should check the 'watch this page' checkbox on the form
509 * based on the user's preferences and whether we're being asked
510 * to create a new file or update an existing one.
512 * In the case where 'watch edits' is off but 'watch creations' is on,
513 * we'll leave the box unchecked.
515 * Note that the page target can be changed *on the form*, so our check
516 * state can get out of sync.
518 protected function getWatchCheck() {
519 global $wgUser;
520 if( $wgUser->getOption( 'watchdefault' ) ) {
521 // Watch all edits!
522 return true;
525 $local = wfLocalFile( $this->mDesiredDestName );
526 if( $local && $local->exists() ) {
527 // We're uploading a new version of an existing file.
528 // No creation, so don't watch it if we're not already.
529 return $local->getTitle()->userIsWatching();
530 } else {
531 // New page should get watched if that's our option.
532 return $wgUser->getOption( 'watchcreations' );
538 * Provides output to the user for a result of UploadBase::verifyUpload
540 * @param $details Array: result of UploadBase::verifyUpload
542 protected function processVerificationError( $details ) {
543 global $wgFileExtensions, $wgLang;
545 switch( $details['status'] ) {
547 /** Statuses that only require name changing **/
548 case UploadBase::MIN_LENGTH_PARTNAME:
549 $this->showRecoverableUploadError( wfMsgHtml( 'minlength1' ) );
550 break;
551 case UploadBase::ILLEGAL_FILENAME:
552 $this->showRecoverableUploadError( wfMsgExt( 'illegalfilename',
553 'parseinline', $details['filtered'] ) );
554 break;
555 case UploadBase::FILETYPE_MISSING:
556 $this->showRecoverableUploadError( wfMsgExt( 'filetype-missing',
557 'parseinline' ) );
558 break;
560 /** Statuses that require reuploading **/
561 case UploadBase::EMPTY_FILE:
562 $this->showUploadError( wfMsgHtml( 'emptyfile' ) );
563 break;
564 case UploadBase::FILE_TOO_LARGE:
565 $this->showUploadError( wfMsgHtml( 'largefileserver' ) );
566 break;
567 case UploadBase::FILETYPE_BADTYPE:
568 $finalExt = $details['finalExt'];
569 $this->showUploadError(
570 wfMsgExt( 'filetype-banned-type',
571 array( 'parseinline' ),
572 htmlspecialchars( $finalExt ),
573 implode(
574 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
575 $wgFileExtensions
577 $wgLang->formatNum( count( $wgFileExtensions ) )
580 break;
581 case UploadBase::VERIFICATION_ERROR:
582 unset( $details['status'] );
583 $code = array_shift( $details['details'] );
584 $this->showUploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
585 break;
586 case UploadBase::HOOK_ABORTED:
587 if ( is_array( $details['error'] ) ) { # allow hooks to return error details in an array
588 $args = $details['error'];
589 $error = array_shift( $args );
590 } else {
591 $error = $details['error'];
592 $args = null;
595 $this->showUploadError( wfMsgExt( $error, 'parseinline', $args ) );
596 break;
597 default:
598 throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
603 * Remove a temporarily kept file stashed by saveTempUploadedFile().
605 * @return Boolean: success
607 protected function unsaveUploadedFile() {
608 global $wgOut;
609 if ( !( $this->mUpload instanceof UploadFromStash ) ) {
610 return true;
612 $success = $this->mUpload->unsaveUploadedFile();
613 if ( !$success ) {
614 $wgOut->showFileDeleteError( $this->mUpload->getTempPath() );
615 return false;
616 } else {
617 return true;
621 /*** Functions for formatting warnings ***/
624 * Formats a result of UploadBase::getExistsWarning as HTML
625 * This check is static and can be done pre-upload via AJAX
627 * @param $exists Array: the result of UploadBase::getExistsWarning
628 * @return String: empty string if there is no warning or an HTML fragment
630 public static function getExistsWarning( $exists ) {
631 global $wgUser;
633 if ( !$exists ) {
634 return '';
637 $file = $exists['file'];
638 $filename = $file->getTitle()->getPrefixedText();
639 $warning = '';
641 $sk = $wgUser->getSkin();
643 if( $exists['warning'] == 'exists' ) {
644 // Exact match
645 $warning = wfMsgExt( 'fileexists', 'parseinline', $filename );
646 } elseif( $exists['warning'] == 'page-exists' ) {
647 // Page exists but file does not
648 $warning = wfMsgExt( 'filepageexists', 'parseinline', $filename );
649 } elseif ( $exists['warning'] == 'exists-normalized' ) {
650 $warning = wfMsgExt( 'fileexists-extension', 'parseinline', $filename,
651 $exists['normalizedFile']->getTitle()->getPrefixedText() );
652 } elseif ( $exists['warning'] == 'thumb' ) {
653 // Swapped argument order compared with other messages for backwards compatibility
654 $warning = wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline',
655 $exists['thumbFile']->getTitle()->getPrefixedText(), $filename );
656 } elseif ( $exists['warning'] == 'thumb-name' ) {
657 // Image w/o '180px-' does not exists, but we do not like these filenames
658 $name = $file->getName();
659 $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
660 $warning = wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart );
661 } elseif ( $exists['warning'] == 'bad-prefix' ) {
662 $warning = wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] );
663 } elseif ( $exists['warning'] == 'was-deleted' ) {
664 # If the file existed before and was deleted, warn the user of this
665 $ltitle = SpecialPage::getTitleFor( 'Log' );
666 $llink = $sk->linkKnown(
667 $ltitle,
668 wfMsgHtml( 'deletionlog' ),
669 array(),
670 array(
671 'type' => 'delete',
672 'page' => $filename
675 $warning = wfMsgWikiHtml( 'filewasdeleted', $llink );
678 return $warning;
682 * Get a list of warnings
684 * @param $filename String: local filename, e.g. 'file exists', 'non-descriptive filename'
685 * @return Array: list of warning messages
687 public static function ajaxGetExistsWarning( $filename ) {
688 $file = wfFindFile( $filename );
689 if( !$file ) {
690 // Force local file so we have an object to do further checks against
691 // if there isn't an exact match...
692 $file = wfLocalFile( $filename );
694 $s = '&#160;';
695 if ( $file ) {
696 $exists = UploadBase::getExistsWarning( $file );
697 $warning = self::getExistsWarning( $exists );
698 if ( $warning !== '' ) {
699 $s = "<div>$warning</div>";
702 return $s;
706 * Construct a warning and a gallery from an array of duplicate files.
708 public static function getDupeWarning( $dupes ) {
709 if( $dupes ) {
710 global $wgOut;
711 $msg = '<gallery>';
712 foreach( $dupes as $file ) {
713 $title = $file->getTitle();
714 $msg .= $title->getPrefixedText() .
715 '|' . $title->getText() . "\n";
717 $msg .= '</gallery>';
718 return '<li>' .
719 wfMsgExt( 'file-exists-duplicate', array( 'parse' ), count( $dupes ) ) .
720 $wgOut->parse( $msg ) .
721 "</li>\n";
722 } else {
723 return '';
730 * Sub class of HTMLForm that provides the form section of SpecialUpload
732 class UploadForm extends HTMLForm {
733 protected $mWatch;
734 protected $mForReUpload;
735 protected $mSessionKey;
736 protected $mHideIgnoreWarning;
737 protected $mDestWarningAck;
738 protected $mDestFile;
740 protected $mTextTop;
741 protected $mTextAfterSummary;
743 protected $mSourceIds;
745 public function __construct( $options = array() ) {
746 $this->mWatch = !empty( $options['watch'] );
747 $this->mForReUpload = !empty( $options['forreupload'] );
748 $this->mSessionKey = isset( $options['sessionkey'] )
749 ? $options['sessionkey'] : '';
750 $this->mHideIgnoreWarning = !empty( $options['hideignorewarning'] );
751 $this->mDestWarningAck = !empty( $options['destwarningack'] );
752 $this->mDestFile = isset( $options['destfile'] ) ? $options['destfile'] : '';
754 $this->mTextTop = isset( $options['texttop'] )
755 ? $options['texttop'] : '';
757 $this->mTextAfterSummary = isset( $options['textaftersummary'] )
758 ? $options['textaftersummary'] : '';
760 $sourceDescriptor = $this->getSourceSection();
761 $descriptor = $sourceDescriptor
762 + $this->getDescriptionSection()
763 + $this->getOptionsSection();
765 wfRunHooks( 'UploadFormInitDescriptor', array( &$descriptor ) );
766 parent::__construct( $descriptor, 'upload' );
768 # Set some form properties
769 $this->setSubmitText( wfMsg( 'uploadbtn' ) );
770 $this->setSubmitName( 'wpUpload' );
771 # Used message keys: 'accesskey-upload', 'tooltip-upload'
772 $this->setSubmitTooltip( 'upload' );
773 $this->setId( 'mw-upload-form' );
775 # Build a list of IDs for javascript insertion
776 $this->mSourceIds = array();
777 foreach ( $sourceDescriptor as $key => $field ) {
778 if ( !empty( $field['id'] ) ) {
779 $this->mSourceIds[] = $field['id'];
786 * Get the descriptor of the fieldset that contains the file source
787 * selection. The section is 'source'
789 * @return Array: descriptor array
791 protected function getSourceSection() {
792 global $wgLang, $wgUser, $wgRequest;
793 global $wgMaxUploadSize;
795 if ( $this->mSessionKey ) {
796 return array(
797 'wpSessionKey' => array(
798 'type' => 'hidden',
799 'default' => $this->mSessionKey,
801 'wpSourceType' => array(
802 'type' => 'hidden',
803 'default' => 'Stash',
808 $canUploadByUrl = UploadFromUrl::isEnabled() && $wgUser->isAllowed( 'upload_by_url' );
809 $radio = $canUploadByUrl;
810 $selectedSourceType = strtolower( $wgRequest->getText( 'wpSourceType', 'File' ) );
812 $descriptor = array();
813 if ( $this->mTextTop ) {
814 $descriptor['UploadFormTextTop'] = array(
815 'type' => 'info',
816 'section' => 'source',
817 'default' => $this->mTextTop,
818 'raw' => true,
822 $descriptor['UploadFile'] = array(
823 'class' => 'UploadSourceField',
824 'section' => 'source',
825 'type' => 'file',
826 'id' => 'wpUploadFile',
827 'label-message' => 'sourcefilename',
828 'upload-type' => 'File',
829 'radio' => &$radio,
830 'help' => wfMsgExt( 'upload-maxfilesize',
831 array( 'parseinline', 'escapenoentities' ),
832 $wgLang->formatSize(
833 wfShorthandToInteger( min(
834 wfShorthandToInteger(
835 ini_get( 'upload_max_filesize' )
836 ), $wgMaxUploadSize
839 ) . ' ' . wfMsgHtml( 'upload_source_file' ),
840 'checked' => $selectedSourceType == 'file',
842 if ( $canUploadByUrl ) {
843 $descriptor['UploadFileURL'] = array(
844 'class' => 'UploadSourceField',
845 'section' => 'source',
846 'id' => 'wpUploadFileURL',
847 'label-message' => 'sourceurl',
848 'upload-type' => 'url',
849 'radio' => &$radio,
850 'help' => wfMsgExt( 'upload-maxfilesize',
851 array( 'parseinline', 'escapenoentities' ),
852 $wgLang->formatSize( $wgMaxUploadSize )
853 ) . ' ' . wfMsgHtml( 'upload_source_url' ),
854 'checked' => $selectedSourceType == 'url',
857 wfRunHooks( 'UploadFormSourceDescriptors', array( &$descriptor, &$radio, $selectedSourceType ) );
859 $descriptor['Extensions'] = array(
860 'type' => 'info',
861 'section' => 'source',
862 'default' => $this->getExtensionsMessage(),
863 'raw' => true,
865 return $descriptor;
869 * Get the messages indicating which extensions are preferred and prohibitted.
871 * @return String: HTML string containing the message
873 protected function getExtensionsMessage() {
874 # Print a list of allowed file extensions, if so configured. We ignore
875 # MIME type here, it's incomprehensible to most people and too long.
876 global $wgLang, $wgCheckFileExtensions, $wgStrictFileExtensions,
877 $wgFileExtensions, $wgFileBlacklist;
879 if( $wgCheckFileExtensions ) {
880 if( $wgStrictFileExtensions ) {
881 # Everything not permitted is banned
882 $extensionsList =
883 '<div id="mw-upload-permitted">' .
884 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
885 "</div>\n";
886 } else {
887 # We have to list both preferred and prohibited
888 $extensionsList =
889 '<div id="mw-upload-preferred">' .
890 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
891 "</div>\n" .
892 '<div id="mw-upload-prohibited">' .
893 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
894 "</div>\n";
896 } else {
897 # Everything is permitted.
898 $extensionsList = '';
900 return $extensionsList;
904 * Get the descriptor of the fieldset that contains the file description
905 * input. The section is 'description'
907 * @return Array: descriptor array
909 protected function getDescriptionSection() {
910 global $wgUser, $wgOut;
912 $cols = intval( $wgUser->getOption( 'cols' ) );
913 if( $wgUser->getOption( 'editwidth' ) ) {
914 $wgOut->addInlineStyle( '#mw-htmlform-description { width: 100%; }' );
917 $descriptor = array(
918 'DestFile' => array(
919 'type' => 'text',
920 'section' => 'description',
921 'id' => 'wpDestFile',
922 'label-message' => 'destfilename',
923 'size' => 60,
924 'default' => $this->mDestFile,
925 # FIXME: hack to work around poor handling of the 'default' option in HTMLForm
926 'nodata' => strval( $this->mDestFile ) !== '',
928 'UploadDescription' => array(
929 'type' => 'textarea',
930 'section' => 'description',
931 'id' => 'wpUploadDescription',
932 'label-message' => $this->mForReUpload
933 ? 'filereuploadsummary'
934 : 'fileuploadsummary',
935 'cols' => $cols,
936 'rows' => 8,
939 if ( $this->mTextAfterSummary ) {
940 $descriptor['UploadFormTextAfterSummary'] = array(
941 'type' => 'info',
942 'section' => 'description',
943 'default' => $this->mTextAfterSummary,
944 'raw' => true,
948 $descriptor += array(
949 'EditTools' => array(
950 'type' => 'edittools',
951 'section' => 'description',
955 if ( $this->mForReUpload ) {
956 $descriptor['DestFile']['readonly'] = true;
957 } else {
958 $descriptor['License'] = array(
959 'type' => 'select',
960 'class' => 'Licenses',
961 'section' => 'description',
962 'id' => 'wpLicense',
963 'label-message' => 'license',
967 global $wgUseCopyrightUpload;
968 if ( $wgUseCopyrightUpload ) {
969 $descriptor['UploadCopyStatus'] = array(
970 'type' => 'text',
971 'section' => 'description',
972 'id' => 'wpUploadCopyStatus',
973 'label-message' => 'filestatus',
975 $descriptor['UploadSource'] = array(
976 'type' => 'text',
977 'section' => 'description',
978 'id' => 'wpUploadSource',
979 'label-message' => 'filesource',
983 return $descriptor;
987 * Get the descriptor of the fieldset that contains the upload options,
988 * such as "watch this file". The section is 'options'
990 * @return Array: descriptor array
992 protected function getOptionsSection() {
993 global $wgUser;
995 if ( $wgUser->isLoggedIn() ) {
996 $descriptor = array(
997 'Watchthis' => array(
998 'type' => 'check',
999 'id' => 'wpWatchthis',
1000 'label-message' => 'watchthisupload',
1001 'section' => 'options',
1002 'default' => $wgUser->getOption( 'watchcreations' ),
1006 if ( !$this->mHideIgnoreWarning ) {
1007 $descriptor['IgnoreWarning'] = array(
1008 'type' => 'check',
1009 'id' => 'wpIgnoreWarning',
1010 'label-message' => 'ignorewarnings',
1011 'section' => 'options',
1015 $descriptor['wpDestFileWarningAck'] = array(
1016 'type' => 'hidden',
1017 'id' => 'wpDestFileWarningAck',
1018 'default' => $this->mDestWarningAck ? '1' : '',
1021 if ( $this->mForReUpload ) {
1022 $descriptor['wpForReUpload'] = array(
1023 'type' => 'hidden',
1024 'id' => 'wpForReUpload',
1025 'default' => '1',
1029 return $descriptor;
1033 * Add the upload JS and show the form.
1035 public function show() {
1036 $this->addUploadJS();
1037 parent::show();
1041 * Add upload JS to $wgOut
1043 protected function addUploadJS() {
1044 global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview, $wgEnableAPI, $wgStrictFileExtensions;
1045 global $wgOut;
1047 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
1048 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview && $wgEnableAPI;
1050 $scriptVars = array(
1051 'wgAjaxUploadDestCheck' => $useAjaxDestCheck,
1052 'wgAjaxLicensePreview' => $useAjaxLicensePreview,
1053 'wgUploadAutoFill' => !$this->mForReUpload &&
1054 // If we received mDestFile from the request, don't autofill
1055 // the wpDestFile textbox
1056 $this->mDestFile === '',
1057 'wgUploadSourceIds' => $this->mSourceIds,
1058 'wgStrictFileExtensions' => $wgStrictFileExtensions,
1059 'wgCapitalizeUploads' => MWNamespace::isCapitalized( NS_FILE ),
1062 $wgOut->addScript( Skin::makeVariablesScript( $scriptVars ) );
1064 // For <charinsert> support
1065 $wgOut->addScriptFile( 'edit.js' );
1066 $wgOut->addScriptFile( 'upload.js' );
1070 * Empty function; submission is handled elsewhere.
1072 * @return bool false
1074 function trySubmit() {
1075 return false;
1081 * A form field that contains a radio box in the label
1083 class UploadSourceField extends HTMLTextField {
1084 function getLabelHtml( $cellAttributes = array() ) {
1085 $id = "wpSourceType{$this->mParams['upload-type']}";
1086 $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel );
1088 if ( !empty( $this->mParams['radio'] ) ) {
1089 $attribs = array(
1090 'name' => 'wpSourceType',
1091 'type' => 'radio',
1092 'id' => $id,
1093 'value' => $this->mParams['upload-type'],
1095 if ( !empty( $this->mParams['checked'] ) ) {
1096 $attribs['checked'] = 'checked';
1098 $label .= Html::element( 'input', $attribs );
1101 return Html::rawElement( 'td', array( 'class' => 'mw-label' ) + $cellAttributes, $label );
1104 function getSize() {
1105 return isset( $this->mParams['size'] )
1106 ? $this->mParams['size']
1107 : 60;