Return nothing on empty math tags instead of char encoding
[lhc/web/wiklou.git] / includes / SpecialUpload.php
index 7f567f9..d2fd839 100644 (file)
@@ -5,10 +5,7 @@
  * @subpackage SpecialPage
  */
 
-/**
- *
- */
-require_once 'Image.php';
+
 /**
  * Entry point
  */
@@ -31,6 +28,13 @@ class UploadForm {
        var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
        var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
        var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile, $mSourceType;
+       var $mUploadTempFileSize = 0;
+
+       # 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 +51,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 +64,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' );
@@ -82,9 +90,9 @@ class UploadForm {
                         *Check for a newly uploaded file.
                         */
                        if( $wgAllowCopyUploads && $this->mSourceType == 'web' ) {
-                               $this->initialize_web_file( $request );
+                               $this->initializeFromUrl( $request );
                        } else {
-                               $this->initialize_php_file( $request );
+                               $this->initializeFromUpload( $request );
                        }
                }
        }
@@ -93,7 +101,7 @@ class UploadForm {
         * Initialize the uploaded file from PHP data
         * @access private
         */
-       function initialize_php_file( &$request ) {
+       function initializeFromUpload( $request ) {
                $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
                $this->mUploadSize     = $request->getFileSize( 'wpUploadFile' );
                $this->mOname          = $request->getFileName( 'wpUploadFile' );
@@ -107,21 +115,90 @@ class UploadForm {
         * Copy a web file to a temporary file
         * @access private
         */
-       function initialize_web_file( &$request ) {
-               global $wgTmpDirectory, $wgMaxUploadSize;
-               $url = $request->getText( 'wpUploadFile' );
+       function initializeFromUrl( $request ) {
+               global $wgTmpDirectory;
+               $url = $request->getText( 'wpUploadFileURL' );
                $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
 
-               if ( $wgMaxUploadSize < @filesize ( $url ) ) $error = true ;
-               else $error = !@copy( $url, $local_file );
-               
                $this->mUploadTempName = $local_file;
-               $this->mUploadSize     = filesize( $local_file );
+               $this->mUploadError    = $this->curlCopy( $url, $local_file );
+               $this->mUploadSize     = $this->mUploadTempFileSize;
                $this->mOname          = array_pop( explode( '/', $url ) );
-               $this->mUploadError    = $error;
                $this->mSessionKey     = false;
                $this->mStashed        = false;
-               $this->mRemoveTempFile = false; // PHP will *not* handle this
+               
+               // 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 $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;
        }
        
        /**
@@ -139,13 +216,12 @@ class UploadForm {
                }
 
                # Check permissions
-               if( $wgUser->isLoggedIn() ) {
-                       if( !$wgUser->isAllowed( 'upload' ) ) {
+               if( !$wgUser->isAllowed( 'upload' ) ) {
+                       if( !$wgUser->isLoggedIn() ) {
+                               $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
+                       } else {
                                $wgOut->permissionRequired( 'upload' );
-                               return;
                        }
-               } else {
-                       $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
                        return;
                }
 
@@ -190,6 +266,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' ) );
@@ -271,7 +353,7 @@ class UploadForm {
                if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
                        ($wgStrictFileExtensions &&
                                !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
-                       return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
+                       return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $finalExt ) ) );
                }
 
                /**
@@ -314,15 +396,16 @@ class UploadForm {
                        global $wgCheckFileExtensions;
                        if ( $wgCheckFileExtensions ) {
                                if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
-                                       $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
+                                       $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $finalExt ) ).'</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>';
@@ -339,7 +422,7 @@ class UploadForm {
                                $image = new Image( $nt );
                                if( $image->wasDeleted() ) {
                                        $skin = $wgUser->getSkin();
-                                       $ltitle = Title::makeTitle( NS_SPECIAL, 'Log' );
+                                       $ltitle = SpecialPage::getTitleFor( 'Log' );
                                        $llink = $skin->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
                                        $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
                                }
@@ -573,7 +656,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 )
@@ -625,6 +708,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%\"";
@@ -638,8 +727,6 @@ class UploadForm {
                $wgOut->addHTML( '<div id="uploadtext">' );
                $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
                $wgOut->addHTML( '</div>' );
-               $sk = $wgUser->getSkin();
-
 
                $sourcefilename = wfMsgHtml( 'sourcefilename' );
                $destfilename = wfMsgHtml( 'destfilename' );
@@ -653,30 +740,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"'
                        : '';
-               
-               if ( $wgAllowCopyUploads AND $wgRequest->getText('source') == 'web' ) {
-                       $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>
@@ -689,6 +790,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>" );
@@ -733,13 +835,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>
@@ -813,7 +912,7 @@ class UploadForm {
         */
        function verify( $tmpfile, $extension ) {
                #magically determine mime type
-               $magic=& wfGetMimeMagic();
+               $magic=& MimeMagic::singleton();
                $mime= $magic->guessMimeType($tmpfile,false);
 
                $fname= "SpecialUpload::verify";
@@ -862,7 +961,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 ) ) {
@@ -975,13 +1074,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;
@@ -1033,21 +1132,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");
@@ -1061,7 +1164,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)) {
@@ -1152,4 +1255,6 @@ class UploadForm {
        }
 
 }
+       
+
 ?>