* (bug 21183) Missing global declaration of $wgLang in SpecialUpload::processVerifica...
[lhc/web/wiklou.git] / includes / specials / SpecialUpload.php
index ff24433..4339f43 100644 (file)
 /**
  * @file
  * @ingroup SpecialPage
+ * @ingroup Upload
+ * 
+ * Form for handling uploads and special page.
+ * 
  */
 
-
-/**
- * Entry point
- */
-function wfSpecialUpload() {
-       global $wgRequest;
-       $form = new UploadForm( $wgRequest );
-       $form->execute();
-}
-
-/**
- * implements Special:Upload
- * @ingroup SpecialPage
- */
-class UploadForm {
-       /**#@+
-        * @access private
-        */
-       var $mComment, $mLicense, $mIgnoreWarning;
-       var $mCopyrightStatus, $mCopyrightSource, $mReUpload, $mAction, $mUploadClicked;
-       var $mDestWarningAck;
-       var $mLocalFile;
-       
-       var $mUpload;   // Instance of UploadFromBase or derivative
-
-       # Placeholders for text injection by hooks (must be HTML)
-       # extensions should take care to _append_ to the present value
-       var $uploadFormTextTop;
-       var $uploadFormTextAfterSummary;
-
-       /**#@-*/
-
+class SpecialUpload extends SpecialPage {
        /**
         * Constructor : initialise object
         * Get data POSTed through the form and assign them to the object
-        * @param $request Data posted.
+        * @param WebRequest $request Data posted.
         */
-       function __construct( &$request ) {
-               global $wgAllowCopyUploads;
+       public function __construct( $request = null ) {
+               global $wgRequest;
+               
+               parent::__construct( 'Upload', 'upload' );
+               
+               $this->loadRequest( is_null( $request ) ? $wgRequest : $request );
+       }
+       
+       /** Misc variables **/
+       protected $mRequest;                    // The WebRequest or FauxRequest this form is supposed to handle
+       protected $mSourceType;
+       protected $mUpload;
+       protected $mLocalFile;
+       protected $mUploadClicked;
+       
+       /** User input variables from the "description" section **/
+       protected $mDesiredDestName;    // The requested target file name
+       protected $mComment;
+       protected $mLicense;
+       
+       /** User input variables from the root section **/
+       protected $mIgnoreWarning;
+       protected $mWatchThis;
+       protected $mCopyrightStatus;
+       protected $mCopyrightSource;
+       
+       /** Hidden variables **/
+       protected $mForReUpload;                // The user followed an "overwrite this file" link
+       protected $mCancelUpload;               // The user clicked "Cancel and return to upload form" button
+       protected $mTokenOk;
+       
+       /**
+        * Initialize instance variables from request and create an Upload handler
+        * 
+        * @param WebRequest $request The request to extract variables from
+        */
+       protected function loadRequest( $request ) {
+               global $wgUser;
+
+               $this->mRequest = $request;
+               $this->mSourceType        = $request->getVal( 'wpSourceType', 'file' );
+               $this->mUpload            = UploadBase::createFromRequest( $request );
+               $this->mUploadClicked     = $request->getCheck( 'wpUpload' ) && $request->wasPosted();
+               
+               // Guess the desired name from the filename if not provided
                $this->mDesiredDestName   = $request->getText( 'wpDestFile' );
-               $this->mIgnoreWarning     = $request->getCheck( 'wpIgnoreWarning' );
+               if( !$this->mDesiredDestName )
+                       $this->mDesiredDestName = $request->getText( 'wpUploadFile' );
                $this->mComment           = $request->getText( 'wpUploadDescription' );
+               $this->mLicense           = $request->getText( 'wpLicense' );           
+               
+               
+               $this->mIgnoreWarning     = $request->getCheck( 'wpIgnoreWarning' );
+               $this->mWatchthis         = $request->getBool( 'wpWatchthis' );
+               $this->mCopyrightStatus   = $request->getText( 'wpUploadCopyStatus' );
+               $this->mCopyrightSource   = $request->getText( 'wpUploadSource' );
 
-               if( !$request->wasPosted() ) {
-                       # GET requests just give the main form; no data except destination
-                       # filename and description
-                       return;
-               }
-
-               # Placeholders for text injection by hooks (empty per default)
-               $this->uploadFormTextTop = "";
-               $this->uploadFormTextAfterSummary = "";
 
-               $this->mReUpload          = $request->getCheck( 'wpReUpload' );
-               $this->mUploadClicked     = $request->getCheck( 'wpUpload' );
+               $this->mForReUpload       = $request->getBool( 'wpForReUpload' ); // updating a file            
+               $this->mCancelUpload      = $request->getCheck( 'wpCancelUpload' )
+                                        || $request->getCheck( 'wpReUpload' ); // b/w compat
 
-               $this->mLicense           = $request->getText( 'wpLicense' );
-               $this->mCopyrightStatus   = $request->getText( 'wpUploadCopyStatus' );
-               $this->mCopyrightSource   = $request->getText( 'wpUploadSource' );
-               $this->mWatchthis         = $request->getBool( 'wpWatchthis' );
-               $this->mSourceType        = $request->getText( 'wpSourceType' );
-               $this->mDestWarningAck    = $request->getText( 'wpDestFileWarningAck' );
-
-               $this->mAction            = $request->getVal( 'action' );
-
-               $desiredDestName = $request->getText( 'wpDestFile' );
-               if( !$desiredDestName )
-                       $desiredDestName = $request->getText( 'wpUploadFile' );
-
-               $this->mSessionKey        = $request->getInt( 'wpSessionKey' );
-               if( !empty( $this->mSessionKey ) &&
-                               isset( $_SESSION['wsUploadData'][$this->mSessionKey]['version'] ) &&
-                               $_SESSION['wsUploadData'][$this->mSessionKey]['version'] == 
-                                       UploadFromBase::SESSION_VERSION ) {
-                       /**
-                        * Confirming a temporarily stashed upload.
-                        * We don't want path names to be forged, so we keep
-                        * them in the session on the server and just give
-                        * an opaque key to the user agent.
-                        */
-                       
-                       $this->mUpload = new UploadFromStash( $desiredDestName );
-                       $data = $_SESSION['wsUploadData'][$this->mSessionKey];
-                       $this->mUpload->initialize( $data );
-                       
+               // If it was posted check for the token (no remote POST'ing with user credentials)
+               $token = $request->getVal( 'wpEditToken' );
+               if( $this->mSourceType == 'file' && $token == null ) {
+                       // Skip token check for file uploads as that can't be faked via JS...
+                       // Some client-side tools don't expect to need to send wpEditToken
+                       // with their submissions, as that's new in 1.16.
+                       $this->mTokenOk = true;
                } else {
-                       /**
-                        *Check for a newly uploaded file.
-                        */
-                       if( $wgAllowCopyUploads && $this->mSourceType == 'web' ) {
-                               $this->mUpload = new UploadFromUrl( $desiredDestName );
-                               $this->mUpload->initialize( $request->getText( 'wpUploadFileURL' ) );
-                       } else {
-                               $this->mUpload = new UploadFromUpload( $desiredDestName );
-                               $this->mUpload->initialize(
-                                       $request->getFileTempName( 'wpUploadFile' ),
-                                       $request->getFileSize( 'wpUploadFile' ),
-                                       $request->getFileName( 'wpUploadFile' )
-                               );
-                       }
+                       $this->mTokenOk = $wgUser->matchEditToken( $token );
                }
        }
-
-
-
+       
        /**
-        * Start doing stuff
-        * @access public
+        * This page can be shown if uploading is enabled.
+        * Handle permission checking elsewhere in order to be able to show 
+        * custom error messages.
+        * 
+        * @param User $user
+        * @return bool
         */
-       function execute() {
-               global $wgUser, $wgOut;
-               global $wgEnableUploads;
-
+       public function userCanExecute( $user ) {
+               return UploadBase::isEnabled() && parent::userCanExecute( $user );
+       }
+       
+       /**
+        * Special page entry point
+        */
+       public function execute( $par ) {
+               global $wgUser, $wgOut, $wgRequest;
+               
+               $this->setHeaders();
+               $this->outputHeader();
+               
                # Check uploading enabled
-               if( !$wgEnableUploads ) {
-                       $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName ) );
+               if( !UploadBase::isEnabled() ) {
+                       $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
                        return;
                }
 
                # Check permissions
+               global $wgGroupPermissions;
                if( !$wgUser->isAllowed( 'upload' ) ) {
-                       if( !$wgUser->isLoggedIn() ) {
+                       if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
+                               || $wgGroupPermissions['autoconfirmed']['upload'] ) ) {
+                               // Custom message if logged-in users without any special rights can upload
                                $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
                        } else {
                                $wgOut->permissionRequired( 'upload' );
@@ -139,85 +134,303 @@ class UploadForm {
                        return;
                }
 
+               # Check whether we actually want to allow changing stuff
                if( wfReadOnly() ) {
                        $wgOut->readOnlyPage();
                        return;
                }
-
-               if( $this->mReUpload ) {
-                       // User did not choose to ignore warnings
-                       if( !$this->mUpload->unsaveUploadedFile() ) {
+               
+               # Unsave the temporary file in case this was a cancelled upload
+               if ( $this->mCancelUpload ) {
+                       if ( !$this->unsaveUploadedFile() )
+                               # Something went wrong, so unsaveUploadedFile showed a warning
                                return;
-                       }
-                       # Because it is probably checked and shouldn't be
-                       $this->mIgnoreWarning = false;
-                       
-                       $this->mainUploadForm();
-               } elseif( $this->mUpload && ( 
-                                       'submit' == $this->mAction || 
-                                       $this->mUploadClicked 
-                               ) ) {
+               }
+               
+               # Process upload or show a form
+               if ( $this->mTokenOk && !$this->mCancelUpload 
+                               && ( $this->mUpload && $this->mUploadClicked ) ) { 
                        $this->processUpload();
                } else {
-                       $this->mainUploadForm();
+                       $this->showUploadForm( $this->getUploadForm() );
                }
                
-               if( $this->mUpload )
+               # Cleanup
+               if ( $this->mUpload )
                        $this->mUpload->cleanupTempFile();
        }
+       
+       /**
+        * Show the main upload form and optionally add the session key to the 
+        * output. This hides the source selection.
+        * 
+        * @param string $message HTML message to be shown at top of form
+        * @param string $sessionKey Session key of the stashed upload
+        */
+       protected function showUploadForm( $form ) {
+               # Add links if file was previously deleted
+               if ( !$this->mDesiredDestName )
+                       $this->showViewDeletedLinks();
+               
+               $form->show();
+       }
+       
+       /**
+        * Get an UploadForm instance with title and text properly set.
+        * 
+        * @param string $message HTML string to add to the form
+        * @param string $sessionKey Session key in case this is a stashed upload
+        * @return UploadForm
+        */
+       protected function getUploadForm( $message = '', $sessionKey = '' ) {
+               # Initialize form
+               $form = new UploadForm( $this->watchCheck(), $this->mForReUpload, $sessionKey );
+               $form->setTitle( $this->getTitle() );
+               
+               # Check the token, but only if necessary
+               if( !$this->mTokenOk && !$this->mCancelUpload 
+                               && ( $this->mUpload && $this->mUploadClicked ) ) 
+                       $form->addPreText( wfMsgExt( 'session_fail_preview', 'parseinline' ) );
+
+               # Add text to form
+               $form->addPreText( '<div id="uploadtext">' . wfMsgExt( 'uploadtext', 'parse' ) . '</div>');
+               # Add upload error message
+               $form->addPreText( $message );          
+               
+               return $form;           
+       }
+       
+       /**
+        * TODO: DOCUMENT
+        */
+       protected function showViewDeletedLinks() {
+               global $wgOut, $wgUser;
+               
+               $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
+               // Show a subtitle link to deleted revisions (to sysops et al only)
+               if( $title instanceof Title && ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
+                       $link = wfMsgExt(
+                               $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
+                               array( 'parse', 'replaceafter' ),
+                               $wgUser->getSkin()->linkKnown(
+                                       SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
+                                       wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
+                               )
+                       );
+                       $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
+               }
+
+               // Show the relevant lines from deletion log (for still deleted files only)
+               if( $title instanceof Title && $title->isDeletedQuick() && !$title->exists() ) {
+                       $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
+               }
+       }
+       
+       /**
+        * Stashes the upload and shows the main upload form.
+        * 
+        * Note: only errors that can be handled by changing the name or 
+        * description should be redirected here. It should be assumed that the
+        * file itself is sane and has passed UploadBase::verifyFile. This 
+        * essentially means that UploadBase::VERIFICATION_ERROR and 
+        * UploadBase::EMPTY_FILE should not be passed here.
+        * 
+        * @param string $message HTML message to be passed to mainUploadForm
+        */
+       protected function recoverableUploadError( $message ) {
+               $sessionKey = $this->mUpload->stashSession();
+               $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
+                       '<div class="error">' . $message . "</div>\n";
+               $this->showUploadForm( $this->getUploadForm( $message, $sessionKey ) );
+       }
+       /** 
+        * Stashes the upload, shows the main form, but adds an "continue anyway button"
+        * 
+        * @param array $warnings
+        */
+       protected function uploadWarning( $warnings ) {
+               global $wgUser;
+               
+               $sessionKey = $this->mUpload->stashSession();
+               
+               $sk = $wgUser->getSkin();
 
+               $warningHtml = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" 
+                       . '<ul class="warning">';
+               foreach( $warnings as $warning => $args ) {
+                               $msg = '';
+                               if( $warning == 'exists' ) {
+                                       $msg = self::getExistsWarning( $args );
+                               } elseif( $warning == 'duplicate' ) {
+                                       $msg = self::getDupeWarning( $args );
+                               } elseif( $warning == 'duplicate-archive' ) {
+                                       $msg = "\t<li>" . wfMsgExt( 'file-deleted-duplicate', 'parseinline', 
+                                                       array( Title::makeTitle( NS_FILE, $args )->getPrefixedText() ) ) 
+                                               . "</li>\n";
+                               } else {
+                                       if ( is_bool( $args ) )
+                                               $args = array();
+                                       elseif ( !is_array( $args ) )
+                                               $args = array( $args );
+                                       $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
+                               }
+                               $warningHtml .= $msg;
+               }
+               
+               $form = $this->getUploadForm( $warningHtml, $sessionKey );
+               $form->setSubmitText( wfMsg( 'ignorewarning' ) );
+               $form->addButton( 'wpCancelUpload', wfMsg( 'reuploaddesc' ) );
+               
+               $this->showUploadForm( $form );
+       }
+       
        /**
-        * Do the upload
+        * Show the upload form with error message, but do not stash the file.
+        * 
+        * @param string $message
+        */
+       protected function uploadError( $message ) {
+               $message = '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" .
+                       '<div class="error">' . $message . "</div>\n";
+               $this->showUploadForm( $this->getUploadForm( $message ) );
+       }
+       
+       /**
+        * Do the upload.
         * Checks are made in SpecialUpload::execute()
-        *
-        * @access private
         */
-       function processUpload(){
-               global $wgUser, $wgOut, $wgFileExtensions, $wgLang;
-               $details = null;
-               $value = null;
-               $value = $this->internalProcessUpload( $details );
-
-               switch($value) {
-                       case UploadFromBase::SUCCESS:
-                               $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
-                               break;
+       protected function processUpload() {
+               global $wgUser, $wgOut;
+               
+               // Verify permissions
+               $permErrors = $this->mUpload->verifyPermissions( $wgUser );
+               if( $permErrors !== true )
+                       return $wgOut->showPermissionsErrorPage( $permErrors );
+
+               // Fetch the file if required
+               $status = $this->mUpload->fetchFile();
+               if( !$status->isOK() )
+                       return $this->mainUploadForm( $wgOut->parse( $status->getWikiText() ) );
+               
+               // Upload verification
+               $details = $this->mUpload->verifyUpload();
+               if ( $details['status'] != UploadBase::OK )
+                       return $this->processVerificationError( $details );
+               
+               $this->mLocalFile = $this->mUpload->getLocalFile();
 
-                       case UploadFromBase::BEFORE_PROCESSING:
-                               // Do... nothing? Why?
-                               break;
+               // Check warnings if necessary
+               if( !$this->mIgnoreWarning ) {
+                       $warnings = $this->mUpload->checkWarnings();
+                       if( count( $warnings ) )
+                               return $this->uploadWarning( $warnings );
+               }
 
-                       case UploadFromBase::LARGE_FILE_SERVER:
-                               $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
-                               break;
+               // Get the page text if this is not a reupload
+               if( !$this->mForReUpload ) {
+                       $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
+                               $this->mCopyrightStatus, $this->mCopyrightSource );
+               } else {
+                       $pageText = false;
+               }
+               $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $wgUser );
+               if ( !$status->isGood() )
+                       return $this->uploadError( $wgOut->parse( $status->getWikiText() ) );
+               
+               // Success, redirect to description page
+               wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
+               $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
 
-                       case UploadFromBase::EMPTY_FILE:
-                               $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
-                               break;
+       }
+       
+       /**
+        * Get the initial image page text based on a comment and optional file status information
+        */
+       public static function getInitialPageText( $comment = '', $license = '', $copyStatus = '', $source = '' ) {
+               global $wgUseCopyrightUpload;
+               if ( $wgUseCopyrightUpload ) {
+                       $licensetxt = '';
+                       if ( $license != '' ) {
+                               $licensetxt = '== ' . wfMsgForContent( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
+                       }
+                       $pageText = '== ' . wfMsgForContent ( 'filedesc' ) . " ==\n" . $comment . "\n" .
+                         '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
+                         "$licensetxt" .
+                         '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
+               } else {
+                       if ( $license != '' ) {
+                               $filedesc = $comment == '' ? '' : '== ' . wfMsgForContent ( 'filedesc' ) . " ==\n" . $comment . "\n";
+                                $pageText = $filedesc .
+                                        '== ' . wfMsgForContent ( 'license-header' ) . " ==\n" . '{{' . $license . '}}' . "\n";
+                       } else {
+                               $pageText = $comment;
+                       }
+               }
+               return $pageText;
+       }
+       
+       /**
+        * See if we should check the 'watch this page' checkbox on the form
+        * based on the user's preferences and whether we're being asked
+        * to create a new file or update an existing one.
+        *
+        * In the case where 'watch edits' is off but 'watch creations' is on,
+        * we'll leave the box unchecked.
+        *
+        * Note that the page target can be changed *on the form*, so our check
+        * state can get out of sync.
+        */
+       protected function watchCheck() {
+               global $wgUser;
+               if( $wgUser->getOption( 'watchdefault' ) ) {
+                       // Watch all edits!
+                       return true;
+               }
 
-                       case UploadFromBase::MIN_LENGHT_PARTNAME:
-                               $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
-                               break;
+               $local = wfLocalFile( $this->mDesiredDestName );
+               if( $local && $local->exists() ) {
+                       // We're uploading a new version of an existing file.
+                       // No creation, so don't watch it if we're not already.
+                       return $local->getTitle()->userIsWatching();
+               } else {
+                       // New page should get watched if that's our option.
+                       return $wgUser->getOption( 'watchcreations' );
+               }
+       }
+       
+       
+       /**
+        * Provides output to the user for a result of UploadBase::verifyUpload
+        * 
+        * @param array $details Result of UploadBase::verifyUpload
+        */
+       protected function processVerificationError( $details ) {
+               global $wgFileExtensions, $wgLang;
+               
+               switch( $details['status'] ) {
 
-                       case UploadFromBase::ILLEGAL_FILENAME:
-                               $this->uploadError( wfMsgExt( 'illegalfilename',
+                       /** Statuses that only require name changing **/
+                       case UploadBase::MIN_LENGTH_PARTNAME:
+                               $this->recoverableUploadError( wfMsgHtml( 'minlength1' ) );
+                               break;
+                       case UploadBase::ILLEGAL_FILENAME:
+                               $this->recoverableUploadError( wfMsgExt( 'illegalfilename',
                                        'parseinline', $details['filtered'] ) );
                                break;
-
-                       case UploadFromBase::PROTECTED_PAGE:
-                               $wgOut->showPermissionsErrorPage( $details['permissionserrors'] );
+                       case UploadBase::OVERWRITE_EXISTING_FILE:
+                               $this->recoverableUploadError( wfMsgExt( $details['overwrite'],
+                                       'parseinline' ) );
                                break;
-
-                       case UploadFromBase::OVERWRITE_EXISTING_FILE:
-                               $this->uploadError( wfMsgExt( $details['overwrite'],
+                       case UploadBase::FILETYPE_MISSING:
+                               $this->recoverableUploadError( wfMsgExt( 'filetype-missing', 
                                        'parseinline' ) );
                                break;
 
-                       case UploadFromBase::FILETYPE_MISSING:
-                               $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
+                       /** Statuses that require reuploading **/
+                       case UploadBase::EMPTY_FILE:
+                               $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
                                break;
-
-                       case UploadFromBase::FILETYPE_BADTYPE:
+                       case UploadBase::FILETYPE_BADTYPE:
                                $finalExt = $details['finalExt'];
                                $this->uploadError(
                                        wfMsgExt( 'filetype-banned-type',
@@ -231,188 +444,105 @@ class UploadForm {
                                        )
                                );
                                break;
-
-                       case UploadFromBase::VERIFICATION_ERROR:
-                               $args = $details['veri'];
-                               $code = array_shift( $args );
-                               $this->uploadError( wfMsgExt( $code, 'parseinline', $args ) );
+                       case UploadBase::VERIFICATION_ERROR:
+                               unset( $details['status'] );
+                               $code = array_shift( $details['details'] );
+                               $this->uploadError( wfMsgExt( $code, 'parseinline', $details['details'] ) );
                                break;
-
-                       case UploadFromBase::UPLOAD_VERIFICATION_ERROR:
+                       case UploadBase::HOOK_ABORTED:
                                $error = $details['error'];
                                $this->uploadError( wfMsgExt( $error, 'parseinline' ) );
                                break;
-
-                       case UploadFromBase::UPLOAD_WARNING:
-                               $warning = $details['warning'];
-                               $this->uploadWarning( $warning );
-                               break;
-
-                       case UploadFromBase::INTERNAL_ERROR:
-                               $status = $details['internal'];
-                               $this->showError( $wgOut->parse( $status->getWikiText() ) );
-                               break;
-
                        default:
-                               throw new MWException( __METHOD__ . ": Unknown value `{$value}`" );
-               }
+                               throw new MWException( __METHOD__ . ": Unknown value `{$details['status']}`" );
+               }
        }
-
+       
        /**
-        * Really do the upload
-        * Checks are made in SpecialUpload::execute()
-        *
-        * @param array $resultDetails contains result-specific dict of additional values
-        *
+        * Remove a temporarily kept file stashed by saveTempUploadedFile().
         * @access private
+        * @return success
         */
-       function internalProcessUpload( &$resultDetails ) {
-               global $wgUser;
-
-               if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
-               {
-                       wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
-                       return UploadFromBase::BEFORE_PROCESSING;
-               }
-
-               $nt = $this->mUpload->getTitle();
-               // Hold back returning errors for a bit so that verifyUpload can fill in the details
-               if ( $nt instanceof Title ) {
-                       /**
-                        * If the image is protected, non-sysop users won't be able
-                        * to modify it by uploading a new revision.
-                        */
-                       $permErrors = $this->mUpload->verifyPermissions( $wgUser );
-                       if( $permErrors !== true ) {
-                               $resultDetails = array( 'permissionserrors' => $permErrors );
-                               return UploadFromBase::PROTECTED_PAGE;
-                       }
-               }
-
-               // Check whether this is a sane upload
-               $result = $this->mUpload->verifyUpload( $resultDetails );
-               if( $result != UploadFromBase::OK )
-                       return $result;
-
-               $this->mLocalFile = $this->mUpload->getLocalFile();
-
-               if( !$this->mIgnoreWarning ) {
-                       $warnings = $this->mUpload->checkWarnings();
-       
-                       if( count( $warnings ) ) {
-                               $resultDetails = array( 'warning' => $warnings );
-                               return UploadFromBase::UPLOAD_WARNING;
-                       }
-               }
-
-
-               /**
-                * Try actually saving the thing...
-                * It will show an error form on failure. No it will not.
-                */
-               $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
-                       $this->mCopyrightStatus, $this->mCopyrightSource );
-
-               $status = $this->mUpload->performUpload( $this->mComment, $pageText, $this->mWatchthis, $wgUser );
-
-               if ( !$status->isGood() ) {
-                       $resultDetails = array( 'internal' => $status );
-                       return UploadFromBase::INTERNAL_ERROR;
+       protected function unsaveUploadedFile() {
+               global $wgOut;
+               if ( !( $this->mUpload instanceof UploadFromStash ) )
+                       return true;
+               $success = $this->mUpload->unsaveUploadedFile();
+               if ( ! $success ) {
+                       $wgOut->showFileDeleteError( $this->mUpload->getTempPath() );
+                       return false;
                } else {
-                       // Success, redirect to description page
-                       // WTF WTF WTF?
-                       $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
-                       wfRunHooks( 'SpecialUploadComplete', array( &$this ) );
-                       return UploadFromBase::SUCCESS;
+                       return true;
                }
        }
-
+       
+       /*** Functions for formatting warnings ***/
+       
        /**
-        * Do existence checks on a file and produce a warning
+        * Formats a result of UploadBase::getExistsWarning as HTML
         * This check is static and can be done pre-upload via AJAX
-        * Returns an HTML fragment consisting of one or more LI elements if there is a warning
-        * Returns an empty string if there is no warning
+        * 
+        * @param array $exists The result of UploadBase::getExistsWarning
+        * @return string Empty string if there is no warning or an HTML fragment 
+        * consisting of one or more <li> elements if there is a warning.
         */
-       static function getExistsWarning( $exists ) {
+       public static function getExistsWarning( $exists ) {
                global $wgUser, $wgContLang;
                
-               if( $exists === false )
+               if ( !$exists )
                        return '';
-               
-               $warning = '';
-               $align = $wgContLang->isRtl() ? 'left' : 'right';
 
-               list( $existsType, $file ) = $exists;
+               $file = $exists['file'];
+               $filename = $file->getTitle()->getPrefixedText();
+               $warning = array();
 
                $sk = $wgUser->getSkin();
 
-               if( $existsType == 'exists' ) {
+               if( $exists['warning'] == 'exists' ) {
                        // Exact match
-                       $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
-                       if ( $file->allowInlineDisplay() ) {
-                               $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
-                                       $file->getName(), $align, array(), false, true );
-                       } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
-                               $icon = $file->iconThumb();
-                               $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
-                                       $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
-                       } else {
-                               $dlink2 = '';
-                       }
-
-                       $warning .= '<li>' . wfMsgExt( 'fileexists', array('parseinline','replaceafter'), $dlink ) . '</li>' . $dlink2;
-
-               } elseif( $existsType == 'page-exists' ) {
-                       $lnk = $sk->makeKnownLinkObj( $file->getTitle(), '', 'redirect=no' );
-                       $warning .= '<li>' . wfMsgExt( 'filepageexists', array( 'parseinline', 'replaceafter' ), $lnk ) . '</li>';
-               } elseif ( $existsType == 'exists-normalized' ) {
-                       # Check if image with lowercase extension exists.
-                       # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
-                       $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
-                       if ( $file->allowInlineDisplay() ) {
-                               $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
-                                       $file->getTitle()->getText(), $align, array(), false, true );
-                       } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
-                               $icon = $file->iconThumb();
-                               $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
-                                       $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
-                       } else {
-                               $dlink2 = '';
-                       }
-
-                       $warning .= '<li>' .
-                               wfMsgExt( 'fileexists-extension', 'parsemag',
-                                       $file->getTitle()->getPrefixedText(), $dlink ) .
-                               '</li>' . $dlink2;
-
-               } elseif ( $existsType == 'thumb' ) {
-                       # Check if an image without leading '180px-' (or similiar) exists
-                       $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
-                       if ( $file->allowInlineDisplay() ) {
-                               $dlink2 = $sk->makeImageLinkObj( $file->getTitle(),
-                                       wfMsgExt( 'fileexists-thumb', 'parseinline' ),
-                                       $file->getTitle()->getText(), $align, array(), false, true );
-                       } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
-                               $icon = $file->iconThumb();
-                               $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
-                                       $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
-                                       $dlink . '</div>';
-                       } else {
-                               $dlink2 = '';
-                       }
-                       $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
-                               '</li>' . $dlink2;
+                       $warning[] = '<li>' . wfMsgExt( 'fileexists', 'parseinline', $filename ) . '</li>';
+               } elseif( $exists['warning'] == 'page-exists' ) {
+                       // Page exists but file does not
+                       $warning[] = '<li>' . wfMsgExt( 'filepageexists', 'parseinline', $filename ) . '</li>';
+               } elseif ( $exists['warning'] == 'exists-normalized' ) {
+                       $warning[] = '<li>' . wfMsgExt( 'fileexists-extension', 'parseinline', $filename, 
+                               $exists['normalizedFile']->getTitle()->getPrefixedText() ) . '</li>';
+               } elseif ( $exists['warning'] == 'thumb' ) {
+                       // Swapped argument order compared with other messages for backwards compatibility
+                       $warning[] = '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parseinline', 
+                               $exists['thumbFile']->getTitle()->getPrefixedText(), $filename ) . '</li>';
+               } elseif ( $exists['warning'] == 'thumb-name' ) {
+                       // Image w/o '180px-' does not exists, but we do not like these filenames
+                       $name = $file->getName();
+                       $badPart = substr( $name, 0, strpos( $name, '-' ) + 1 );
+                       $warning[] = '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline', $badPart ) . '</li>';
+               } elseif ( $exists['warning'] == 'bad-prefix' ) {
+                       $warning[] = '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $exists['prefix'] ) . '</li>';
+               } elseif ( $exists['warning'] == 'was-deleted' ) {
+                       # If the file existed before and was deleted, warn the user of this
+                       $ltitle = SpecialPage::getTitleFor( 'Log' );
+                       $llink = $sk->linkKnown(
+                               $ltitle,
+                               wfMsgHtml( 'deletionlog' ),
+                               array(),
+                               array(
+                                       'type' => 'delete',
+                                       'page' => $filename
+                               )
+                       );
+                       $warning[] = '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
                }
-               return $warning;
+               
+               return implode( "\n", $warning );
        }
-       
+
        /**
         * Get a list of warnings
         *
         * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
         * @return array list of warning messages
         */
-       static function ajaxGetExistsWarning( $filename ) {
+       public static function ajaxGetExistsWarning( $filename ) {
                $file = wfFindFile( $filename );
                if( !$file ) {
                        // Force local file so we have an object to do further checks against
@@ -421,9 +551,8 @@ class UploadForm {
                }
                $s = '&nbsp;';
                if ( $file ) {
-                       $exists = UploadFromBase::getExistsWarning( $file );                    
+                       $exists = UploadBase::getExistsWarning( $file );
                        $warning = self::getExistsWarning( $exists );
-                       // FIXME: We probably also want the prefix blacklist and the wasdeleted check here
                        if ( $warning !== '' ) {
                                $s = "<ul>$warning</ul>";
                        }
@@ -440,7 +569,7 @@ class UploadForm {
        public static function ajaxGetLicensePreview( $license ) {
                global $wgParser, $wgUser;
                $text = '{{' . $license . '}}';
-               $title = Title::makeTitle( NS_IMAGE, 'Sample.jpg' );
+               $title = Title::makeTitle( NS_FILE, 'Sample.jpg' );
                $options = ParserOptions::newFromUser( $wgUser );
 
                // Expand subst: first, then live templates...
@@ -449,10 +578,9 @@ class UploadForm {
 
                return $output->getText();
        }
-       
+
        /**
-        * Check for duplicate files and throw up a warning before the upload
-        * completes.
+        * Construct a warning and a gallery from an array of duplicate files.
         */
        public static function getDupeWarning( $dupes ) {
                if( $dupes ) {
@@ -472,532 +600,335 @@ class UploadForm {
                        return '';
                }
        }
+       
+}
 
-       /**
-        * Remove a temporarily kept file stashed by saveTempUploadedFile().
-        * @access private
-        * @return success
-        */
-       function unsaveUploadedFile() {
-               global $wgOut;
-               $success = $this->mUpload->unsaveUploadedFile();
-               if ( ! $success ) {
-                       $wgOut->showFileDeleteError( $this->mUpload->getTempPath() );
-                       return false;
-               } else {
-                       return true;
+/**
+ * Sub class of HTMLForm that provides the form section of SpecialUpload 
+ */
+class UploadForm extends HTMLForm {
+       protected $mWatch;
+       protected $mForReUpload;
+       protected $mSessionKey;
+       protected $mSourceIds;
+               
+       public function __construct( $watch, $forReUpload = false, $sessionKey = '' ) {
+               global $wgLang;
+               
+               $this->mWatch = $watch;
+               $this->mForReUpload = $forReUpload;
+               $this->mSessionKey = $sessionKey;
+               
+               $sourceDescriptor = $this->getSourceSection(); 
+               $descriptor = $sourceDescriptor
+                       + $this->getDescriptionSection()
+                       + $this->getOptionsSection();
+               
+               wfRunHooks( 'UploadFormInitDescriptor', array( $descriptor ) );
+               parent::__construct( $descriptor, 'upload' );
+               
+               # Set some form properties
+               $this->setSubmitText( wfMsg( 'uploadbtn' ) );
+               $this->setSubmitName( 'wpUpload' );
+               $this->setSubmitTooltip( 'upload' );
+               $this->setId( 'mw-upload-form' );
+               
+               # Build a list of IDs for javascript insertion
+               $this->mSourceIds = array();
+               foreach ( $sourceDescriptor as $key => $field ) {
+                       if ( !empty( $field['id'] ) )
+                               $this->mSourceIds[] = $field['id'];
                }
+               
        }
-
-       /* -------------------------------------------------------------- */
-
-       /**
-        * @param string $error as HTML
-        * @access private
-        */
-       function uploadError( $error ) {
-               global $wgOut;
-               $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
-               $wgOut->addHTML( '<span class="error">' . $error . '</span>' );
-       }
-
+       
        /**
-        * There's something wrong with this file, not enough to reject it
-        * totally but we require manual intervention to save it for real.
-        * Stash it away, then present a form asking to confirm or cancel.
-        *
-        * @param string $warning as HTML
-        * @access private
+        * 
         */
-       function uploadWarning( $warnings ) {
-               global $wgOut;
-               global $wgUseCopyrightUpload;
-
-               $this->mSessionKey = $this->mUpload->stashSession();
-               if( !$this->mSessionKey ) {
-                       # Couldn't save file; an error has been displayed so let's go.
-                       return;
-               }
-
-               $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
-               $wgOut->addHTML( '<ul class="warning">' );
-               foreach( $warnings as $warning => $args ) {
-                               $msg = null;
-                               if( $warning == 'exists' ) {
-                                       if ( !$this->mDestWarningAck )
-                                               $msg = self::getExistsWarning( $args );
-                               } elseif( $warning == 'duplicate' ) {
-                                       $msg = $this->getDupeWarning( $args );
-                               } elseif( $warning == 'filewasdeleted' ) {
-                                       $ltitle = SpecialPage::getTitleFor( 'Log' );
-                                       $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
-                                               'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
-                                       $msg = "\t<li>" . wfMsgWikiHtml( 'filewasdeleted', $llink ) . "</li>\n";
-                               } else {
-                                       if( is_bool( $args ) )
-                                               $args = array();
-                                       elseif( !is_array( $args ) ) 
-                                               $args = array( $args );
-                                       $msg = "\t<li>" . wfMsgExt( $warning, 'parseinline', $args ) . "</li>\n";
-                               }
-                               if( $msg )
-                                       $wgOut->addHTML( $msg );
+       protected function getSourceSection() {
+               global $wgLang, $wgUser, $wgRequest;
+               
+               if ( $this->mSessionKey ) {
+                       return array(
+                               'wpSessionKey' => array(
+                                       'type' => 'hidden',
+                                       'default' => $this->mSessionKey,
+                               ),
+                               'wpSourceType' => array(
+                                       'type' => 'hidden',
+                                       'default' => 'Stash',
+                               ),
+                       );
                }
                
-               $titleObj = SpecialPage::getTitleFor( 'Upload' );
-
-               if ( $wgUseCopyrightUpload ) {
-                       $copyright = Xml::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus ) . "\n" .
-                                       Xml::hidden( 'wpUploadSource', $this->mCopyrightSource ) . "\n";
-               } else {
-                       $copyright = '';
+               $canUploadByUrl = UploadFromUrl::isEnabled() && $wgUser->isAllowed( 'upload_by_url' );
+               $radio = $canUploadByUrl;
+               $selectedSourceType = strtolower( $wgRequest->getText( 'wpSourceType', 'File' ) );
+               
+               $descriptor = array();
+               $descriptor['UploadFile'] = array(
+                               'class' => 'UploadSourceField',
+                               'section' => 'source',
+                               'type' => 'file',
+                               'id' => 'wpUploadFile',
+                               'label-message' => 'sourcefilename',
+                               'upload-type' => 'File',
+                               'radio' => &$radio,
+                               'help' => wfMsgExt( 'upload-maxfilesize', 
+                                               array( 'parseinline', 'escapenoentities' ),
+                                               $wgLang->formatSize( 
+                                                       wfShorthandToInteger( ini_get( 'upload_max_filesize' ) ) 
+                                               )
+                                       ) . ' ' . wfMsgHtml( 'upload_source_file' ),
+                               'checked' => $selectedSourceType == 'file',
+               );
+               if ( $canUploadByUrl ) {
+                       global $wgMaxUploadSize;
+                       $descriptor['UploadFileURL'] = array(
+                               'class' => 'UploadSourceField',
+                               'section' => 'source',
+                               'id' => 'wpUploadFileURL',
+                               'label-message' => 'sourceurl',
+                               'upload-type' => 'Url',
+                               'radio' => &$radio,
+                               'help' => wfMsgExt( 'upload-maxfilesize', 
+                                               array( 'parseinline', 'escapenoentities' ),
+                                               $wgLang->formatSize( $wgMaxUploadSize )
+                                       ) . ' ' . wfMsgHtml( 'upload_source_url' ),
+                               'checked' => $selectedSourceType == 'url',
+                       );
                }
-
-               $wgOut->addHTML(
-                       Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
-                                'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
-                       Xml::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
-                       Xml::hidden( 'wpSessionKey', $this->mSessionKey ) . "\n" .
-                       Xml::hidden( 'wpUploadDescription', $this->mComment ) . "\n" .
-                       Xml::hidden( 'wpLicense', $this->mLicense ) . "\n" .
-                       Xml::hidden( 'wpDestFile', $this->mDesiredDestName ) . "\n" .
-                       Xml::hidden( 'wpWatchthis', $this->mWatchthis ) . "\n" .
-                       "{$copyright}<br />" .
-                       Xml::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
-                       Xml::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
-                       Xml::closeElement( 'form' ) . "\n"
+               wfRunHooks( 'UploadFormSourceDescriptors', array( $descriptor, &$radio, $selectedSourceType ) );
+               
+               $descriptor['Extensions'] = array(
+                       'type' => 'info',
+                       'section' => 'source',
+                       'default' => $this->getExtensionsMessage(),
+                       'raw' => true,
                );
+               return $descriptor;             
        }
-
+       
        /**
-        * Displays the main upload form, optionally with a highlighted
-        * error message up at the top.
-        *
-        * @param string $msg as HTML
-        * @access private
+        * 
         */
-       function mainUploadForm( $msg='' ) {
-               global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
-               global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
-               global $wgRequest, $wgAllowCopyUploads;
-               global $wgStylePath, $wgStyleVersion;
-
-               $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
-               $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
-
-               $adc = wfBoolToStr( $useAjaxDestCheck );
-               $alp = wfBoolToStr( $useAjaxLicensePreview );
-               $autofill = wfBoolToStr( $this->mDesiredDestName == '' );
-
-               $wgOut->addScript( "<script type=\"text/javascript\">
-wgAjaxUploadDestCheck = {$adc};
-wgAjaxLicensePreview = {$alp};
-wgUploadAutoFill = {$autofill};
-</script>" );
-               $wgOut->addScriptFile( 'upload.js' );
-               $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
-
-               if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
-               {
-                       wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
-                       return false;
-               }
-
-               if( $this->mDesiredDestName ) {
-                       $title = Title::makeTitleSafe( NS_IMAGE, $this->mDesiredDestName );
-                       // Show a subtitle link to deleted revisions (to sysops et al only)
-                       if( $title instanceof Title && ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
-                               $link = wfMsgExt(
-                                       $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
-                                       array( 'parse', 'replaceafter' ),
-                                       $wgUser->getSkin()->makeKnownLinkObj(
-                                               SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
-                                               wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
-                                       )
-                               );
-                               $wgOut->addHtml( "<div id=\"contentSub2\">{$link}</div>" );
-                       }
-
-                       // Show the relevant lines from deletion log (for still deleted files only)
-                       if( $title instanceof Title && $title->isDeleted() > 0 && !$title->exists() ) {
-                               $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
-                       }
-               }
-
-               $cols = intval($wgUser->getOption( 'cols' ));
-
-               if( $wgUser->getOption( 'editwidth' ) ) {
-                       $width = " style=\"width:100%\"";
-               } else {
-                       $width = '';
-               }
-
-               if ( '' != $msg ) {
-                       $sub = wfMsgHtml( 'uploaderror' );
-                       $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
-                         "<span class='error'>{$msg}</span>\n" );
-               }
-               $wgOut->addHTML( '<div id="uploadtext">' );
-               $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName );
-               $wgOut->addHTML( "</div>\n" );
-
+       protected function getExtensionsMessage() {
                # Print a list of allowed file extensions, if so configured.  We ignore
                # MIME type here, it's incomprehensible to most people and too long.
-               global $wgCheckFileExtensions, $wgStrictFileExtensions,
+               global $wgLang, $wgCheckFileExtensions, $wgStrictFileExtensions,
                $wgFileExtensions, $wgFileBlacklist;
 
                $allowedExtensions = '';
                if( $wgCheckFileExtensions ) {
-                       $delim = wfMsgExt( 'comma-separator', array( 'escapenoentities' ) );
                        if( $wgStrictFileExtensions ) {
                                # Everything not permitted is banned
                                $extensionsList =
                                        '<div id="mw-upload-permitted">' .
-                                       wfMsgWikiHtml( 'upload-permitted', implode( $wgFileExtensions, $delim ) ) .
+                                       wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
                                        "</div>\n";
                        } else {
                                # We have to list both preferred and prohibited
                                $extensionsList =
                                        '<div id="mw-upload-preferred">' .
-                                       wfMsgWikiHtml( 'upload-preferred', implode( $wgFileExtensions, $delim ) ) .
+                                       wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
                                        "</div>\n" .
                                        '<div id="mw-upload-prohibited">' .
-                                       wfMsgWikiHtml( 'upload-prohibited', implode( $wgFileBlacklist, $delim ) ) .
+                                       wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
                                        "</div>\n";
                        }
                } else {
                        # Everything is permitted.
                        $extensionsList = '';
                }
-
-               # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
-               # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
-               $val = trim( ini_get( 'upload_max_filesize' ) );
-               $last = strtoupper( ( substr( $val, -1 ) ) );
-               switch( $last ) {
-                       case 'G':
-                               $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
-                               break;
-                       case 'M':
-                               $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
-                               break;
-                       case 'K':
-                               $val2 = substr( $val, 0, -1 ) * 1024;
-                               break;
-                       default:
-                               $val2 = $val;
-               }
-               $val2 = $wgAllowCopyUploads ? min( $wgMaxUploadSize, $val2 ) : $val2;
-               $maxUploadSize = '<div id="mw-upload-maxfilesize">' . 
-                       wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ), 
-                               $wgLang->formatSize( $val2 ) ) .
-                               "</div>\n";
-
-               $sourcefilename = wfMsgExt( 'sourcefilename', array( 'parseinline', 'escapenoentities' ) );
-        $destfilename = wfMsgExt( 'destfilename', array( 'parseinline', 'escapenoentities' ) ); 
-               
-               $summary = wfMsgExt( 'fileuploadsummary', 'parseinline' );
-
-               $licenses = new Licenses();
-               $license = wfMsgExt( 'license', array( 'parseinline' ) );
-               $nolicense = wfMsgHtml( 'nolicense' );
-               $licenseshtml = $licenses->getHtml();
-
-               $ulb = wfMsgHtml( 'uploadbtn' );
-
-
-               $titleObj = SpecialPage::getTitleFor( 'Upload' );
-
-               $encDestName = htmlspecialchars( $this->mDesiredDestName );
-
-               $watchChecked = $this->watchCheck()
-                       ? 'checked="checked"'
-                       : '';
-               $warningChecked = $this->mIgnoreWarning ? 'checked' : '';
-
-               // Prepare form for upload or upload/copy
-               if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
-                       $filename_form =
-                               "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
-                                  "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
-                                "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
-                                  "onfocus='" .
-                                    "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
-                                    "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
-                                    "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
-                               wfMsgHTML( 'upload_source_file' ) . "<br/>" .
-                               "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
-                                 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
-                               "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
-                                 "onfocus='" .
-                                   "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
-                                   "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
-                                   "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
-                               wfMsgHtml( 'upload_source_url' ) ;
-               } else {
-                       $filename_form =
-                               "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
-                               ($this->mDesiredDestName?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
-                               "size='60' />" .
-                               "<input type='hidden' name='wpSourceType' value='file' />" ;
-               }
-               if ( $useAjaxDestCheck ) {
-                       $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'>&nbsp;</td></tr>";
-                       $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
-               } else {
-                       $warningRow = '';
-                       $destOnkeyup = '';
+               return $extensionsList;
+       }
+       
+       /**
+        * 
+        */
+       protected function getDescriptionSection() {
+               global $wgUser, $wgOut;
+                               
+               $cols = intval( $wgUser->getOption( 'cols' ) );
+               if( $wgUser->getOption( 'editwidth' ) ) {
+                       $wgOut->addInlineStyle( '#mw-htmlform-description { width: 100%; }' );
                }
-
-               $encComment = htmlspecialchars( $this->mComment );
-
-               $wgOut->addHTML(
-                        Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL(),
-                                'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
-                        Xml::openElement( 'fieldset' ) .
-                        Xml::element( 'legend', null, wfMsg( 'upload' ) ) .
-                        Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
-                        "<tr>
-                               {$this->uploadFormTextTop}
-                               <td class='mw-label'>
-                                       <label for='wpUploadFile'>{$sourcefilename}</label>
-                               </td>
-                               <td class='mw-input'>
-                                       {$filename_form}
-                               </td>
-                       </tr>
-                       <tr>
-                               <td></td>
-                               <td>
-                                       {$maxUploadSize}
-                                       {$extensionsList}
-                               </td>
-                       </tr>
-                       <tr>
-                               <td class='mw-label'>
-                                       <label for='wpDestFile'>{$destfilename}</label>
-                               </td>
-                               <td class='mw-input'>
-                                       <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
-                                               value=\"{$encDestName}\" onchange='toggleFilenameFiller()' $destOnkeyup />
-                               </td>
-                       </tr>
-                       <tr>
-                               <td class='mw-label'>
-                                       <label for='wpUploadDescription'>{$summary}</label>
-                               </td>
-                               <td class='mw-input'>
-                                       <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
-                                               cols='{$cols}'{$width}>$encComment</textarea>
-                                       {$this->uploadFormTextAfterSummary}
-                               </td>
-                       </tr>
-                       <tr>"
+               
+               $descriptor = array(
+                       'DestFile' => array(
+                               'type' => 'text',
+                               'section' => 'description',
+                               'id' => 'wpDestFile',
+                               'label-message' => 'destfilename',
+                               'size' => 60,
+                       ),
+                       'UploadDescription' => array(
+                               'type' => 'textarea',
+                               'section' => 'description',
+                               'id' => 'wpUploadDescription',
+                               'label-message' => $this->mForReUpload
+                                       ? 'filereuploadsummary' 
+                                       : 'fileuploadsummary',
+                               'cols' => $cols,
+                               'rows' => 8,
+                       ),
+                       'License' => array(
+                               'type' => 'select',
+                               'class' => 'Licenses',
+                               'section' => 'description',
+                               'id' => 'wpLicense',
+                               'label-message' => 'license',
+                       ),
                );
-
-               if ( $licenseshtml != '' ) {
-                       global $wgStylePath;
-                       $wgOut->addHTML( "
-                                       <td class='mw-label'>
-                                               <label for='wpLicense'>$license</label>
-                                       </td>
-                                       <td class='mw-input'>
-                                               <select name='wpLicense' id='wpLicense' tabindex='4'
-                                                       onchange='licenseSelectorCheck()'>
-                                                       <option value=''>$nolicense</option>
-                                                       $licenseshtml
-                                               </select>
-                                       </td>
-                               </tr>
-                               <tr>"
+               if ( $this->mForReUpload )
+                       $descriptor['DestFile']['readonly'] = true;
+               
+               global $wgUseAjax, $wgAjaxLicensePreview;
+               if ( $wgUseAjax && $wgAjaxLicensePreview )
+                       $descriptor['AjaxLicensePreview'] = array( 
+                               'class' => 'UploadAjaxLicensePreview', 
+                               'section' => 'description' 
                        );
-                       if( $useAjaxLicensePreview ) {
-                               $wgOut->addHtml( "
-                                               <td></td>
-                                               <td id=\"mw-license-preview\"></td>
-                                       </tr>
-                                       <tr>"
-                               );
-                       }
-               }
-
+                       
+               global $wgUseCopyrightUpload;
                if ( $wgUseCopyrightUpload ) {
-                       $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
-                       $copystatus =  htmlspecialchars( $this->mCopyrightStatus );
-                       $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
-                       $uploadsource = htmlspecialchars( $this->mCopyrightSource );
-
-                       $wgOut->addHTML( "
-                                       <td class='mw-label' style='white-space: nowrap;'>
-                                               <label for='wpUploadCopyStatus'>$filestatus</label></td>
-                                       <td class='mw-input'>
-                                               <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
-                                                       value=\"$copystatus\" size='60' />
-                                       </td>
-                               </tr>
-                               <tr>
-                                       <td class='mw-label'>
-                                               <label for='wpUploadCopyStatus'>$filesource</label>
-                                       </td>
-                                       <td class='mw-input'>
-                                               <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
-                                                       value=\"$uploadsource\" size='60' />
-                                       </td>
-                               </tr>
-                               <tr>"
+                       $descriptor['UploadCopyStatus'] = array(
+                               'type' => 'text',
+                               'section' => 'description',
+                               'id' => 'wpUploadCopyStatus',
+                               'label-message' => 'filestatus',
+                       );
+                       $descriptor['UploadSource'] = array(
+                               'type' => 'text',
+                               'section' => 'description',
+                               'id' => 'wpUploadSource',
+                               'label-message' => 'filesource',
                        );
                }
-
-               $wgOut->addHtml( "
-                               <td></td>
-                               <td>
-                                       <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
-                                       <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
-                                       <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
-                                       <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
-                               </td>
-                       </tr>
-                       $warningRow
-                       <tr>
-                               <td></td>
-                                       <td class='mw-input'>
-                                               <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
-                                       </td>
-                       </tr>
-                       <tr>
-                               <td></td>
-                               <td class='mw-input'>"
-               );
-               $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
-               $wgOut->addHTML( "
-                               </td>
-                       </tr>" .
-                       Xml::closeElement( 'table' ) .
-                       Xml::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
-                       Xml::closeElement( 'fieldset' ) .
-                       Xml::closeElement( 'form' )
-               );
-               $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
-               if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
-                       $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
-               }
+               
+               return $descriptor;
        }
-
-       /* -------------------------------------------------------------- */
        
        /**
-        * See if we should check the 'watch this page' checkbox on the form
-        * based on the user's preferences and whether we're being asked
-        * to create a new file or update an existing one.
-        *
-        * In the case where 'watch edits' is off but 'watch creations' is on,
-        * we'll leave the box unchecked.
-        *
-        * Note that the page target can be changed *on the form*, so our check
-        * state can get out of sync.
-        */
-       function watchCheck() {
-               global $wgUser;
-               if( $wgUser->getOption( 'watchdefault' ) ) {
-                       // Watch all edits!
-                       return true;
-               }
-               
-               $local = wfLocalFile( $this->mDesiredDestName );
-               if( $local && $local->exists() ) {
-                       // We're uploading a new version of an existing file.
-                       // No creation, so don't watch it if we're not already.
-                       return $local->getTitle()->userIsWatching();
-               } else {
-                       // New page should get watched if that's our option.
-                       return $wgUser->getOption( 'watchcreations' );
-               }
-       }
-
-        /**
-        * Check if a user is the last uploader
-        *
-        * @param User $user
-        * @param string $img, image name
-        * @return bool
-        * @deprecated Use UploadFromBase::userCanReUpload
+        * 
         */
-       public static function userCanReUpload( User $user, $img ) {
-               wfDeprecated( __METHOD__ );
+       protected function getOptionsSection() {
+               global $wgOut;
                
-               if( $user->isAllowed( 'reupload' ) )
-                       return true; // non-conditional
-               if( !$user->isAllowed( 'reupload-own' ) )
-                       return false;
-
-               $dbr = wfGetDB( DB_SLAVE );
-               $row = $dbr->selectRow('image',
-               /* SELECT */ 'img_user',
-               /* WHERE */ array( 'img_name' => $img )
+               $descriptor = array(
+                       'Watchthis' => array(
+                               'type' => 'check',
+                               'id' => 'wpWatchthis',
+                               'label-message' => 'watchthisupload',
+                               'section' => 'options',
+                       ),
+                       'IgnoreWarning' => array(
+                               'type' => 'check',
+                               'id' => 'wpIgnoreWarning',
+                               'label-message' => 'ignorewarnings',
+                               'section' => 'options',
+                       ),
+                       'EditTools' => array(
+                               'type' => 'edittools',
+                               'section' => 'options',
+                       ),
                );
-               if ( !$row )
-                       return false;
-
-               return $user->getId() == $row->img_user;
+               
+               $uploadFooter = wfMsgNoTrans( 'uploadfooter' );
+               if ( $uploadFooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadFooter ) )
+                       $descriptor['UploadFooter'] = array(
+                               'type' => 'info',
+                               'id' => 'mw-upload-footer-message',
+                               'default' => $wgOut->parse( $uploadFooter ),
+                       );
+               
+               return $descriptor;
+               
        }
-
+       
        /**
-        * Display an error with a wikitext description
+        * 
         */
-       function showError( $description ) {
-               global $wgOut;
-               $wgOut->setPageTitle( wfMsg( "internalerror" ) );
-               $wgOut->setRobotPolicy( "noindex,nofollow" );
-               $wgOut->setArticleRelated( false );
-               $wgOut->enableClientCache( false );
-               $wgOut->addWikiText( $description );
+       public function show() {
+               $this->addUploadJS();
+               parent::show();
        }
-
+       
        /**
-        * Get the initial image page text based on a comment and optional file status information
+        * 
         */
-       static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
-               global $wgUseCopyrightUpload;
-               if ( $wgUseCopyrightUpload ) {
-                       if ( $license != '' ) {
-                               $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
-                       }
-                       $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
-                         '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
-                         "$licensetxt" .
-                         '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
+       protected function addUploadJS( $autofill = true ) {
+               global $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
+               global $wgEnableFirefogg, $wgEnableJS2system;
+               global $wgOut;
+               
+               $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
+               $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
+               
+               $scriptVars = array(
+                       'wgAjaxUploadDestCheck' => $wgUseAjax && $wgAjaxUploadDestCheck,
+                       'wgAjaxLicensePreview' => $wgUseAjax && $wgAjaxLicensePreview,
+                       'wgEnableFirefogg' => (bool)$wgEnableFirefogg,
+                       'wgUploadAutoFill' => (bool)$autofill,
+                       'wgUploadSourceIds' => $this->mSourceIds,
+               );
+
+               $wgOut->addScript( Skin::makeVariablesScript( $scriptVars ) );
+
+               if ( $wgEnableJS2system ) {
+                       //js2version of upload page:
+                       $wgOut->addScriptClass( 'uploadPage' );
                } else {
-                       if ( $license != '' ) {
-                               $filedesc = $comment == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
-                                $pageText = $filedesc .
-                                        '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
-                       } else {
-                               $pageText = $comment;
-                       }
+                       //legacy upload code:
+                       $wgOut->addScriptFile( 'upload.js' );
+                       $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
                }
-               return $pageText;
+       }
+       
+       function trySubmit() {
+               return false;
        }
 
-       /**
-        * If there are rows in the deletion log for this file, show them,
-        * along with a nice little note for the user
-        *
-        * @param OutputPage $out
-        * @param string filename
-        */
-       private function showDeletionLog( $out, $filename ) {
-               global $wgUser;
-               $loglist = new LogEventsList( $wgUser->getSkin(), $out );
-               $pager = new LogPager( $loglist, 'delete', false, $filename );
-               if( $pager->getNumRows() > 0 ) {
-                       $out->addHtml( '<div id="mw-upload-deleted-warn">' );
-                       $out->addWikiMsg( 'upload-wasdeleted' );
-                       $out->addHTML(
-                               $loglist->beginLogEventsList() .
-                               $pager->getBody() .
-                               $loglist->endLogEventsList()
+}
+
+/**
+ * TODO: DOCUMENT
+ */
+class UploadSourceField extends HTMLTextField {
+       function getLabelHtml() {
+               $id = "wpSourceType{$this->mParams['upload-type']}";            
+               $label = Html::rawElement( 'label', array( 'for' => $id ), $this->mLabel  );
+                               
+               if ( !empty( $this->mParams['radio'] ) ) {
+                       $attribs = array( 
+                               'name' => 'wpSourceType',
+                               'type' => 'radio',
+                               'id' => $id,
+                               'value' => $this->mParams['upload-type'],
                        );
-                       $out->addHtml( '</div>' );
+                       if ( !empty( $this->mParams['checked'] ) )
+                               $attribs['checked'] = 'checked';
+                       $label .= Html::element( 'input', $attribs );
                }
+               
+               return Html::rawElement( 'td', array( 'class' => 'mw-label' ), $label );
+       }
+       function getSize() {
+               return isset( $this->mParams['size'] ) 
+                       ? $this->mParams['size'] 
+                       : 60;
        }
 }
+
+/**
+ * TODO: Document
+ * TODO: This can be migrated to JS only
+ */
+class UploadAjaxLicensePreview extends HTMLFormField {
+       public function getTableRow( $value ) {
+               return "<tr><td></td><td id=\"mw-license-preview\"></td></tr>\n";
+       }
+       public function getInputHTML( $value ) {
+               return '';
+       }
+}
\ No newline at end of file