Added placeholders for text injection by hooks to EditPage.php
[lhc/web/wiklou.git] / includes / SpecialUpload.php
index 951b23b..768c14f 100644 (file)
@@ -5,12 +5,7 @@
  * @subpackage SpecialPage
  */
 
-/**
- *
- */
-require_once 'Image.php';
-require_once 'MacBinary.php';
-require_once 'Licenses.php';
+
 /**
  * Entry point
  */
@@ -32,7 +27,8 @@ class UploadForm {
        var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError;
        var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
        var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
-       var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile;
+       var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile, $mSourceType;
+       var $mUploadTempFileSize = 0;
        /**#@-*/
 
        /**
@@ -41,6 +37,7 @@ class UploadForm {
         * @param $request Data posted.
         */
        function UploadForm( &$request ) {
+               global $wgAllowCopyUploads;
                $this->mDestFile          = $request->getText( 'wpDestFile' );
 
                if( !$request->wasPosted() ) {
@@ -48,14 +45,17 @@ class UploadForm {
                        return;
                }
 
-               $this->mIgnoreWarning     = $request->getCheck( 'wpIgnoreWarning');
+               $this->mIgnoreWarning     = $request->getCheck( 'wpIgnoreWarning' );
                $this->mReUpload          = $request->getCheck( 'wpReUpload' );
                $this->mUpload            = $request->getCheck( 'wpUpload' );
 
                $this->mUploadDescription = $request->getText( 'wpUploadDescription' );
                $this->mLicense           = $request->getText( 'wpLicense' );
                $this->mUploadCopyStatus  = $request->getText( 'wpUploadCopyStatus' );
-               $this->mUploadSource      = $request->getText( 'wpUploadSource');
+               $this->mUploadSource      = $request->getText( 'wpUploadSource' );
+               $this->mWatchthis         = $request->getBool( 'wpWatchthis' );
+               $this->mSourceType         = $request->getText( 'wpSourceType' );
+               wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
 
                $this->mAction            = $request->getVal( 'action' );
 
@@ -79,16 +79,118 @@ class UploadForm {
                        /**
                         *Check for a newly uploaded file.
                         */
-                       $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
-                       $this->mUploadSize     = $request->getFileSize( 'wpUploadFile' );
-                       $this->mOname          = $request->getFileName( 'wpUploadFile' );
-                       $this->mUploadError    = $request->getUploadError( 'wpUploadFile' );
-                       $this->mSessionKey     = false;
-                       $this->mStashed        = false;
-                       $this->mRemoveTempFile = false; // PHP will handle this
+                       if( $wgAllowCopyUploads && $this->mSourceType == 'web' ) {
+                               $this->initializeFromUrl( $request );
+                       } else {
+                               $this->initializeFromUpload( $request );
+                       }
                }
        }
 
+       /**
+        * Initialize the uploaded file from PHP data
+        * @access private
+        */
+       function initializeFromUpload( $request ) {
+               $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
+               $this->mUploadSize     = $request->getFileSize( 'wpUploadFile' );
+               $this->mOname          = $request->getFileName( 'wpUploadFile' );
+               $this->mUploadError    = $request->getUploadError( 'wpUploadFile' );
+               $this->mSessionKey     = false;
+               $this->mStashed        = false;
+               $this->mRemoveTempFile = false; // PHP will handle this
+       }
+
+       /**
+        * Copy a web file to a temporary file
+        * @access private
+        */
+       function initializeFromUrl( $request ) {
+               global $wgTmpDirectory, $wgMaxUploadSize;
+               $url = $request->getText( 'wpUploadFileURL' );
+               $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
+
+               $this->mUploadTempName = $local_file;
+               $this->mUploadError    = $this->curlCopy( $url, $local_file );
+               $this->mUploadSize     = $this->mUploadTempFileSize;
+               $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, $wgOut;
+
+               if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
+                       $wgOut->permissionRequired( 'upload_by_url' );
+                       return true;
+               }
+
+               # Maybe remove some pasting blanks :-)
+               $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->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_WRITEFUNCTION, array( $this, 'uploadCurlCallback' ) );
+               curl_exec( $ch );
+               $error = curl_errno( $ch ) ? true : false;
+               $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;
+        * if so, abort immediately.
+        * @access private
+        */
+       function uploadCurlCallback( $ch, $data ) {
+               global $wgMaxUploadSize;
+               $length = strlen( $data );
+               $this->mUploadTempFileSize += $length;
+               if( $this->mUploadTempFileSize > $wgMaxUploadSize ) {
+                       return 0;
+               }
+               fwrite( $this->mUploadTempFile, $data );
+               return $length;
+       }
+       
        /**
         * Start doing stuff
         * @access public
@@ -97,32 +199,45 @@ class UploadForm {
                global $wgUser, $wgOut;
                global $wgEnableUploads, $wgUploadDirectory;
 
-               /** Show an error message if file upload is disabled */
-               if( ! $wgEnableUploads ) {
-                       $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
+               # Check uploading enabled
+               if( !$wgEnableUploads ) {
+                       $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
                        return;
                }
 
-               /** Various rights checks */
-               if( !$wgUser->isAllowed( 'upload' ) || $wgUser->isBlocked() ) {
-                       $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
+               # Check permissions
+               if( !$wgUser->isAllowed( 'upload' ) ) {
+                       if( !$wgUser->isLoggedIn() ) {
+                               $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
+                       } else {
+                               $wgOut->permissionRequired( 'upload' );
+                       }
+                       return;
+               }
+
+               # Check blocks
+               if( $wgUser->isBlocked() ) {
+                       $wgOut->blockedPage();
                        return;
                }
+
                if( wfReadOnly() ) {
                        $wgOut->readOnlyPage();
                        return;
                }
 
                /** Check if the image directory is writeable, this is a common mistake */
-               if ( !is_writeable( $wgUploadDirectory ) ) {
+               if( !is_writeable( $wgUploadDirectory ) ) {
                        $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
                        return;
                }
 
                if( $this->mReUpload ) {
-                       $this->unsaveUploadedFile();
+                       if( !$this->unsaveUploadedFile() ) {
+                               return;
+                       }
                        $this->mainUploadForm();
-               } else if ( 'submit' == $this->mAction || $this->mUpload ) {
+               } else if( 'submit' == $this->mAction || $this->mUpload ) {
                        $this->processUpload();
                } else {
                        $this->mainUploadForm();
@@ -139,12 +254,10 @@ class UploadForm {
         * @access private
         */
        function processUpload() {
-               global $wgUser, $wgOut, $wgLang, $wgContLang;
-               global $wgUploadDirectory;
-               global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
+               global $wgUser, $wgOut;
 
                /* Check for PHP error if any, requires php 4.2 or newer */
-               if ( $this->mUploadError == 1/*UPLOAD_ERR_INI_SIZE*/ ) {
+               if( $this->mUploadError == 1/*UPLOAD_ERR_INI_SIZE*/ ) {
                        $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
                        return;
                }
@@ -158,10 +271,10 @@ class UploadForm {
                }
 
                # Chop off any directories in the given filename
-               if ( $this->mDestFile ) {
-                       $basename = basename( $this->mDestFile );
+               if( $this->mDestFile ) {
+                       $basename = wfBaseName( $this->mDestFile );
                } else {
-                       $basename = basename( $this->mOname );
+                       $basename = wfBaseName( $this->mOname );
                }
 
                /**
@@ -169,6 +282,7 @@ class UploadForm {
                 * only the final one for the whitelist.
                 */
                list( $partname, $ext ) = $this->splitExtensions( $basename );
+               
                if( count( $ext ) ) {
                        $finalExt = $ext[count( $ext ) - 1];
                } else {
@@ -176,7 +290,14 @@ class UploadForm {
                }
                $fullExt = implode( '.', $ext );
 
-               if ( strlen( $partname ) < 3 ) {
+               # If there was more than one "extension", reassemble the base
+               # filename to prevent bogus complaints about length
+               if( count( $ext ) > 1 ) {
+                       for( $i = 0; $i < count( $ext ) - 1; $i++ )
+                               $partname .= '.' . $ext[$i];
+               }
+
+               if( strlen( $partname ) < 3 ) {
                        $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
                        return;
                }
@@ -202,6 +323,14 @@ class UploadForm {
                        return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
                }
 
+               /**
+                * In some cases we may forbid overwriting of existing files.
+                */
+               $overwrite = $this->checkOverwrite( $this->mUploadSaveName );
+               if( WikiError::isError( $overwrite ) ) {
+                       return $this->uploadError( $overwrite->toString() );
+               }
+
                /* Don't allow users to override the blacklist (check file extension) */
                global $wgStrictFileExtensions;
                global $wgFileExtensions, $wgFileBlacklist;
@@ -225,12 +354,26 @@ class UploadForm {
                        }
                }
 
+               /**
+                * 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
                 */
                if ( ! $this->mIgnoreWarning ) {
                        $warning = '';
-                       if( $this->mUploadSaveName != ucfirst( $filtered ) ) {
+
+                       global $wgCapitalLinks;
+                       if( $wgCapitalLinks ) {
+                               $filtered = ucfirst( $filtered );
+                       }
+                       if( $this->mUploadSaveName != $filtered ) {
                                $warning .=  '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
                        }
 
@@ -256,6 +399,16 @@ class UploadForm {
                                $sk = $wgUser->getSkin();
                                $dlink = $sk->makeKnownLinkObj( $nt );
                                $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
+                       } else {
+                               # 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 = SpecialPage::getTitleFor( 'Log' );
+                                       $llink = $skin->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
+                                       $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
+                               }
                        }
 
                        if( $warning != '' ) {
@@ -284,14 +437,16 @@ class UploadForm {
                                                        $this->mUploadDescription,
                                                        $this->mLicense,
                                                        $this->mUploadCopyStatus,
-                                                       $this->mUploadSource );
+                                                       $this->mUploadSource,
+                                                       $this->mWatchthis );
 
                        if ( $success ) {
                                $this->showSuccess();
+                               wfRunHooks( 'UploadComplete', array( &$img ) );
                        } else {
                                // Image::recordUpload() fails if the image went missing, which is
                                // unlikely, hence the lack of a specialised message
-                               $wgOut->fileNotFoundError( $this->mUploadSaveName );
+                               $wgOut->showFileNotFoundError( $this->mUploadSaveName );
                        }
                }
        }
@@ -309,12 +464,17 @@ class UploadForm {
         *                        is a PHP-managed upload temporary
         */
        function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
-               global $wgUploadDirectory, $wgOut;
+               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 ) ) {
@@ -324,7 +484,7 @@ class UploadForm {
                        wfRestoreWarnings();
 
                        if( ! $success ) {
-                               $wgOut->fileRenameError( $this->mSavedFile,
+                               $wgOut->showFileRenameError( $this->mSavedFile,
                                  "${archive}/{$this->mUploadOldVersion}" );
                                return false;
                        }
@@ -341,7 +501,7 @@ class UploadForm {
                wfRestoreWarnings();
 
                if( ! $success ) {
-                       $wgOut->fileCopyError( $tempName, $this->mSavedFile );
+                       $wgOut->showFileCopyError( $tempName, $this->mSavedFile );
                        return false;
                } else {
                        wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
@@ -366,13 +526,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->fileCopyError( $tempName, $stash );
+                       $wgOut->showFileCopyError( $tempName, $stash );
                        return false;
                }
 
@@ -408,6 +569,7 @@ class UploadForm {
        /**
         * Remove a temporarily kept file stashed by saveTempUploadedFile().
         * @access private
+        * @return success
         */
        function unsaveUploadedFile() {
                global $wgOut;
@@ -415,7 +577,10 @@ class UploadForm {
                $success = unlink( $this->mUploadTempName );
                wfRestoreWarnings();
                if ( ! $success ) {
-                       $wgOut->fileDeleteError( $this->mUploadTempName );
+                       $wgOut->showFileDeleteError( $this->mUploadTempName );
+                       return false;
+               } else {
+                       return true;
                }
        }
 
@@ -458,7 +623,7 @@ class UploadForm {
         * @access private
         */
        function uploadWarning( $warning ) {
-               global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
+               global $wgOut;
                global $wgUseCopyrightUpload;
 
                $this->mSessionKey = $this->stashSession();
@@ -474,7 +639,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 )
@@ -494,18 +659,19 @@ class UploadForm {
                <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
                <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense ) . "\" />
                <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile ) . "\" />
+               <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis ) ) . "\" />
        {$copyright}
        <table border='0'>
                <tr>
                        <tr>
                                <td align='right'>
-                                       <input tabindex='2' type='submit' name='wpUpload' value='$save' />
+                                       <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
                                </td>
                                <td align='left'>$iw</td>
                        </tr>
                        <tr>
                                <td align='right'>
-                                       <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
+                                       <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
                                </td>
                                <td align='left'>$reup</td>
                        </tr>
@@ -521,8 +687,9 @@ class UploadForm {
         * @access private
         */
        function mainUploadForm( $msg='' ) {
-               global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
+               global $wgOut, $wgUser;
                global $wgUseCopyrightUpload;
+               global $wgRequest, $wgAllowCopyUploads;
 
                $cols = intval($wgUser->getOption( 'cols' ));
                $ew = $wgUser->getOption( 'editwidth' );
@@ -534,7 +701,9 @@ class UploadForm {
                        $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
                          "<span class='error'>{$msg}</span>\n" );
                }
+               $wgOut->addHTML( '<div id="uploadtext">' );
                $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
+               $wgOut->addHTML( '</div>' );
                $sk = $wgUser->getSkin();
 
 
@@ -546,63 +715,128 @@ class UploadForm {
                $license = wfMsgHtml( 'license' );
                $nolicense = wfMsgHtml( 'nolicense' );
                $licenseshtml = $licenses->getHtml();
-               
+
                $ulb = wfMsgHtml( 'uploadbtn' );
 
 
-               $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
+               $titleObj = SpecialPage::getTitleFor( 'Upload' );
                $action = $titleObj->escapeLocalURL();
 
                $encDestFile = htmlspecialchars( $this->mDestFile );
-               $source = null;
 
-               if ( $wgUseCopyrightUpload )
-                 {
-                       $source = "
-       <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
-       <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
-       htmlspecialchars($this->mUploadCopyStatus). "\" size='40' /></td>
-       </tr><tr>
-       <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
-       <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
-       htmlspecialchars($this->mUploadSource). "\" size='40' /></td>
-       " ;
-                 }
+               $watchChecked =
+                       ( $wgUser->getOption( 'watchdefault' ) ||
+                               ( $wgUser->getOption( 'watchcreations' ) && $this->mDestFile == '' ) )
+                       ? 'checked="checked"'
+                       : '';
+
+               // Prepare form for upload or upload/copy
+               if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
+                       $source_comment = wfMsgHtml( 'upload_source_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 {
+                       $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>
+               <table border='0'>
+               <tr>
+                       <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
+                       <td align='left'>
+                               {$filename_form}
+                       </td>
+               </tr>
+               <tr>
+                       <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
+                       <td align='left'>
+                               <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
+                       </td>
+               </tr>
+               <tr>
+                       <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>
+                       </td>
+               </tr>
+               <tr>" );
+
+               if ( $licenseshtml != '' ) {
+                       global $wgStylePath;
+                       $wgOut->addHTML( "
+                       <td align='right'><label for='wpLicense'>$license:</label></td>
+                       <td align='left'>
+                               <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
+                               <select name='wpLicense' id='wpLicense' tabindex='4'
+                                       onchange='licenseSelectorCheck()'>
+                                       <option value=''>$nolicense</option>
+                                       $licenseshtml
+                               </select>
+                       </td>
+                       </tr>
+                       <tr>
+               ");
+               }
 
-       <td align='right'>{$sourcefilename}:</td><td align='left'>
-       <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?"":"onchange='fillDestFilename()' ") . "size='40' />
-       </td></tr><tr>
+               if ( $wgUseCopyrightUpload ) {
+                       $filestatus = wfMsgHtml ( 'filestatus' );
+                       $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>
+                       </tr>
+                       <tr>
+                               <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
+                               <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
+                       </tr>
+                       <tr>
+               ");
+               }
 
-       <td align='right'>{$destfilename}:</td><td align='left'>
-       <input tabindex='1' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
-       </td></tr><tr>
 
-       <td align='right'>{$summary}</td><td align='left'>
-       <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"        
-         . htmlspecialchars( $this->mUploadDescription ) .
-       "</textarea>
-       </td></tr><tr>" );
-       
-       if ( $licenseshtml != '' ) {
+               $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' />
+                       <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
+               </td>
+       </tr>
+       <tr>
+
+       </tr>
+       <tr>
+               <td></td>
+               <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
+       </tr>
+
+       <tr>
+               <td></td>
+               <td align='left'>
+               " );
+               $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
                $wgOut->addHTML( "
-       <td align='right'>$license:</td>
-       <td align='left'>
-               <select name='wpLicense'>
-                       <option value=''>$nolicense</option>
-                       $licenseshtml
-               </select>
-       </td></tr><tr>
-               ");
-       }
-       $wgOut->addHtml( "{$source}
+               </td>
        </tr>
-       <tr><td></td><td align='left'>
-       <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
-       </td></tr></table></form>\n" );
+
+       </table>
+       </form>" );
        }
 
        /* -------------------------------------------------------------- */
@@ -659,7 +893,7 @@ class UploadForm {
         */
        function verify( $tmpfile, $extension ) {
                #magically determine mime type
-               $magic=& wfGetMimeMagic();
+               $magic=& MimeMagic::singleton();
                $mime= $magic->guessMimeType($tmpfile,false);
 
                $fname= "SpecialUpload::verify";
@@ -682,7 +916,7 @@ class UploadForm {
                }
 
                #check for htmlish code and javascript
-               if( $this->detectScript ( $tmpfile, $mime ) ) {
+               if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
                        return new WikiErrorMsg( 'uploadscripted' );
                }
 
@@ -708,12 +942,16 @@ class UploadForm {
        function verifyExtension( $mime, $extension ) {
                $fname = 'SpecialUpload::verifyExtension';
 
-               if (!$mime || $mime=="unknown" || $mime=="unknown/unknown") {
-                       wfDebug( "$fname: passing file with unknown mime type\n" );
-                       return true;
-               }
+               $magic =& MimeMagic::singleton();
 
-               $magic=& wfGetMimeMagic();
+               if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
+                       if ( ! $magic->isRecognizableExtension( $extension ) ) {
+                               wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
+                               return true;
+                       } else {
+                               wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
+                               return false;
+                       }
 
                $match= $magic->isMatchingExtension($extension,$mime);
 
@@ -738,9 +976,11 @@ class UploadForm {
        *
        * @param string $file Pathname to the temporary upload file
        * @param string $mime The mime type of the file
+       * @param string $extension The extension of the file
        * @return bool true if the file contains something looking like embedded scripts
        */
-       function detectScript($file,$mime) {
+       function detectScript($file, $mime, $extension) {
+               global $wgAllowTitlesInSVG;
 
                #ugly hack: for text files, always look at the entire file.
                #For binarie field, just check the first K.
@@ -795,9 +1035,11 @@ class UploadForm {
                        '<img',
                        '<pre',
                        '<script', #also in safari
-                       '<table',
-                       '<title'   #also in safari
+                       '<table'
                        );
+               if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
+                       $tags[] = '<title';
+               }
 
                foreach( $tags as $tag ) {
                        if( false !== strpos( $chunk, $tag ) ) {
@@ -835,7 +1077,7 @@ class UploadForm {
        *         If textual feedback is missing but a virus was found, this function returns true.
        */
        function detectVirus($file) {
-               global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
+               global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
 
                $fname= "SpecialUpload::detectVirus";
 
@@ -950,5 +1192,46 @@ class UploadForm {
                }
        }
 
+       /**
+        * Check if there's an overwrite conflict and, if so, if restrictions
+        * forbid this user from performing the upload.
+        *
+        * @return mixed true on success, WikiError on failure
+        * @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;
+               }
+
+               $error = '';
+               if( $img->exists() ) {
+                       global $wgUser, $wgOut;
+                       if( $img->isLocal() ) {
+                               if( !$wgUser->isAllowed( 'reupload' ) ) {
+                                       $error = 'fileexists-forbidden';
+                               }
+                       } else {
+                               if( !$wgUser->isAllowed( 'reupload' ) ||
+                                   !$wgUser->isAllowed( 'reupload-shared' ) ) {
+                                       $error = "fileexists-shared-forbidden";
+                               }
+                       }
+               }
+
+               if( $error ) {
+                       $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
+                       return new WikiError( $wgOut->parse( $errorText ) );
+               }
+
+               // Rockin', go ahead and upload
+               return true;
+       }
+
 }
+       
+
 ?>