5 * @subpackage SpecialPage
11 require_once( 'Image.php' );
16 function wfSpecialUpload() {
18 $form = new UploadForm( $wgRequest );
25 * @subpackage SpecialPage
31 var $mUploadAffirm, $mUploadFile, $mUploadDescription, $mIgnoreWarning;
32 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
33 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
34 var $mOname, $mSessionKey, $mStashed, $mDestFile;
38 * Constructor : initialise object
39 * Get data POSTed through the form and assign them to the object
40 * @param $request Data posted.
42 function UploadForm( &$request ) {
43 $this->mDestFile
= $request->getText( 'wpDestFile' );
45 if( !$request->wasPosted() ) {
46 # GET requests just give the main form; no data except wpDestfile.
50 $this->mUploadAffirm
= $request->getCheck( 'wpUploadAffirm' );
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->mUploadCopyStatus
= $request->getText( 'wpUploadCopyStatus' );
57 $this->mUploadSource
= $request->getText( 'wpUploadSource');
59 $this->mAction
= $request->getVal( 'action' );
61 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
62 if( !empty( $this->mSessionKey
) &&
63 isset( $_SESSION['wsUploadData'][$this->mSessionKey
] ) ) {
65 * Confirming a temporarily stashed upload.
66 * We don't want path names to be forged, so we keep
67 * them in the session on the server and just give
68 * an opaque key to the user agent.
70 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
71 $this->mUploadTempName
= $data['mUploadTempName'];
72 $this->mUploadSize
= $data['mUploadSize'];
73 $this->mOname
= $data['mOname'];
74 $this->mStashed
= true;
77 *Check for a newly uploaded file.
79 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
80 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
81 $this->mOname
= $request->getFileName( 'wpUploadFile' );
82 $this->mSessionKey
= false;
83 $this->mStashed
= false;
92 global $wgUser, $wgOut;
93 global $wgEnableUploads, $wgUploadDirectory;
95 /** Show an error message if file upload is disabled */
96 if( ! $wgEnableUploads ) {
97 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
101 /** Various rights checks */
102 if( !$wgUser->isAllowed( 'upload' ) ||
$wgUser->isBlocked() ) {
103 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
107 $wgOut->readOnlyPage();
111 /** Check if the image directory is writeable, this is a common mistake */
112 if ( !is_writeable( $wgUploadDirectory ) ) {
113 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
117 if( $this->mReUpload
) {
118 $this->unsaveUploadedFile();
119 $this->mainUploadForm();
120 } else if ( 'submit' == $this->mAction ||
$this->mUpload
) {
121 $this->processUpload();
123 $this->mainUploadForm();
127 /* -------------------------------------------------------------- */
130 * Really do the upload
131 * Checks are made in SpecialUpload::execute()
134 function processUpload() {
135 global $wgUser, $wgOut, $wgLang, $wgContLang;
136 global $wgUploadDirectory;
137 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
140 * If there was no filename or a zero size given, give up quick.
142 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
143 return $this->mainUploadForm('<li>'.wfMsg( 'emptyfile' ).'</li>');
147 * When using detailed copyright, if user filled field, assume he
148 * confirmed the upload
150 if ( $wgUseCopyrightUpload ) {
151 $this->mUploadAffirm
= true;
152 if( $wgCheckCopyrightUpload &&
153 ( trim( $this->mUploadCopyStatus
) == '' ||
154 trim( $this->mUploadSource
) == '' ) ) {
155 $this->mUploadAffirm
= false;
159 /** User need to confirm his upload */
160 if( !$this->mUploadAffirm
) {
161 $this->mainUploadForm( wfMsg( 'noaffirmation' ) );
165 # Chop off any directories in the given filename
166 if ( $this->mDestFile
) {
167 $basename = basename( $this->mDestFile
);
169 $basename = basename( $this->mOname
);
173 * We'll want to blacklist against *any* 'extension', and use
174 * only the final one for the whitelist.
176 list( $partname, $ext ) = $this->splitExtensions( $basename );
177 if( count( $ext ) ) {
178 $finalExt = $ext[count( $ext ) - 1];
182 $fullExt = implode( '.', $ext );
184 if ( strlen( $partname ) < 3 ) {
185 $this->mainUploadForm( wfMsg( 'minlength' ) );
190 * Filter out illegal characters, and try to make a legible name
191 * out of it. We'll strip some silently that Title would die on.
193 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
194 $nt = Title
::newFromText( $filtered );
195 if( is_null( $nt ) ) {
196 return $this->uploadError( wfMsg( 'illegalfilename', htmlspecialchars( $filtered ) ) );
198 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
199 $this->mUploadSaveName
= $nt->getDBkey();
202 * If the image is protected, non-sysop users won't be able
203 * to modify it by uploading a new revision.
205 if( !$nt->userCanEdit() ) {
206 return $this->uploadError( wfMsg( 'protectedpage' ) );
209 /* Don't allow users to override the blacklist (check file extension) */
210 global $wgStrictFileExtensions;
211 global $wgFileExtensions, $wgFileBlacklist;
212 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
213 ($wgStrictFileExtensions &&
214 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
215 return $this->uploadError( wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ) );
219 * Look at the contents of the file; if we can recognize the
220 * type but it's corrupt or data of the wrong type, we should
221 * probably not accept it.
223 if( !$this->mStashed
) {
224 $veri= $this->verify($this->mUploadTempName
, $finalExt);
226 if( $veri !== true ) { //it's a wiki error...
227 return $this->uploadError( $veri->toString() );
232 * Check for non-fatal conditions
234 if ( ! $this->mIgnoreWarning
) {
236 if( $this->mUploadSaveName
!= ucfirst( $filtered ) ) {
237 $warning .= '<li>'.wfMsg( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
240 global $wgCheckFileExtensions;
241 if ( $wgCheckFileExtensions ) {
242 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
243 $warning .= '<li>'.wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
247 global $wgUploadSizeWarning;
248 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
249 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
250 # value, perhaps add GB,MB and KB suffixes?
251 $warning .= '<li>'.wfMsg( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
253 if ( $this->mUploadSize
== 0 ) {
254 $warning .= '<li>'.wfMsg( 'emptyfile' ).'</li>';
257 if( $nt->getArticleID() ) {
259 $sk = $wgUser->getSkin();
260 $dlink = $sk->makeKnownLinkObj( $nt );
261 $warning .= '<li>'.wfMsg( 'fileexists', $dlink ).'</li>';
264 if( $warning != '' ) {
266 * Stash the file in a temporary location; the user can choose
267 * to let it through and we'll complete the upload then.
269 return $this->uploadWarning($warning);
274 * Try actually saving the thing...
275 * It will show an error form on failure.
277 if( $this->saveUploadedFile( $this->mUploadSaveName
,
278 $this->mUploadTempName
,
279 !empty( $this->mSessionKey
) ) ) {
281 * Update the upload log and create the description page
282 * if it's a new file.
284 $img = Image
::newFromName( $this->mUploadSaveName
);
285 $success = $img->recordUpload( $this->mUploadOldVersion
,
286 $this->mUploadDescription
,
287 $this->mUploadCopyStatus
,
288 $this->mUploadSource
);
291 $this->showSuccess();
293 // Image::recordUpload() fails if the image went missing, which is
294 // unlikely, hence the lack of a specialised message
295 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
301 * Move the uploaded file from its temporary location to the final
302 * destination. If a previous version of the file exists, move
303 * it into the archive subdirectory.
305 * @todo If the later save fails, we may have disappeared the original file.
307 * @param string $saveName
308 * @param string $tempName full path to the temporary file
309 * @param bool $useRename if true, doesn't check that the source file
310 * is a PHP-managed upload temporary
312 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
313 global $wgUploadDirectory, $wgOut;
315 $fname= "SpecialUpload::saveUploadedFile";
317 $dest = wfImageDir( $saveName );
318 $archive = wfImageArchiveDir( $saveName );
319 $this->mSavedFile
= "{$dest}/{$saveName}";
321 if( is_file( $this->mSavedFile
) ) {
322 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
323 wfSuppressWarnings();
324 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
328 $wgOut->fileRenameError( $this->mSavedFile
,
329 "${archive}/{$this->mUploadOldVersion}" );
332 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
335 $this->mUploadOldVersion
= '';
339 wfSuppressWarnings();
340 $success = rename( $tempName, $this->mSavedFile
);
344 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
347 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
350 wfSuppressWarnings();
351 $success = move_uploaded_file( $tempName, $this->mSavedFile
);
355 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
358 else wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
361 chmod( $this->mSavedFile
, 0644 );
366 * Stash a file in a temporary directory for later processing
367 * after the user has confirmed it.
369 * If the user doesn't explicitly cancel or accept, these files
370 * can accumulate in the temp directory.
372 * @param string $saveName - the destination filename
373 * @param string $tempName - the source temporary file to save
374 * @return string - full path the stashed file, or false on failure
377 function saveTempUploadedFile( $saveName, $tempName ) {
379 $archive = wfImageArchiveDir( $saveName, 'temp' );
380 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
382 if ( !move_uploaded_file( $tempName, $stash ) ) {
383 $wgOut->fileCopyError( $tempName, $stash );
391 * Stash a file in a temporary directory for later processing,
392 * and save the necessary descriptive info into the session.
393 * Returns a key value which will be passed through a form
394 * to pick up the path info on a later invocation.
399 function stashSession() {
400 $stash = $this->saveTempUploadedFile(
401 $this->mUploadSaveName
, $this->mUploadTempName
);
404 # Couldn't save the file.
408 $key = mt_rand( 0, 0x7fffffff );
409 $_SESSION['wsUploadData'][$key] = array(
410 'mUploadTempName' => $stash,
411 'mUploadSize' => $this->mUploadSize
,
412 'mOname' => $this->mOname
);
417 * Remove a temporarily kept file stashed by saveTempUploadedFile().
420 function unsaveUploadedFile() {
421 wfSuppressWarnings();
422 $success = unlink( $this->mUploadTempName
);
425 $wgOut->fileDeleteError( $this->mUploadTempName
);
429 /* -------------------------------------------------------------- */
432 * Show some text and linkage on successful upload.
435 function showSuccess() {
436 global $wgUser, $wgOut, $wgContLang;
438 $sk = $wgUser->getSkin();
439 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
440 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
441 $dlink = $sk->makeKnownLink( $dname, $dname );
443 $wgOut->addHTML( '<h2>' . wfMsg( 'successfulupload' ) . "</h2>\n" );
444 $text = wfMsg( 'fileuploaded', $ilink, $dlink );
445 $wgOut->addHTML( '<p>'.$text."\n" );
446 $wgOut->returnToMain( false );
450 * @param string $error as HTML
453 function uploadError( $error ) {
455 $sub = wfMsg( 'uploadwarning' );
456 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
457 $wgOut->addHTML( "<h4 class='error'>{$error}</h4>\n" );
461 * There's something wrong with this file, not enough to reject it
462 * totally but we require manual intervention to save it for real.
463 * Stash it away, then present a form asking to confirm or cancel.
465 * @param string $warning as HTML
468 function uploadWarning( $warning ) {
469 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
470 global $wgUseCopyrightUpload;
472 $this->mSessionKey
= $this->stashSession();
473 if( !$this->mSessionKey
) {
474 # Couldn't save file; an error has been displayed so let's go.
478 $sub = wfMsg( 'uploadwarning' );
479 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
480 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
482 $save = wfMsg( 'savefile' );
483 $reupload = wfMsg( 'reupload' );
484 $iw = wfMsg( 'ignorewarning' );
485 $reup = wfMsg( 'reuploaddesc' );
486 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
487 $action = $titleObj->escapeLocalURL( 'action=submit' );
489 if ( $wgUseCopyrightUpload )
492 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
493 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
500 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
501 <input type='hidden' name='wpUploadAffirm' value='1' />
502 <input type='hidden' name='wpIgnoreWarning' value='1' />
503 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
504 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
505 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
511 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
513 <td align='left'>$iw</td>
517 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
519 <td align='left'>$reup</td>
522 </table></form>\n" );
526 * Displays the main upload form, optionally with a highlighted
527 * error message up at the top.
529 * @param string $msg as HTML
532 function mainUploadForm( $msg='' ) {
533 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
534 global $wgUseCopyrightUpload;
536 $cols = intval($wgUser->getOption( 'cols' ));
537 $ew = $wgUser->getOption( 'editwidth' );
538 if ( $ew ) $ew = " style=\"width:100%\"";
542 $sub = wfMsg( 'uploaderror' );
543 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
544 "<h4 class='error'>{$msg}</h4>\n" );
546 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
547 $sk = $wgUser->getSkin();
550 $sourcefilename = wfMsg( 'sourcefilename' );
551 $destfilename = wfMsg( 'destfilename' );
553 $fd = wfMsg( 'filedesc' );
554 $ulb = wfMsg( 'uploadbtn' );
556 $clink = $sk->makeKnownLink( wfMsgForContent( 'copyrightpage' ),
557 wfMsg( 'copyrightpagename' ) );
558 $ca = wfMsg( 'affirmation', $clink );
559 $iw = wfMsg( 'ignorewarning' );
561 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
562 $action = $titleObj->escapeLocalURL();
564 $encDestFile = htmlspecialchars( $this->mDestFile
);
568 <input tabindex='3' type='checkbox' name='wpUploadAffirm' value='1' id='wpUploadAffirm' />
569 </td><td align='left'><label for='wpUploadAffirm'>{$ca}</label></td>
571 if ( $wgUseCopyrightUpload )
574 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
575 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
576 htmlspecialchars($this->mUploadCopyStatus
). "\" size='40' /></td>
578 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
579 <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
580 htmlspecialchars($this->mUploadSource
). "\" size='40' /></td>
585 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
586 <table border='0'><tr>
588 <td align='right'>{$sourcefilename}:</td><td align='left'>
589 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onchange='fillDestFilename()' size='40' />
592 <td align='right'>{$destfilename}:</td><td align='left'>
593 <input tabindex='1' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
596 <td align='right'>{$fd}:</td><td align='left'>
597 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
598 . htmlspecialchars( $this->mUploadDescription
) .
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 opf 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");