aaaand one more
[lhc/web/wiklou.git] / includes / SpecialUpload.php
index b6301f1..2ebd3fa 100644 (file)
@@ -1,14 +1,10 @@
 <?php
 /**
  *
- * @package MediaWiki
- * @subpackage SpecialPage
+ * @addtogroup SpecialPage
  */
 
-/**
- *
- */
-require_once 'Image.php';
+
 /**
  * Entry point
  */
@@ -19,9 +15,8 @@ function wfSpecialUpload() {
 }
 
 /**
- *
- * @package MediaWiki
- * @subpackage SpecialPage
+ * implements Special:Upload
+ * @addtogroup SpecialPage
  */
 class UploadForm {
        /**#@+
@@ -31,6 +26,14 @@ class UploadForm {
        var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
        var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
        var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile, $mSourceType;
+       var $mUploadTempFileSize = 0;
+       var $mImage;
+
+       # Placeholders for text injection by hooks (must be HTML)
+       # extensions should take care to _append_ to the present value
+       var $uploadFormTextTop;
+       var $uploadFormTextAfterSummary;
+
        /**#@-*/
 
        /**
@@ -47,6 +50,10 @@ class UploadForm {
                        return;
                }
 
+               # Placeholders for text injection by hooks (empty per default)
+               $this->uploadFormTextTop = "";
+               $this->uploadFormTextAfterSummary = "";
+
                $this->mIgnoreWarning     = $request->getCheck( 'wpIgnoreWarning' );
                $this->mReUpload          = $request->getCheck( 'wpReUpload' );
                $this->mUpload            = $request->getCheck( 'wpUpload' );
@@ -56,7 +63,7 @@ class UploadForm {
                $this->mUploadCopyStatus  = $request->getText( 'wpUploadCopyStatus' );
                $this->mUploadSource      = $request->getText( 'wpUploadSource' );
                $this->mWatchthis         = $request->getBool( 'wpWatchthis' );
-               $this->mSourceType         = $request->getBool( 'wpSourceType' );
+               $this->mSourceType         = $request->getText( 'wpSourceType' );
                wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
 
                $this->mAction            = $request->getVal( 'action' );
@@ -108,8 +115,8 @@ class UploadForm {
         * @access private
         */
        function initializeFromUrl( $request ) {
-               global $wgTmpDirectory, $wgMaxUploadSize;
-               $url = $request->getText( 'wpUploadFile' );
+               global $wgTmpDirectory;
+               $url = $request->getText( 'wpUploadFileURL' );
                $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
 
                $this->mUploadTempName = $local_file;
@@ -118,17 +125,17 @@ class UploadForm {
                $this->mOname          = array_pop( explode( '/', $url ) );
                $this->mSessionKey     = false;
                $this->mStashed        = false;
-               
+
                // PHP won't auto-cleanup the file
                $this->mRemoveTempFile = file_exists( $local_file );
        }
-       
+
        /**
         * Safe copy from URL
         * Returns true if there was an error, false otherwise
         */
        private function curlCopy( $url, $dest ) {
-               global $wgMaxUploadSize, $wgUser;
+               global $wgUser, $wgOut;
 
                if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
                        $wgOut->permissionRequired( 'upload_by_url' );
@@ -136,40 +143,46 @@ class UploadForm {
                }
 
                # Maybe remove some pasting blanks :-)
-               $url = strtolower( trim( $url ) );
-               if( substr( $u, 0, 7 ) != 'http://' && substr( $u, 0, 6 ) != 'ftp://' ) {
+               $url =  trim( $url );
+               if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
                        # Only HTTP or FTP URLs
+                       $wgOut->errorPage( 'upload-proto-error', 'upload-proto-error-text' );
                        return true;
                }
 
                # Open temporary file
-               $this->mUploadTempFileSize = 0;
                $this->mUploadTempFile = @fopen( $this->mUploadTempName, "wb" );
                if( $this->mUploadTempFile === false ) {
                        # Could not open temporary file to write in
+                       $wgOut->errorPage( 'upload-file-error', 'upload-file-error-text');
                        return true;
                }
-               
+
                $ch = curl_init();
                curl_setopt( $ch, CURLOPT_HTTP_VERSION, 1.0); # Probably not needed, but apparently can work around some bug
                curl_setopt( $ch, CURLOPT_TIMEOUT, 10); # 10 seconds timeout
                curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT, 512); # 0.5KB per second minimum transfer speed
-               curl_setopt( $ch, CURLOPT_URL, $url); 
+               curl_setopt( $ch, CURLOPT_URL, $url);
                curl_setopt( $ch, CURLOPT_WRITEFUNCTION, array( $this, 'uploadCurlCallback' ) );
                curl_exec( $ch );
                $error = curl_errno( $ch ) ? true : false;
-#              if ( $error ) print curl_error ( $ch ) ; # Debugging output
+               $errornum =  curl_errno( $ch );
+               // if ( $error ) print curl_error ( $ch ) ; # Debugging output
                curl_close( $ch );
-               
+
                fclose( $this->mUploadTempFile );
                unset( $this->mUploadTempFile );
                if( $error ) {
                        unlink( $dest );
+                       if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
+                               $wgOut->errorPage( 'upload-misc-error', 'upload-misc-error-text' );
+                       else
+                               $wgOut->errorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
                }
-               
+
                return $error;
        }
-       
+
        /**
         * Callback function for CURL-based web transfer
         * Write data to file unless we've passed the length limit;
@@ -186,7 +199,7 @@ class UploadForm {
                fwrite( $this->mUploadTempFile, $data );
                return $length;
        }
-       
+
        /**
         * Start doing stuff
         * @access public
@@ -197,7 +210,7 @@ class UploadForm {
 
                # Check uploading enabled
                if( !$wgEnableUploads ) {
-                       $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
+                       $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDestFile ) );
                        return;
                }
 
@@ -252,6 +265,12 @@ class UploadForm {
        function processUpload() {
                global $wgUser, $wgOut;
 
+               if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
+               {
+                       wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
+                       return false;
+               }
+
                /* Check for PHP error if any, requires php 4.2 or newer */
                if( $this->mUploadError == 1/*UPLOAD_ERR_INI_SIZE*/ ) {
                        $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
@@ -278,13 +297,12 @@ class UploadForm {
                 * only the final one for the whitelist.
                 */
                list( $partname, $ext ) = $this->splitExtensions( $basename );
-               
+
                if( count( $ext ) ) {
                        $finalExt = $ext[count( $ext ) - 1];
                } else {
                        $finalExt = '';
                }
-               $fullExt = implode( '.', $ext );
 
                # If there was more than one "extension", reassemble the base
                # filename to prevent bogus complaints about length
@@ -315,7 +333,7 @@ class UploadForm {
                 * If the image is protected, non-sysop users won't be able
                 * to modify it by uploading a new revision.
                 */
-               if( !$nt->userCanEdit() ) {
+               if( !$nt->userCan( 'edit' ) ) {
                        return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
                }
 
@@ -330,10 +348,12 @@ class UploadForm {
                /* Don't allow users to override the blacklist (check file extension) */
                global $wgStrictFileExtensions;
                global $wgFileExtensions, $wgFileBlacklist;
-               if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
-                       ($wgStrictFileExtensions &&
-                               !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
-                       return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
+               if ($finalExt == '') {
+                       return $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
+               } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
+                               ($wgStrictFileExtensions &&
+                                       !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
+                       return $this->uploadError( wfMsgExt( 'filetype-badtype', array ( 'parseinline' ), htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ) );
                }
 
                /**
@@ -348,17 +368,18 @@ class UploadForm {
                        if( $veri !== true ) { //it's a wiki error...
                                return $this->uploadError( $veri->toString() );
                        }
-               }
 
-               /**
-                * Provide an opportunity for extensions to add futher checks
-                */
-               $error = '';
-               if( !wfRunHooks( 'UploadVerification',
-                               array( $this->mUploadSaveName, $this->mUploadTempName, &$error ) ) ) {
-                       return $this->uploadError( $error );
+                       /**
+                        * Provide an opportunity for extensions to add futher checks
+                        */
+                       $error = '';
+                       if( !wfRunHooks( 'UploadVerification',
+                                       array( $this->mUploadSaveName, $this->mUploadTempName, &$error ) ) ) {
+                               return $this->uploadError( $error );
+                       }
                }
 
+
                /**
                 * Check for non-fatal conditions
                 */
@@ -376,35 +397,88 @@ class UploadForm {
                        global $wgCheckFileExtensions;
                        if ( $wgCheckFileExtensions ) {
                                if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
-                                       $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
+                                       $warning .= '<li>'.wfMsgExt( 'filetype-badtype', array ( 'parseinline' ), htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ).'</li>';
                                }
                        }
 
                        global $wgUploadSizeWarning;
                        if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
-                               # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
-                               # value, perhaps add GB,MB and KB suffixes?
-                               $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize ).'</li>';
+                               $skin = $wgUser->getSkin();
+                               $wsize = $skin->formatSize( $wgUploadSizeWarning );
+                               $asize = $skin->formatSize( $this->mUploadSize );
+                               $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
                        }
                        if ( $this->mUploadSize == 0 ) {
                                $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
                        }
 
-                       if( $nt->getArticleID() ) {
-                               global $wgUser;
-                               $sk = $wgUser->getSkin();
+                       global $wgUser;
+                       $sk = $wgUser->getSkin();
+                       $image = wfLocalFile( $nt );
+
+                       // Check for uppercase extension. We allow these filenames but check if an image
+                       // with lowercase extension exists already
+                       if ( $finalExt != strtolower( $finalExt ) ) {
+                               $nt_lc = Title::newFromText( $partname . '.' . strtolower( $finalExt ) );
+                               $image_lc = wfLocalFile( $nt_lc );
+                       }
+
+                       if( $image->exists() ) {
                                $dlink = $sk->makeKnownLinkObj( $nt );
-                               $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
-                       } else {
+                               if ( $image->allowInlineDisplay() ) {
+                                       $dlink2 = $sk->makeImageLinkObj( $nt, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt->getText(), 'right', array(), false, true );
+                               } elseif ( !$image->allowInlineDisplay() && $image->isSafeFile() ) {
+                                       $icon = $image->iconThumb();
+                                       $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $image->getURL() . '">' . $icon->toHtml() . '</a><br />' . $dlink . '</div>';
+                               } else {
+                                       $dlink2 = '';
+                               }
+
+                               $warning .= '<li>' . wfMsgExt( 'fileexists', 'parseline', $dlink ) . '</li>' . $dlink2;
+
+                       } elseif ( isset( $image_lc) && $image_lc->exists() ) {
+                               # 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( $nt_lc );
+                               if ( $image_lc->allowInlineDisplay() ) {
+                                       $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt_lc->getText(), 'right', array(), false, true );
+                               } elseif ( !$image_lc->allowInlineDisplay() && $image_lc->isSafeFile() ) {
+                                       $icon = $image_lc->iconThumb();
+                                       $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $image_lc->getURL() . '">' . $icon->toHtml() . '</a><br />' . $dlink . '</div>';
+                               } else {
+                                       $dlink2 = '';
+                               }
+
+                               $warning .= '<li>' . wfMsgExt( 'fileexists-extension', 'parsemag' , $partname . '.' . $finalExt , $dlink ) . '</li>' . $dlink2;                         
+
+                       } elseif ( ( substr( $partname , 3, 3 ) == 'px-' || substr( $partname , 2, 3 ) == 'px-' ) && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) ) {
+                               # Check for filenames like 50px- or 180px-, these are mostly thumbnails
+                               $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $finalExt );
+                               $image_thb = wfLocalFile( $nt_thb );
+                               if ($image_thb->exists() ) {
+                                       # Check if an image without leading '180px-' (or similiar) exists
+                                       $dlink = $sk->makeKnownLinkObj( $nt_thb);
+                                       if ( $image_thb->allowInlineDisplay() ) {
+                                               $dlink2 = $sk->makeImageLinkObj( $nt_thb, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt_thb->getText(), 'right', array(), false, true );
+                                       } elseif ( !$image_thb->allowInlineDisplay() && $image_thb->isSafeFile() ) {
+                                               $icon = $image_thb->iconThumb();
+                                               $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $image_thb->getURL() . '">' . $icon->toHtml() . '</a><br />' . $dlink . '</div>';
+                                       } else {
+                                               $dlink2 = '';
+                                       }
+
+                                       $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) . '</li>' . $dlink2;    
+                               } else {
+                                       # Image w/o '180px-' does not exists, but we do not like these filenames
+                                       $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' , substr( $partname , 0, strpos( $partname , '-' ) +1 ) ) . '</li>';
+                               }
+                       }
+                       if ( $image->wasDeleted() ) {
                                # If the file existed before and was deleted, warn the user of this
                                # Don't bother doing so if the image exists now, however
-                               $image = new Image( $nt );
-                               if( $image->wasDeleted() ) {
-                                       $skin = $wgUser->getSkin();
-                                       $ltitle = Title::makeTitle( NS_SPECIAL, 'Log' );
-                                       $llink = $skin->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
-                                       $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
-                               }
+                               $ltitle = SpecialPage::getTitleFor( 'Log' );
+                               $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
+                               $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
                        }
 
                        if( $warning != '' ) {
@@ -428,8 +502,8 @@ class UploadForm {
                         * Update the upload log and create the description page
                         * if it's a new file.
                         */
-                       $img = Image::newFromName( $this->mUploadSaveName );
-                       $success = $img->recordUpload( $this->mUploadOldVersion,
+                       $this->mImage = wfLocalFile( $this->mUploadSaveName );
+                       $success = $this->mImage->recordUpload( $this->mUploadOldVersion,
                                                        $this->mUploadDescription,
                                                        $this->mLicense,
                                                        $this->mUploadCopyStatus,
@@ -440,7 +514,7 @@ class UploadForm {
                                $this->showSuccess();
                                wfRunHooks( 'UploadComplete', array( &$img ) );
                        } else {
-                               // Image::recordUpload() fails if the image went missing, which is
+                               // File::recordUpload() fails if the image went missing, which is
                                // unlikely, hence the lack of a specialised message
                                $wgOut->showFileNotFoundError( $this->mUploadSaveName );
                        }
@@ -461,49 +535,14 @@ class UploadForm {
         */
        function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
                global $wgOut, $wgAllowCopyUploads;
-               
-               if ( !$useRename AND $wgAllowCopyUploads AND $this->mSourceType == 'web' ) $useRename = true;
-
-               $fname= "SpecialUpload::saveUploadedFile";
-
-               $dest = wfImageDir( $saveName );
-               $archive = wfImageArchiveDir( $saveName );
-               if ( !is_dir( $dest ) ) wfMkdirParents( $dest );
-               if ( !is_dir( $archive ) ) wfMkdirParents( $archive );
-               
-               $this->mSavedFile = "{$dest}/{$saveName}";
-
-               if( is_file( $this->mSavedFile ) ) {
-                       $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
-                       wfSuppressWarnings();
-                       $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
-                       wfRestoreWarnings();
-
-                       if( ! $success ) {
-                               $wgOut->showFileRenameError( $this->mSavedFile,
-                                 "${archive}/{$this->mUploadOldVersion}" );
-                               return false;
-                       }
-                       else wfDebug("$fname: moved file ".$this->mSavedFile." to ${archive}/{$this->mUploadOldVersion}\n");
-               }
-               else {
-                       $this->mUploadOldVersion = '';
-               }
-
-               wfSuppressWarnings();
-               $success = $useRename
-                       ? rename( $tempName, $this->mSavedFile )
-                       : move_uploaded_file( $tempName, $this->mSavedFile );
-               wfRestoreWarnings();
 
-               if( ! $success ) {
-                       $wgOut->showFileCopyError( $tempName, $this->mSavedFile );
+               $image = wfLocalFile( $saveName );
+               $archiveName = $image->publish( $tempName, File::DELETE_SOURCE );
+               if ( WikiError::isError( $archiveName ) ) {
+                       $this->showError( $archiveName );
                        return false;
-               } else {
-                       wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
                }
-
-               chmod( $this->mSavedFile, 0644 );
+               $this->mUploadOldVersion = $archiveName;
                return true;
        }
 
@@ -521,19 +560,14 @@ class UploadForm {
         */
        function saveTempUploadedFile( $saveName, $tempName ) {
                global $wgOut;
-               $archive = wfImageArchiveDir( $saveName, 'temp' );
-               if ( !is_dir ( $archive ) ) wfMkdirParents( $archive );
-               $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
-
-               $success = $this->mRemoveTempFile
-                       ? rename( $tempName, $stash )
-                       : move_uploaded_file( $tempName, $stash );
-               if ( !$success ) {
-                       $wgOut->showFileCopyError( $tempName, $stash );
+               $repo = RepoGroup::singleton()->getLocalRepo();
+               $result = $repo->storeTemp( $saveName, $tempName );
+               if ( WikiError::isError( $result ) ) {
+                       $this->showError( $result );
                        return false;
+               } else {
+                       return $result;
                }
-
-               return $stash;
        }
 
        /**
@@ -569,9 +603,8 @@ class UploadForm {
         */
        function unsaveUploadedFile() {
                global $wgOut;
-               wfSuppressWarnings();
-               $success = unlink( $this->mUploadTempName );
-               wfRestoreWarnings();
+               $repo = RepoGroup::singleton()->getLocalRepo();
+               $success = $repo->freeTemp( $this->mUploadTempName );
                if ( ! $success ) {
                        $wgOut->showFileDeleteError( $this->mUploadTempName );
                        return false;
@@ -590,7 +623,7 @@ class UploadForm {
                global $wgUser, $wgOut, $wgContLang;
 
                $sk = $wgUser->getSkin();
-               $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
+               $ilink = $sk->makeMediaLinkObj( $this->mImage->getTitle() );
                $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
                $dlink = $sk->makeKnownLink( $dname, $dname );
 
@@ -635,7 +668,7 @@ class UploadForm {
                $reupload = wfMsgHtml( 'reupload' );
                $iw = wfMsgWikiHtml( 'ignorewarning' );
                $reup = wfMsgWikiHtml( 'reuploaddesc' );
-               $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
+               $titleObj = SpecialPage::getTitleFor( 'Upload' );
                $action = $titleObj->escapeLocalURL( 'action=submit' );
 
                if ( $wgUseCopyrightUpload )
@@ -687,6 +720,12 @@ class UploadForm {
                global $wgUseCopyrightUpload;
                global $wgRequest, $wgAllowCopyUploads;
 
+               if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
+               {
+                       wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
+                       return false;
+               }
+
                $cols = intval($wgUser->getOption( 'cols' ));
                $ew = $wgUser->getOption( 'editwidth' );
                if ( $ew ) $ew = " style=\"width:100%\"";
@@ -698,10 +737,8 @@ class UploadForm {
                          "<span class='error'>{$msg}</span>\n" );
                }
                $wgOut->addHTML( '<div id="uploadtext">' );
-               $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
+               $wgOut->addWikiText( wfMsgNoTrans( 'uploadtext', $this->mDestFile ) );
                $wgOut->addHTML( '</div>' );
-               $sk = $wgUser->getSkin();
-
 
                $sourcefilename = wfMsgHtml( 'sourcefilename' );
                $destfilename = wfMsgHtml( 'destfilename' );
@@ -715,31 +752,44 @@ class UploadForm {
                $ulb = wfMsgHtml( 'uploadbtn' );
 
 
-               $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
+               $titleObj = SpecialPage::getTitleFor( 'Upload' );
                $action = $titleObj->escapeLocalURL();
 
                $encDestFile = htmlspecialchars( $this->mDestFile );
 
-               $watchChecked = $wgUser->getOption( 'watchdefault' )
+               $watchChecked =
+                       ( $wgUser->getOption( 'watchdefault' ) ||
+                               ( $wgUser->getOption( 'watchcreations' ) && $this->mDestFile == '' ) )
                        ? 'checked="checked"'
                        : '';
 
-               // Fixme: this is a crappy form
-               if( $wgAllowCopyUploads && $wgRequest->getVal( 'source' ) == 'web' && $wgUser->isAllowed( 'upload_by_url' ) ) {
-                       $sourcetype = 'text';
-                       $source_comment = '<input type="hidden" name="wpSourceType" value="web" />' . wfMsgHtml( 'upload_source_url' );
+               // 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 />" .
+                               "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onfocus='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
+                               ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
+                               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\")'" .
+                               ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
+                               wfMsgHtml( 'upload_source_url' ) ;
                } else {
-                       $sourcetype = 'file';
-                       $source_comment = '';
+                       $filename_form =
+                               "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
+                               ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
+                               "size='40' />" .
+                               "<input type='hidden' name='wpSourceType' value='file' />" ;
                }
 
                $wgOut->addHTML( "
        <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
                <table border='0'>
                <tr>
-                       <td align='right'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
+         {$this->uploadFormTextTop}
+                       <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
                        <td align='left'>
-                               <input tabindex='1' type='{$sourcetype}' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?"":"onchange='fillDestFilename()' ") . "size='40' />{$source_comment}
+                               {$filename_form}
                        </td>
                </tr>
                <tr>
@@ -752,6 +802,7 @@ class UploadForm {
                        <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
                        <td align='left'>
                                <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription ) . "</textarea>
+          {$this->uploadFormTextAfterSummary}
                        </td>
                </tr>
                <tr>" );
@@ -778,7 +829,7 @@ class UploadForm {
                        $copystatus =  htmlspecialchars( $this->mUploadCopyStatus );
                        $filesource = wfMsgHtml ( 'filesource' );
                        $uploadsource = htmlspecialchars( $this->mUploadSource );
-                       
+
                        $wgOut->addHTML( "
                                <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
                                <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
@@ -796,13 +847,10 @@ class UploadForm {
                <td></td>
                <td>
                        <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
-                       <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
+                       <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
                        <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
                        <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
                </td>
-       </tr>
-       <tr>
-
        </tr>
        <tr>
                <td></td>
@@ -876,7 +924,7 @@ class UploadForm {
         */
        function verify( $tmpfile, $extension ) {
                #magically determine mime type
-               $magic=& wfGetMimeMagic();
+               $magic=& MimeMagic::singleton();
                $mime= $magic->guessMimeType($tmpfile,false);
 
                $fname= "SpecialUpload::verify";
@@ -894,7 +942,7 @@ class UploadForm {
                        global $wgMimeTypeBlacklist;
                        if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
                                && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
-                               return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
+                               return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
                        }
                }
 
@@ -925,7 +973,7 @@ class UploadForm {
        function verifyExtension( $mime, $extension ) {
                $fname = 'SpecialUpload::verifyExtension';
 
-               $magic =& wfGetMimeMagic();
+               $magic =& MimeMagic::singleton();
 
                if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
                        if ( ! $magic->isRecognizableExtension( $extension ) ) {
@@ -1038,13 +1086,13 @@ class UploadForm {
                $chunk = Sanitizer::decodeCharReferences( $chunk );
 
                #look for script-types
-               if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
+               if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
 
                #look for html-style script-urls
-               if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
+               if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
 
                #look for css-style script-urls
-               if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
+               if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
 
                wfDebug("SpecialUpload::detectScript: no scripts found\n");
                return false;
@@ -1096,21 +1144,25 @@ class UploadForm {
                #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
                #      that does not seem to be worth the pain.
                #      Ask me (Duesentrieb) about it if it's ever needed.
+               $output = array();
                if (wfIsWindows()) exec("$scanner",$output,$code);
                else exec("$scanner 2>&1",$output,$code);
 
-               $exit_code= $code; #remeber for user feedback
+               $exit_code= $code; #remember for user feedback
 
                if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
-                       if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
-                       else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
+                       if (isset($virus_scanner_codes[$code])) {
+                               $code= $virus_scanner_codes[$code]; # explicit mapping
+                       } else if (isset($virus_scanner_codes["*"])) {
+                               $code= $virus_scanner_codes["*"];   # fallback mapping
+                       }
                }
 
                if ($code===AV_SCAN_FAILED) { #scan failed (code was mapped to false by $virus_scanner_codes)
                        wfDebug("$fname: failed to scan $file (code $exit_code).\n");
 
-                       if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
-                       else return NULL;
+                       if ($wgAntivirusRequired) { return "scan failed (code $exit_code)"; }
+                       else { return NULL; }
                }
                else if ($code===AV_SCAN_ABORTED) { #scan failed because filetype is unknown (probably imune)
                        wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
@@ -1124,7 +1176,7 @@ class UploadForm {
                        $output= join("\n",$output);
                        $output= trim($output);
 
-                       if (!$output) $output= true; #if ther's no output, return true
+                       if (!$output) $output= true; #if there's no output, return true
                        else if ($msg_pattern) {
                                $groups= array();
                                if (preg_match($msg_pattern,$output,$groups)) {
@@ -1183,18 +1235,13 @@ class UploadForm {
         * @access private
         */
        function checkOverwrite( $name ) {
-               $img = Image::newFromName( $name );
-               if( is_null( $img ) ) {
-                       // Uh... this shouldn't happen ;)
-                       // But if it does, fall through to previous behavior
-                       return false;
-               }
+               $img = wfFindFile( $name );
 
                $error = '';
-               if( $img->exists() ) {
+               if( $img ) {
                        global $wgUser, $wgOut;
                        if( $img->isLocal() ) {
-                               if( !$wgUser->isAllowed( 'reupload' ) ) {
+                               if( !self::userCanReUpload( $wgUser, $img->name ) ) {
                                        $error = 'fileexists-forbidden';
                                }
                        } else {
@@ -1214,7 +1261,40 @@ class UploadForm {
                return true;
        }
 
-}
-       
+        /**
+        * Check if a user is the last uploader
+        *
+        * @param User $user
+        * @param string $img, image name
+        * @return bool
+        */
+       public static function userCanReUpload( User $user, $img ) {
+               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 )
+               );
+               if ( !$row )
+                       return false;
+
+               return $user->getID() == $row->img_user;
+       }
 
+       /**
+        * Display an error from a wikitext-formatted WikiError object
+        */
+       function showError( WikiError $error ) {
+               global $wgOut;
+               $wgOut->setPageTitle( wfMsg( "internalerror" ) );
+               $wgOut->setRobotpolicy( "noindex,nofollow" );
+               $wgOut->setArticleRelated( false );
+               $wgOut->enableClientCache( false );
+               $wgOut->addWikiText( $error->getMessage() );
+       }
+}
 ?>