5 * @subpackage SpecialPage
11 require_once 'Image.php';
12 require_once 'MacBinary.php';
13 require_once 'Licenses.php';
17 function wfSpecialUpload() {
19 $form = new UploadForm( $wgRequest );
26 * @subpackage SpecialPage
32 var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError;
33 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
34 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
35 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile;
39 * Constructor : initialise object
40 * Get data POSTed through the form and assign them to the object
41 * @param $request Data posted.
43 function UploadForm( &$request ) {
44 $this->mDestFile
= $request->getText( 'wpDestFile' );
46 if( !$request->wasPosted() ) {
47 # GET requests just give the main form; no data except wpDestfile.
51 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning');
52 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
53 $this->mUpload
= $request->getCheck( 'wpUpload' );
55 $this->mUploadDescription
= $request->getText( 'wpUploadDescription' );
56 $this->mLicense
= $request->getText( 'wpLicense' );
57 $this->mUploadCopyStatus
= $request->getText( 'wpUploadCopyStatus' );
58 $this->mUploadSource
= $request->getText( 'wpUploadSource');
60 $this->mAction
= $request->getVal( 'action' );
62 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
63 if( !empty( $this->mSessionKey
) &&
64 isset( $_SESSION['wsUploadData'][$this->mSessionKey
] ) ) {
66 * Confirming a temporarily stashed upload.
67 * We don't want path names to be forged, so we keep
68 * them in the session on the server and just give
69 * an opaque key to the user agent.
71 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
72 $this->mUploadTempName
= $data['mUploadTempName'];
73 $this->mUploadSize
= $data['mUploadSize'];
74 $this->mOname
= $data['mOname'];
75 $this->mUploadError
= 0/*UPLOAD_ERR_OK*/;
76 $this->mStashed
= true;
77 $this->mRemoveTempFile
= false;
80 *Check for a newly uploaded file.
82 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
83 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
84 $this->mOname
= $request->getFileName( 'wpUploadFile' );
85 $this->mUploadError
= $request->getUploadError( 'wpUploadFile' );
86 $this->mSessionKey
= false;
87 $this->mStashed
= false;
88 $this->mRemoveTempFile
= false; // PHP will handle this
97 global $wgUser, $wgOut;
98 global $wgEnableUploads, $wgUploadDirectory;
100 /** Show an error message if file upload is disabled */
101 if( ! $wgEnableUploads ) {
102 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
106 /** Various rights checks */
107 if( !$wgUser->isAllowed( 'upload' ) ||
$wgUser->isBlocked() ) {
108 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
112 $wgOut->readOnlyPage();
116 /** Check if the image directory is writeable, this is a common mistake */
117 if ( !is_writeable( $wgUploadDirectory ) ) {
118 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
122 if( $this->mReUpload
) {
123 $this->unsaveUploadedFile();
124 $this->mainUploadForm();
125 } else if ( 'submit' == $this->mAction ||
$this->mUpload
) {
126 $this->processUpload();
128 $this->mainUploadForm();
131 $this->cleanupTempFile();
134 /* -------------------------------------------------------------- */
137 * Really do the upload
138 * Checks are made in SpecialUpload::execute()
141 function processUpload() {
142 global $wgUser, $wgOut, $wgLang, $wgContLang;
143 global $wgUploadDirectory;
144 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
146 /* Check for PHP error if any, requires php 4.2 or newer */
147 if ( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
148 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
153 * If there was no filename or a zero size given, give up quick.
155 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
156 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
160 # Chop off any directories in the given filename
161 if ( $this->mDestFile
) {
162 $basename = basename( $this->mDestFile
);
164 $basename = basename( $this->mOname
);
168 * We'll want to blacklist against *any* 'extension', and use
169 * only the final one for the whitelist.
171 list( $partname, $ext ) = $this->splitExtensions( $basename );
172 if( count( $ext ) ) {
173 $finalExt = $ext[count( $ext ) - 1];
177 $fullExt = implode( '.', $ext );
179 if ( strlen( $partname ) < 3 ) {
180 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
185 * Filter out illegal characters, and try to make a legible name
186 * out of it. We'll strip some silently that Title would die on.
188 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
189 $nt = Title
::newFromText( $filtered );
190 if( is_null( $nt ) ) {
191 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
194 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
195 $this->mUploadSaveName
= $nt->getDBkey();
198 * If the image is protected, non-sysop users won't be able
199 * to modify it by uploading a new revision.
201 if( !$nt->userCanEdit() ) {
202 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
205 /* Don't allow users to override the blacklist (check file extension) */
206 global $wgStrictFileExtensions;
207 global $wgFileExtensions, $wgFileBlacklist;
208 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
209 ($wgStrictFileExtensions &&
210 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
211 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
215 * Look at the contents of the file; if we can recognize the
216 * type but it's corrupt or data of the wrong type, we should
217 * probably not accept it.
219 if( !$this->mStashed
) {
220 $this->checkMacBinary();
221 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
223 if( $veri !== true ) { //it's a wiki error...
224 return $this->uploadError( $veri->toString() );
229 * Check for non-fatal conditions
231 if ( ! $this->mIgnoreWarning
) {
233 if( $this->mUploadSaveName
!= ucfirst( $filtered ) ) {
234 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
237 global $wgCheckFileExtensions;
238 if ( $wgCheckFileExtensions ) {
239 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
240 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
244 global $wgUploadSizeWarning;
245 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
246 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
247 # value, perhaps add GB,MB and KB suffixes?
248 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
250 if ( $this->mUploadSize
== 0 ) {
251 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
254 if( $nt->getArticleID() ) {
256 $sk = $wgUser->getSkin();
257 $dlink = $sk->makeKnownLinkObj( $nt );
258 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
261 if( $warning != '' ) {
263 * Stash the file in a temporary location; the user can choose
264 * to let it through and we'll complete the upload then.
266 return $this->uploadWarning( $warning );
271 * Try actually saving the thing...
272 * It will show an error form on failure.
274 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
275 if( $this->saveUploadedFile( $this->mUploadSaveName
,
276 $this->mUploadTempName
,
279 * Update the upload log and create the description page
280 * if it's a new file.
282 $img = Image
::newFromName( $this->mUploadSaveName
);
283 $success = $img->recordUpload( $this->mUploadOldVersion
,
284 $this->mUploadDescription
,
286 $this->mUploadCopyStatus
,
287 $this->mUploadSource
);
290 $this->showSuccess();
292 // Image::recordUpload() fails if the image went missing, which is
293 // unlikely, hence the lack of a specialised message
294 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
300 * Move the uploaded file from its temporary location to the final
301 * destination. If a previous version of the file exists, move
302 * it into the archive subdirectory.
304 * @todo If the later save fails, we may have disappeared the original file.
306 * @param string $saveName
307 * @param string $tempName full path to the temporary file
308 * @param bool $useRename if true, doesn't check that the source file
309 * is a PHP-managed upload temporary
311 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
312 global $wgUploadDirectory, $wgOut;
314 $fname= "SpecialUpload::saveUploadedFile";
316 $dest = wfImageDir( $saveName );
317 $archive = wfImageArchiveDir( $saveName );
318 $this->mSavedFile
= "{$dest}/{$saveName}";
320 if( is_file( $this->mSavedFile
) ) {
321 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
322 wfSuppressWarnings();
323 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
327 $wgOut->fileRenameError( $this->mSavedFile
,
328 "${archive}/{$this->mUploadOldVersion}" );
331 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
334 $this->mUploadOldVersion
= '';
337 wfSuppressWarnings();
338 $success = $useRename
339 ?
rename( $tempName, $this->mSavedFile
)
340 : move_uploaded_file( $tempName, $this->mSavedFile
);
344 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
347 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
350 chmod( $this->mSavedFile
, 0644 );
355 * Stash a file in a temporary directory for later processing
356 * after the user has confirmed it.
358 * If the user doesn't explicitly cancel or accept, these files
359 * can accumulate in the temp directory.
361 * @param string $saveName - the destination filename
362 * @param string $tempName - the source temporary file to save
363 * @return string - full path the stashed file, or false on failure
366 function saveTempUploadedFile( $saveName, $tempName ) {
368 $archive = wfImageArchiveDir( $saveName, 'temp' );
369 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
371 $success = $this->mRemoveTempFile
372 ?
rename( $tempName, $stash )
373 : move_uploaded_file( $tempName, $stash );
375 $wgOut->fileCopyError( $tempName, $stash );
383 * Stash a file in a temporary directory for later processing,
384 * and save the necessary descriptive info into the session.
385 * Returns a key value which will be passed through a form
386 * to pick up the path info on a later invocation.
391 function stashSession() {
392 $stash = $this->saveTempUploadedFile(
393 $this->mUploadSaveName
, $this->mUploadTempName
);
396 # Couldn't save the file.
400 $key = mt_rand( 0, 0x7fffffff );
401 $_SESSION['wsUploadData'][$key] = array(
402 'mUploadTempName' => $stash,
403 'mUploadSize' => $this->mUploadSize
,
404 'mOname' => $this->mOname
);
409 * Remove a temporarily kept file stashed by saveTempUploadedFile().
412 function unsaveUploadedFile() {
414 wfSuppressWarnings();
415 $success = unlink( $this->mUploadTempName
);
418 $wgOut->fileDeleteError( $this->mUploadTempName
);
422 /* -------------------------------------------------------------- */
425 * Show some text and linkage on successful upload.
428 function showSuccess() {
429 global $wgUser, $wgOut, $wgContLang;
431 $sk = $wgUser->getSkin();
432 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
433 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
434 $dlink = $sk->makeKnownLink( $dname, $dname );
436 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
437 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
438 $wgOut->addHTML( $text );
439 $wgOut->returnToMain( false );
443 * @param string $error as HTML
446 function uploadError( $error ) {
448 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
449 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
453 * There's something wrong with this file, not enough to reject it
454 * totally but we require manual intervention to save it for real.
455 * Stash it away, then present a form asking to confirm or cancel.
457 * @param string $warning as HTML
460 function uploadWarning( $warning ) {
461 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
462 global $wgUseCopyrightUpload;
464 $this->mSessionKey
= $this->stashSession();
465 if( !$this->mSessionKey
) {
466 # Couldn't save file; an error has been displayed so let's go.
470 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
471 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
473 $save = wfMsgHtml( 'savefile' );
474 $reupload = wfMsgHtml( 'reupload' );
475 $iw = wfMsgWikiHtml( 'ignorewarning' );
476 $reup = wfMsgWikiHtml( 'reuploaddesc' );
477 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
478 $action = $titleObj->escapeLocalURL( 'action=submit' );
480 if ( $wgUseCopyrightUpload )
483 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
484 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
491 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
492 <input type='hidden' name='wpIgnoreWarning' value='1' />
493 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
494 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
495 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
496 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
502 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
504 <td align='left'>$iw</td>
508 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
510 <td align='left'>$reup</td>
513 </table></form>\n" );
517 * Displays the main upload form, optionally with a highlighted
518 * error message up at the top.
520 * @param string $msg as HTML
523 function mainUploadForm( $msg='' ) {
524 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
525 global $wgUseCopyrightUpload;
527 $cols = intval($wgUser->getOption( 'cols' ));
528 $ew = $wgUser->getOption( 'editwidth' );
529 if ( $ew ) $ew = " style=\"width:100%\"";
533 $sub = wfMsgHtml( 'uploaderror' );
534 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
535 "<span class='error'>{$msg}</span>\n" );
537 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
538 $sk = $wgUser->getSkin();
541 $sourcefilename = wfMsgHtml( 'sourcefilename' );
542 $destfilename = wfMsgHtml( 'destfilename' );
543 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
545 $licenses = new Licenses();
546 $license = wfMsgHtml( 'license' );
547 $nolicense = wfMsgHtml( 'nolicense' );
548 $licenseshtml = $licenses->getHtml();
550 $ulb = wfMsgHtml( 'uploadbtn' );
553 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
554 $action = $titleObj->escapeLocalURL();
556 $encDestFile = htmlspecialchars( $this->mDestFile
);
559 if ( $wgUseCopyrightUpload )
562 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
563 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
564 htmlspecialchars($this->mUploadCopyStatus
). "\" size='40' /></td>
566 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
567 <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
568 htmlspecialchars($this->mUploadSource
). "\" size='40' /></td>
573 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
574 <table border='0'><tr>
576 <td align='right'>{$sourcefilename}:</td><td align='left'>
577 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onchange='fillDestFilename()' size='40' />
580 <td align='right'>{$destfilename}:</td><td align='left'>
581 <input tabindex='1' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
584 <td align='right'>{$summary}</td><td align='left'>
585 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
586 . htmlspecialchars( $this->mUploadDescription
) .
590 if ( $licenseshtml != '' ) {
592 <td align='right'>$license:</td>
594 <select name='wpLicense'>
595 <option value=''>$nolicense</option>
601 $wgOut->addHtml( "{$source}
603 <tr><td></td><td align='left'>
604 <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
605 </td></tr></table></form>\n" );
608 /* -------------------------------------------------------------- */
611 * Split a file into a base name and all dot-delimited 'extensions'
612 * on the end. Some web server configurations will fall back to
613 * earlier pseudo-'extensions' to determine type and execute
614 * scripts, so the blacklist needs to check them all.
618 function splitExtensions( $filename ) {
619 $bits = explode( '.', $filename );
620 $basename = array_shift( $bits );
621 return array( $basename, $bits );
625 * Perform case-insensitive match against a list of file extensions.
626 * Returns true if the extension is in the list.
632 function checkFileExtension( $ext, $list ) {
633 return in_array( strtolower( $ext ), $list );
637 * Perform case-insensitive match against a list of file extensions.
638 * Returns true if any of the extensions are in the list.
644 function checkFileExtensionList( $ext, $list ) {
645 foreach( $ext as $e ) {
646 if( in_array( strtolower( $e ), $list ) ) {
654 * Verifies that it's ok to include the uploaded file
656 * @param string $tmpfile the full path of the temporary file to verify
657 * @param string $extension The filename extension that the file is to be served with
658 * @return mixed true of the file is verified, a WikiError object otherwise.
660 function verify( $tmpfile, $extension ) {
661 #magically determine mime type
662 $magic=& wfGetMimeMagic();
663 $mime= $magic->guessMimeType($tmpfile,false);
665 $fname= "SpecialUpload::verify";
667 #check mime type, if desired
668 global $wgVerifyMimeType;
669 if ($wgVerifyMimeType) {
671 #check mime type against file extension
672 if( !$this->verifyExtension( $mime, $extension ) ) {
673 return new WikiErrorMsg( 'uploadcorrupt' );
676 #check mime type blacklist
677 global $wgMimeTypeBlacklist;
678 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
679 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
680 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
684 #check for htmlish code and javascript
685 if( $this->detectScript ( $tmpfile, $mime ) ) {
686 return new WikiErrorMsg( 'uploadscripted' );
690 * Scan the uploaded file for viruses
692 $virus= $this->detectVirus($tmpfile);
694 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
697 wfDebug( "$fname: all clear; passing.\n" );
702 * Checks if the mime type of the uploaded file matches the file extension.
704 * @param string $mime the mime type of the uploaded file
705 * @param string $extension The filename extension that the file is to be served with
708 function verifyExtension( $mime, $extension ) {
709 $fname = 'SpecialUpload::verifyExtension';
711 if (!$mime ||
$mime=="unknown" ||
$mime=="unknown/unknown") {
712 wfDebug( "$fname: passing file with unknown mime type\n" );
716 $magic=& wfGetMimeMagic();
718 $match= $magic->isMatchingExtension($extension,$mime);
721 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
723 } elseif ($match===true) {
724 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
726 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
730 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
735 /** Heuristig for detecting files that *could* contain JavaScript instructions or
736 * things that may look like HTML to a browser and are thus
737 * potentially harmful. The present implementation will produce false positives in some situations.
739 * @param string $file Pathname to the temporary upload file
740 * @param string $mime The mime type of the file
741 * @return bool true if the file contains something looking like embedded scripts
743 function detectScript($file,$mime) {
745 #ugly hack: for text files, always look at the entire file.
746 #For binarie field, just check the first K.
748 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
750 $fp = fopen( $file, 'rb' );
751 $chunk = fread( $fp, 1024 );
755 $chunk= strtolower( $chunk );
757 if (!$chunk) return false;
759 #decode from UTF-16 if needed (could be used for obfuscation).
760 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
761 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
764 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
766 $chunk= trim($chunk);
768 #FIXME: convert from UTF-16 if necessarry!
770 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
772 #check for HTML doctype
773 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
776 * Internet Explorer for Windows performs some really stupid file type
777 * autodetection which can cause it to interpret valid image files as HTML
778 * and potentially execute JavaScript, creating a cross-site scripting
781 * Apple's Safari browser also performs some unsafe file type autodetection
782 * which can cause legitimate files to be interpreted as HTML if the
783 * web server is not correctly configured to send the right content-type
784 * (or if you're really uploading plain text and octet streams!)
786 * Returns true if IE is likely to mistake the given file for HTML.
787 * Also returns true if Safari would mistake the given file for HTML
788 * when served with a generic content-type.
794 '<html', #also in safari
797 '<script', #also in safari
799 '<title' #also in safari
802 foreach( $tags as $tag ) {
803 if( false !== strpos( $chunk, $tag ) ) {
809 * look for javascript
812 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
813 $chunk = Sanitizer
::decodeCharReferences( $chunk );
815 #look for script-types
816 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
818 #look for html-style script-urls
819 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
821 #look for css-style script-urls
822 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
824 wfDebug("SpecialUpload::detectScript: no scripts found\n");
828 /** Generic wrapper function for a virus scanner program.
829 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
830 * $wgAntivirusRequired may be used to deny upload if the scan fails.
832 * @param string $file Pathname to the temporary upload file
833 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
834 * or a string containing feedback from the virus scanner if a virus was found.
835 * If textual feedback is missing but a virus was found, this function returns true.
837 function detectVirus($file) {
838 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
840 $fname= "SpecialUpload::detectVirus";
842 if (!$wgAntivirus) { #disabled?
843 wfDebug("$fname: virus scanner disabled\n");
848 if (!$wgAntivirusSetup[$wgAntivirus]) {
849 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
851 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
853 return "unknown antivirus: $wgAntivirus";
856 #look up scanner configuration
857 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
858 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
859 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
861 $scanner= $virus_scanner; #copy, so we can resolve the pattern
863 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
864 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
866 wfDebug("$fname: running virus scan: $scanner \n");
868 #execute virus scanner
871 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
872 # that does not seem to be worth the pain.
873 # Ask me (Duesentrieb) about it if it's ever needed.
874 if (wfIsWindows()) exec("$scanner",$output,$code);
875 else exec("$scanner 2>&1",$output,$code);
877 $exit_code= $code; #remeber for user feedback
879 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
880 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
881 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
884 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
885 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
887 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
890 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
891 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
894 else if ($code===AV_NO_VIRUS
) {
895 wfDebug("$fname: file passed virus scan.\n");
896 return false; #no virus found
899 $output= join("\n",$output);
900 $output= trim($output);
902 if (!$output) $output= true; #if ther's no output, return true
903 else if ($msg_pattern) {
905 if (preg_match($msg_pattern,$output,$groups)) {
906 if ($groups[1]) $output= $groups[1];
910 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
916 * Check if the temporary file is MacBinary-encoded, as some uploads
917 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
918 * If so, the data fork will be extracted to a second temporary file,
919 * which will then be checked for validity and either kept or discarded.
923 function checkMacBinary() {
924 $macbin = new MacBinary( $this->mUploadTempName
);
925 if( $macbin->isValid() ) {
926 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
927 $dataHandle = fopen( $dataFile, 'wb' );
929 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
930 $macbin->extractData( $dataHandle );
932 $this->mUploadTempName
= $dataFile;
933 $this->mUploadSize
= $macbin->dataForkLength();
935 // We'll have to manually remove the new file if it's not kept.
936 $this->mRemoveTempFile
= true;
942 * If we've modified the upload file we need to manually remove it
943 * on exit to clean up.
946 function cleanupTempFile() {
947 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
948 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
949 unlink( $this->mUploadTempName
);