X-Git-Url: http://git.heureux-cyclage.org/?a=blobdiff_plain;f=includes%2FSpecialUpload.php;h=9f8b63f120ba2177a5e30bd68b8ffbf07575e68d;hb=09da7fb96c45255899fa0f4c62412d14b8575b3e;hp=fc7093fd4c10f8fe2108beca3738f4026b12d546;hpb=d82c14fb4fbac288b42ca5918b0a72f33ecb1e69;p=lhc%2Fweb%2Fwiklou.git diff --git a/includes/SpecialUpload.php b/includes/SpecialUpload.php index fc7093fd4c..9f8b63f120 100644 --- a/includes/SpecialUpload.php +++ b/includes/SpecialUpload.php @@ -1,245 +1,1063 @@ - +execute(); +} + +/** + * + * @package MediaWiki + * @subpackage SpecialPage + */ +class UploadForm { + /**#@+ + * @access private + */ + var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError; + var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion; + var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload; + var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile; + /**#@-*/ + + /** + * Constructor : initialise object + * Get data POSTed through the form and assign them to the object + * @param $request Data posted. + */ + function UploadForm( &$request ) { + $this->mDestFile = $request->getText( 'wpDestFile' ); + + if( !$request->wasPosted() ) { + # GET requests just give the main form; no data except wpDestfile. + return; + } - $fields = array( "wpUploadFile", "wpUploadDescription" ); - wfCleanFormFields( $fields ); + $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning'); + $this->mReUpload = $request->getCheck( 'wpReUpload' ); + $this->mUpload = $request->getCheck( 'wpUpload' ); - if ( 0 == $wgUser->getID() ) { - $wgOut->errorpage( "uploadnologin", "uploadnologintext" ); - return; + $this->mUploadDescription = $request->getText( 'wpUploadDescription' ); + $this->mLicense = $request->getText( 'wpLicense' ); + $this->mUploadCopyStatus = $request->getText( 'wpUploadCopyStatus' ); + $this->mUploadSource = $request->getText( 'wpUploadSource' ); + $this->mWatchthis = $request->getBool( 'wpWatchthis' ); + wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" ); + + $this->mAction = $request->getVal( 'action' ); + + $this->mSessionKey = $request->getInt( 'wpSessionKey' ); + if( !empty( $this->mSessionKey ) && + isset( $_SESSION['wsUploadData'][$this->mSessionKey] ) ) { + /** + * Confirming a temporarily stashed upload. + * We don't want path names to be forged, so we keep + * them in the session on the server and just give + * an opaque key to the user agent. + */ + $data = $_SESSION['wsUploadData'][$this->mSessionKey]; + $this->mUploadTempName = $data['mUploadTempName']; + $this->mUploadSize = $data['mUploadSize']; + $this->mOname = $data['mOname']; + $this->mUploadError = 0/*UPLOAD_ERR_OK*/; + $this->mStashed = true; + $this->mRemoveTempFile = false; + } else { + /** + *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 ( wfReadOnly() ) { - $wgOut->readOnlyPage(); - return; + + /** + * Start doing stuff + * @access public + */ + function execute() { + global $wgUser, $wgOut; + global $wgEnableUploads, $wgUploadDirectory; + + /** Show an error message if file upload is disabled */ + if( ! $wgEnableUploads ) { + $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) ); + return; + } + + /** Various rights checks */ + if( !$wgUser->isAllowed( 'upload' ) || $wgUser->isBlocked() ) { + $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' ); + return; + } + if( wfReadOnly() ) { + $wgOut->readOnlyPage(); + return; + } + + /** Check if the image directory is writeable, this is a common mistake */ + if ( !is_writeable( $wgUploadDirectory ) ) { + $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) ); + return; + } + + if( $this->mReUpload ) { + $this->unsaveUploadedFile(); + $this->mainUploadForm(); + } else if ( 'submit' == $this->mAction || $this->mUpload ) { + $this->processUpload(); + } else { + $this->mainUploadForm(); + } + + $this->cleanupTempFile(); } - if ( isset( $wpReUpload) ) { - unsaveUploadedFile(); - mainUploadForm( "" ); - } else if ( "submit" == $action || isset( $wpUpload ) ) { - processUpload(); - } else { - mainUploadForm( "" ); + + /* -------------------------------------------------------------- */ + + /** + * Really do the upload + * Checks are made in SpecialUpload::execute() + * @access private + */ + function processUpload() { + global $wgUser, $wgOut, $wgUploadDirectory; + + /* Check for PHP error if any, requires php 4.2 or newer */ + if ( $this->mUploadError == 1/*UPLOAD_ERR_INI_SIZE*/ ) { + $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) ); + return; + } + + /** + * If there was no filename or a zero size given, give up quick. + */ + if( trim( $this->mOname ) == '' || empty( $this->mUploadSize ) ) { + $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) ); + return; + } + + # Chop off any directories in the given filename + if ( $this->mDestFile ) { + $basename = basename( $this->mDestFile ); + } else { + $basename = basename( $this->mOname ); + } + + /** + * We'll want to blacklist against *any* 'extension', and use + * 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 ( strlen( $partname ) < 3 ) { + $this->mainUploadForm( wfMsgHtml( 'minlength' ) ); + return; + } + + /** + * Filter out illegal characters, and try to make a legible name + * out of it. We'll strip some silently that Title would die on. + */ + $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename ); + $nt = Title::newFromText( $filtered ); + if( is_null( $nt ) ) { + $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) ); + return; + } + $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() ); + $this->mUploadSaveName = $nt->getDBkey(); + + /** + * If the image is protected, non-sysop users won't be able + * to modify it by uploading a new revision. + */ + if( !$nt->userCanEdit() ) { + 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; + if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) || + ($wgStrictFileExtensions && + !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) { + return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) ); + } + + /** + * Look at the contents of the file; if we can recognize the + * type but it's corrupt or data of the wrong type, we should + * probably not accept it. + */ + if( !$this->mStashed ) { + $this->checkMacBinary(); + $veri = $this->verify( $this->mUploadTempName, $finalExt ); + + 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 ); + } + + /** + * Check for non-fatal conditions + */ + if ( ! $this->mIgnoreWarning ) { + $warning = ''; + + global $wgCapitalLinks; + if( $wgCapitalLinks ) { + $filtered = ucfirst( $filtered ); + } + if( $this->mUploadSaveName != $filtered ) { + $warning .= '
{$text}\n" ); - $wgOut->returnToMain( false ); -} + /* -------------------------------------------------------------- */ -function saveUploadedFile() -{ - global $wpUploadSaveName, $wpUploadTempName; - global $wgSavedFile, $wgUploadOldVersion; - global $wgUploadDirectory, $wgOut; + /** + * Split a file into a base name and all dot-delimited 'extensions' + * on the end. Some web server configurations will fall back to + * earlier pseudo-'extensions' to determine type and execute + * scripts, so the blacklist needs to check them all. + * + * @return array + */ + function splitExtensions( $filename ) { + $bits = explode( '.', $filename ); + $basename = array_shift( $bits ); + return array( $basename, $bits ); + } + + /** + * Perform case-insensitive match against a list of file extensions. + * Returns true if the extension is in the list. + * + * @param string $ext + * @param array $list + * @return bool + */ + function checkFileExtension( $ext, $list ) { + return in_array( strtolower( $ext ), $list ); + } - $dest = wfImageDir( $wpUploadSaveName ); - $archive = wfImageArchiveDir( $wpUploadSaveName ); - $wgSavedFile = "{$dest}/{$wpUploadSaveName}"; + /** + * Perform case-insensitive match against a list of file extensions. + * Returns true if any of the extensions are in the list. + * + * @param array $ext + * @param array $list + * @return bool + */ + function checkFileExtensionList( $ext, $list ) { + foreach( $ext as $e ) { + if( in_array( strtolower( $e ), $list ) ) { + return true; + } + } + return false; + } - if ( is_file( $wgSavedFile ) ) { - $wgUploadOldVersion = date( "YmdHis" ) . "!{$wpUploadSaveName}"; + /** + * Verifies that it's ok to include the uploaded file + * + * @param string $tmpfile the full path of the temporary file to verify + * @param string $extension The filename extension that the file is to be served with + * @return mixed true of the file is verified, a WikiError object otherwise. + */ + function verify( $tmpfile, $extension ) { + #magically determine mime type + $magic=& wfGetMimeMagic(); + $mime= $magic->guessMimeType($tmpfile,false); - if ( ! rename( $wgSavedFile, "${archive}/{$wgUploadOldVersion}" ) ) { - $wgOut->fileRenameError( $wgSavedFile, - "${archive}/{$wgUploadOldVersion}" ); - return; + $fname= "SpecialUpload::verify"; + + #check mime type, if desired + global $wgVerifyMimeType; + if ($wgVerifyMimeType) { + + #check mime type against file extension + if( !$this->verifyExtension( $mime, $extension ) ) { + return new WikiErrorMsg( 'uploadcorrupt' ); + } + + #check mime type blacklist + global $wgMimeTypeBlacklist; + if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist) + && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) { + return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) ); + } } - } else { - $wgUploadOldVersion = ""; + + #check for htmlish code and javascript + if( $this->detectScript ( $tmpfile, $mime ) ) { + return new WikiErrorMsg( 'uploadscripted' ); + } + + /** + * Scan the uploaded file for viruses + */ + $virus= $this->detectVirus($tmpfile); + if ( $virus ) { + return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) ); + } + + wfDebug( "$fname: all clear; passing.\n" ); + return true; } - if ( ! move_uploaded_file( $wpUploadTempName, $wgSavedFile ) ) { - $wgOut->fileCopyError( $wpUploadTempName, $wgSavedFile ); + + /** + * Checks if the mime type of the uploaded file matches the file extension. + * + * @param string $mime the mime type of the uploaded file + * @param string $extension The filename extension that the file is to be served with + * @return bool + */ + function verifyExtension( $mime, $extension ) { + $fname = 'SpecialUpload::verifyExtension'; + + $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); + + if ($match===NULL) { + wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" ); + return true; + } elseif ($match===true) { + wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" ); + + #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it! + return true; + + } else { + wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" ); + return false; + } } - chmod( $wgSavedFile, 0644 ); -} -function unsaveUploadedFile() -{ - global $wgSavedFile, $wgUploadOldVersion; - global $wpSavedFile, $wpUploadOldVersion; - global $wgUploadDirectory, $wgOut; + /** Heuristig for detecting files that *could* contain JavaScript instructions or + * things that may look like HTML to a browser and are thus + * potentially harmful. The present implementation will produce false positives in some situations. + * + * @param string $file Pathname to the temporary upload file + * @param string $mime The mime type of the file + * @return bool true if the file contains something looking like embedded scripts + */ + function detectScript($file,$mime) { + + #ugly hack: for text files, always look at the entire file. + #For binarie field, just check the first K. + + if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file ); + else { + $fp = fopen( $file, 'rb' ); + $chunk = fread( $fp, 1024 ); + fclose( $fp ); + } + + $chunk= strtolower( $chunk ); + + if (!$chunk) return false; + + #decode from UTF-16 if needed (could be used for obfuscation). + if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE"; + elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE"; + else $enc= NULL; + + if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk); + + $chunk= trim($chunk); + + #FIXME: convert from UTF-16 if necessarry! + + wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n"); + + #check for HTML doctype + if (eregi("fileDeleteError( $wgSavedFile ); - return; + foreach( $tags as $tag ) { + if( false !== strpos( $chunk, $tag ) ) { + return true; + } + } + + /* + * look for javascript + */ + + #resolve entity-refs to look at attributes. may be harsh on big files... cache result? + $chunk = Sanitizer::decodeCharReferences( $chunk ); + + #look for script-types + 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; + + #look for css-style script-urls + if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true; + + wfDebug("SpecialUpload::detectScript: no scripts found\n"); + return false; } - if ( "" != $wgUploadOldVersion ) { - $hash = md5( substr( $wgUploadOldVersion, 15 ) ); - $archive = "{$wgUploadDirectory}/archive/" . $hash{0} . - "/" . substr( $hash, 0, 2 ); - if ( ! rename( "{$archive}/{$wgUploadOldVersion}", $wgSavedFile ) ) { - $wgOut->fileRenameError( "{$archive}/{$wgUploadOldVersion}", - $wgSavedFile ); + /** Generic wrapper function for a virus scanner program. + * This relies on the $wgAntivirus and $wgAntivirusSetup variables. + * $wgAntivirusRequired may be used to deny upload if the scan fails. + * + * @param string $file Pathname to the temporary upload file + * @return mixed false if not virus is found, NULL if the scan fails or is disabled, + * or a string containing feedback from the virus scanner if a virus was found. + * If textual feedback is missing but a virus was found, this function returns true. + */ + function detectVirus($file) { + global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired; + + $fname= "SpecialUpload::detectVirus"; + + if (!$wgAntivirus) { #disabled? + wfDebug("$fname: virus scanner disabled\n"); + + return NULL; + } + + if (!$wgAntivirusSetup[$wgAntivirus]) { + wfDebug("$fname: unknown virus scanner: $wgAntivirus\n"); + + $wgOut->addHTML( "
" . wfMsg( "uploadtext" ) ); - $sk = $wgUser->getSkin(); - - $fn = wfMsg( "filename" ); - $fd = wfMsg( "filedesc" ); - $ulb = wfMsg( "uploadbtn" ); - - $clink = $sk->makeKnownLink( wfMsg( "copyrightpage" ), - wfMsg( "copyrightpagename" ) ); - $ca = str_replace( "$1", $clink, wfMsg( "affirmation" ) ); - $iw = wfMsg( "ignorewarning" ); - - $action = wfLocalUrl( $wgLang->specialPage( "Upload" ) ); - $wgOut->addHTML( " -
\n" ); -} + $this->mUploadTempName = $dataFile; + $this->mUploadSize = $macbin->dataForkLength(); + // We'll have to manually remove the new file if it's not kept. + $this->mRemoveTempFile = true; + } + $macbin->close(); + } + + /** + * If we've modified the upload file we need to manually remove it + * on exit to clean up. + * @access private + */ + function cleanupTempFile() { + if( $this->mRemoveTempFile && file_exists( $this->mUploadTempName ) ) { + wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" ); + unlink( $this->mUploadTempName ); + } + } + + /** + * 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; + } + +} ?>