5 * @subpackage SpecialPage
11 require_once( 'Image.php' );
16 function wfSpecialUpload() {
18 $form = new UploadForm( $wgRequest );
25 * @subpackage SpecialPage
31 var $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->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning');
51 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
52 $this->mUpload
= $request->getCheck( 'wpUpload' );
54 $this->mUploadDescription
= $request->getText( 'wpUploadDescription' );
55 $this->mUploadCopyStatus
= $request->getText( 'wpUploadCopyStatus' );
56 $this->mUploadSource
= $request->getText( 'wpUploadSource');
58 $this->mAction
= $request->getVal( 'action' );
60 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
61 if( !empty( $this->mSessionKey
) &&
62 isset( $_SESSION['wsUploadData'][$this->mSessionKey
] ) ) {
64 * Confirming a temporarily stashed upload.
65 * We don't want path names to be forged, so we keep
66 * them in the session on the server and just give
67 * an opaque key to the user agent.
69 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
70 $this->mUploadTempName
= $data['mUploadTempName'];
71 $this->mUploadSize
= $data['mUploadSize'];
72 $this->mOname
= $data['mOname'];
73 $this->mStashed
= true;
76 *Check for a newly uploaded file.
78 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
79 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
80 $this->mOname
= $request->getFileName( 'wpUploadFile' );
81 $this->mSessionKey
= false;
82 $this->mStashed
= false;
91 global $wgUser, $wgOut;
92 global $wgEnableUploads, $wgUploadDirectory;
94 /** Show an error message if file upload is disabled */
95 if( ! $wgEnableUploads ) {
96 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
100 /** Various rights checks */
101 if( !$wgUser->isAllowed( 'upload' ) ||
$wgUser->isBlocked() ) {
102 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
106 $wgOut->readOnlyPage();
110 /** Check if the image directory is writeable, this is a common mistake */
111 if ( !is_writeable( $wgUploadDirectory ) ) {
112 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
116 if( $this->mReUpload
) {
117 $this->unsaveUploadedFile();
118 $this->mainUploadForm();
119 } else if ( 'submit' == $this->mAction ||
$this->mUpload
) {
120 $this->processUpload();
122 $this->mainUploadForm();
126 /* -------------------------------------------------------------- */
129 * Really do the upload
130 * Checks are made in SpecialUpload::execute()
133 function processUpload() {
134 global $wgUser, $wgOut, $wgLang, $wgContLang;
135 global $wgUploadDirectory;
136 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
139 * If there was no filename or a zero size given, give up quick.
141 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
142 return $this->mainUploadForm('<li>'.wfMsg( 'emptyfile' ).'</li>');
145 # Chop off any directories in the given filename
146 if ( $this->mDestFile
) {
147 $basename = basename( $this->mDestFile
);
149 $basename = basename( $this->mOname
);
153 * We'll want to blacklist against *any* 'extension', and use
154 * only the final one for the whitelist.
156 list( $partname, $ext ) = $this->splitExtensions( $basename );
157 if( count( $ext ) ) {
158 $finalExt = $ext[count( $ext ) - 1];
162 $fullExt = implode( '.', $ext );
164 if ( strlen( $partname ) < 3 ) {
165 $this->mainUploadForm( wfMsg( 'minlength' ) );
170 * Filter out illegal characters, and try to make a legible name
171 * out of it. We'll strip some silently that Title would die on.
173 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
174 $nt = Title
::newFromText( $filtered );
175 if( is_null( $nt ) ) {
176 return $this->uploadError( wfMsg( 'illegalfilename', htmlspecialchars( $filtered ) ) );
178 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
179 $this->mUploadSaveName
= $nt->getDBkey();
182 * If the image is protected, non-sysop users won't be able
183 * to modify it by uploading a new revision.
185 if( !$nt->userCanEdit() ) {
186 return $this->uploadError( wfMsg( 'protectedpage' ) );
189 /* Don't allow users to override the blacklist (check file extension) */
190 global $wgStrictFileExtensions;
191 global $wgFileExtensions, $wgFileBlacklist;
192 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
193 ($wgStrictFileExtensions &&
194 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
195 return $this->uploadError( wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ) );
199 * Look at the contents of the file; if we can recognize the
200 * type but it's corrupt or data of the wrong type, we should
201 * probably not accept it.
203 if( !$this->mStashed
) {
204 $veri= $this->verify($this->mUploadTempName
, $finalExt);
206 if( $veri !== true ) { //it's a wiki error...
207 return $this->uploadError( $veri->toString() );
212 * Check for non-fatal conditions
214 if ( ! $this->mIgnoreWarning
) {
216 if( $this->mUploadSaveName
!= ucfirst( $filtered ) ) {
217 $warning .= '<li>'.wfMsg( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
220 global $wgCheckFileExtensions;
221 if ( $wgCheckFileExtensions ) {
222 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
223 $warning .= '<li>'.wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
227 global $wgUploadSizeWarning;
228 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
229 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
230 # value, perhaps add GB,MB and KB suffixes?
231 $warning .= '<li>'.wfMsg( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
233 if ( $this->mUploadSize
== 0 ) {
234 $warning .= '<li>'.wfMsg( 'emptyfile' ).'</li>';
237 if( $nt->getArticleID() ) {
239 $sk = $wgUser->getSkin();
240 $dlink = $sk->makeKnownLinkObj( $nt );
241 $warning .= '<li>'.wfMsg( 'fileexists', $dlink ).'</li>';
244 if( $warning != '' ) {
246 * Stash the file in a temporary location; the user can choose
247 * to let it through and we'll complete the upload then.
249 return $this->uploadWarning($warning);
254 * Try actually saving the thing...
255 * It will show an error form on failure.
257 if( $this->saveUploadedFile( $this->mUploadSaveName
,
258 $this->mUploadTempName
,
259 !empty( $this->mSessionKey
) ) ) {
261 * Update the upload log and create the description page
262 * if it's a new file.
264 $img = Image
::newFromName( $this->mUploadSaveName
);
265 $success = $img->recordUpload( $this->mUploadOldVersion
,
266 $this->mUploadDescription
,
267 $this->mUploadCopyStatus
,
268 $this->mUploadSource
);
271 $this->showSuccess();
273 // Image::recordUpload() fails if the image went missing, which is
274 // unlikely, hence the lack of a specialised message
275 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
281 * Move the uploaded file from its temporary location to the final
282 * destination. If a previous version of the file exists, move
283 * it into the archive subdirectory.
285 * @todo If the later save fails, we may have disappeared the original file.
287 * @param string $saveName
288 * @param string $tempName full path to the temporary file
289 * @param bool $useRename if true, doesn't check that the source file
290 * is a PHP-managed upload temporary
292 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
293 global $wgUploadDirectory, $wgOut;
295 $fname= "SpecialUpload::saveUploadedFile";
297 $dest = wfImageDir( $saveName );
298 $archive = wfImageArchiveDir( $saveName );
299 $this->mSavedFile
= "{$dest}/{$saveName}";
301 if( is_file( $this->mSavedFile
) ) {
302 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
303 wfSuppressWarnings();
304 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
308 $wgOut->fileRenameError( $this->mSavedFile
,
309 "${archive}/{$this->mUploadOldVersion}" );
312 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
315 $this->mUploadOldVersion
= '';
319 wfSuppressWarnings();
320 $success = rename( $tempName, $this->mSavedFile
);
324 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
327 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
330 wfSuppressWarnings();
331 $success = move_uploaded_file( $tempName, $this->mSavedFile
);
335 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
338 else wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
341 chmod( $this->mSavedFile
, 0644 );
346 * Stash a file in a temporary directory for later processing
347 * after the user has confirmed it.
349 * If the user doesn't explicitly cancel or accept, these files
350 * can accumulate in the temp directory.
352 * @param string $saveName - the destination filename
353 * @param string $tempName - the source temporary file to save
354 * @return string - full path the stashed file, or false on failure
357 function saveTempUploadedFile( $saveName, $tempName ) {
359 $archive = wfImageArchiveDir( $saveName, 'temp' );
360 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
362 if ( !move_uploaded_file( $tempName, $stash ) ) {
363 $wgOut->fileCopyError( $tempName, $stash );
371 * Stash a file in a temporary directory for later processing,
372 * and save the necessary descriptive info into the session.
373 * Returns a key value which will be passed through a form
374 * to pick up the path info on a later invocation.
379 function stashSession() {
380 $stash = $this->saveTempUploadedFile(
381 $this->mUploadSaveName
, $this->mUploadTempName
);
384 # Couldn't save the file.
388 $key = mt_rand( 0, 0x7fffffff );
389 $_SESSION['wsUploadData'][$key] = array(
390 'mUploadTempName' => $stash,
391 'mUploadSize' => $this->mUploadSize
,
392 'mOname' => $this->mOname
);
397 * Remove a temporarily kept file stashed by saveTempUploadedFile().
400 function unsaveUploadedFile() {
401 wfSuppressWarnings();
402 $success = unlink( $this->mUploadTempName
);
405 $wgOut->fileDeleteError( $this->mUploadTempName
);
409 /* -------------------------------------------------------------- */
412 * Show some text and linkage on successful upload.
415 function showSuccess() {
416 global $wgUser, $wgOut, $wgContLang;
418 $sk = $wgUser->getSkin();
419 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
420 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
421 $dlink = $sk->makeKnownLink( $dname, $dname );
423 $wgOut->addHTML( '<h2>' . wfMsg( 'successfulupload' ) . "</h2>\n" );
424 $text = wfMsg( 'fileuploaded', $ilink, $dlink );
425 $wgOut->addHTML( $text );
426 $wgOut->returnToMain( false );
430 * @param string $error as HTML
433 function uploadError( $error ) {
435 $sub = wfMsg( 'uploadwarning' );
436 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
437 $wgOut->addHTML( "<h4 class='error'>{$error}</h4>\n" );
441 * There's something wrong with this file, not enough to reject it
442 * totally but we require manual intervention to save it for real.
443 * Stash it away, then present a form asking to confirm or cancel.
445 * @param string $warning as HTML
448 function uploadWarning( $warning ) {
449 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
450 global $wgUseCopyrightUpload;
452 $this->mSessionKey
= $this->stashSession();
453 if( !$this->mSessionKey
) {
454 # Couldn't save file; an error has been displayed so let's go.
458 $sub = wfMsg( 'uploadwarning' );
459 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
460 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
462 $save = wfMsg( 'savefile' );
463 $reupload = wfMsg( 'reupload' );
464 $iw = wfMsg( 'ignorewarning' );
465 $reup = wfMsg( 'reuploaddesc' );
466 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
467 $action = $titleObj->escapeLocalURL( 'action=submit' );
469 if ( $wgUseCopyrightUpload )
472 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
473 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
480 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
481 <input type='hidden' name='wpIgnoreWarning' value='1' />
482 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
483 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
484 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
490 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
492 <td align='left'>$iw</td>
496 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
498 <td align='left'>$reup</td>
501 </table></form>\n" );
505 * Displays the main upload form, optionally with a highlighted
506 * error message up at the top.
508 * @param string $msg as HTML
511 function mainUploadForm( $msg='' ) {
512 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
513 global $wgUseCopyrightUpload;
515 $cols = intval($wgUser->getOption( 'cols' ));
516 $ew = $wgUser->getOption( 'editwidth' );
517 if ( $ew ) $ew = " style=\"width:100%\"";
521 $sub = wfMsg( 'uploaderror' );
522 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
523 "<h4 class='error'>{$msg}</h4>\n" );
525 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
526 $sk = $wgUser->getSkin();
529 $sourcefilename = wfMsg( 'sourcefilename' );
530 $destfilename = wfMsg( 'destfilename' );
532 $fd = wfMsg( 'filedesc' );
533 $ulb = wfMsg( 'uploadbtn' );
535 $iw = wfMsg( 'ignorewarning' );
537 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
538 $action = $titleObj->escapeLocalURL();
540 $encDestFile = htmlspecialchars( $this->mDestFile
);
543 if ( $wgUseCopyrightUpload )
546 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
547 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
548 htmlspecialchars($this->mUploadCopyStatus
). "\" size='40' /></td>
550 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
551 <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
552 htmlspecialchars($this->mUploadSource
). "\" size='40' /></td>
557 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
558 <table border='0'><tr>
560 <td align='right'>{$sourcefilename}:</td><td align='left'>
561 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onchange='fillDestFilename()' size='40' />
564 <td align='right'>{$destfilename}:</td><td align='left'>
565 <input tabindex='1' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
568 <td align='right'>{$fd}:</td><td align='left'>
569 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
570 . htmlspecialchars( $this->mUploadDescription
) .
575 <tr><td></td><td align='left'>
576 <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
577 </td></tr></table></form>\n" );
580 /* -------------------------------------------------------------- */
583 * Split a file into a base name and all dot-delimited 'extensions'
584 * on the end. Some web server configurations will fall back to
585 * earlier pseudo-'extensions' to determine type and execute
586 * scripts, so the blacklist needs to check them all.
590 function splitExtensions( $filename ) {
591 $bits = explode( '.', $filename );
592 $basename = array_shift( $bits );
593 return array( $basename, $bits );
597 * Perform case-insensitive match against a list of file extensions.
598 * Returns true if the extension is in the list.
604 function checkFileExtension( $ext, $list ) {
605 return in_array( strtolower( $ext ), $list );
609 * Perform case-insensitive match against a list of file extensions.
610 * Returns true if any of the extensions are in the list.
616 function checkFileExtensionList( $ext, $list ) {
617 foreach( $ext as $e ) {
618 if( in_array( strtolower( $e ), $list ) ) {
626 * Verifies that it's ok to include the uploaded file
628 * @param string $tmpfile the full path opf the temporary file to verify
629 * @param string $extension The filename extension that the file is to be served with
630 * @return mixed true of the file is verified, a WikiError object otherwise.
632 function verify( $tmpfile, $extension ) {
633 #magically determine mime type
634 $magic=& wfGetMimeMagic();
635 $mime= $magic->guessMimeType($tmpfile,false);
637 $fname= "SpecialUpload::verify";
639 #check mime type, if desired
640 global $wgVerifyMimeType;
641 if ($wgVerifyMimeType) {
643 #check mime type against file extension
644 if( !$this->verifyExtension( $mime, $extension ) ) {
645 return new WikiErrorMsg( 'uploadcorrupt' );
648 #check mime type blacklist
649 global $wgMimeTypeBlacklist;
650 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
651 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
652 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
656 #check for htmlish code and javascript
657 if( $this->detectScript ( $tmpfile, $mime ) ) {
658 return new WikiErrorMsg( 'uploadscripted' );
662 * Scan the uploaded file for viruses
664 $virus= $this->detectVirus($tmpfile);
666 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
669 wfDebug( "$fname: all clear; passing.\n" );
674 * Checks if the mime type of the uploaded file matches the file extension.
676 * @param string $mime the mime type of the uploaded file
677 * @param string $extension The filename extension that the file is to be served with
680 function verifyExtension( $mime, $extension ) {
681 $fname = 'SpecialUpload::verifyExtension';
683 if (!$mime ||
$mime=="unknown" ||
$mime=="unknown/unknown") {
684 wfDebug( "$fname: passing file with unknown mime type\n" );
688 $magic=& wfGetMimeMagic();
690 $match= $magic->isMatchingExtension($extension,$mime);
693 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
695 } elseif ($match===true) {
696 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
698 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
702 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
707 /** Heuristig for detecting files that *could* contain JavaScript instructions or
708 * things that may look like HTML to a browser and are thus
709 * potentially harmful. The present implementation will produce false positives in some situations.
711 * @param string $file Pathname to the temporary upload file
712 * @param string $mime The mime type of the file
713 * @return bool true if the file contains something looking like embedded scripts
715 function detectScript($file,$mime) {
717 #ugly hack: for text files, always look at the entire file.
718 #For binarie field, just check the first K.
720 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
722 $fp = fopen( $file, 'rb' );
723 $chunk = fread( $fp, 1024 );
727 $chunk= strtolower( $chunk );
729 if (!$chunk) return false;
731 #decode from UTF-16 if needed (could be used for obfuscation).
732 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
733 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
736 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
738 $chunk= trim($chunk);
740 #FIXME: convert from UTF-16 if necessarry!
742 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
744 #check for HTML doctype
745 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
748 * Internet Explorer for Windows performs some really stupid file type
749 * autodetection which can cause it to interpret valid image files as HTML
750 * and potentially execute JavaScript, creating a cross-site scripting
753 * Apple's Safari browser also performs some unsafe file type autodetection
754 * which can cause legitimate files to be interpreted as HTML if the
755 * web server is not correctly configured to send the right content-type
756 * (or if you're really uploading plain text and octet streams!)
758 * Returns true if IE is likely to mistake the given file for HTML.
759 * Also returns true if Safari would mistake the given file for HTML
760 * when served with a generic content-type.
766 '<html', #also in safari
769 '<script', #also in safari
771 '<title' #also in safari
774 foreach( $tags as $tag ) {
775 if( false !== strpos( $chunk, $tag ) ) {
781 * look for javascript
784 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
785 $chunk = Sanitizer
::decodeCharReferences( $chunk );
787 #look for script-types
788 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
790 #look for html-style script-urls
791 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
793 #look for css-style script-urls
794 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
796 wfDebug("SpecialUpload::detectScript: no scripts found\n");
800 /** Generic wrapper function for a virus scanner program.
801 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
802 * $wgAntivirusRequired may be used to deny upload if the scan fails.
804 * @param string $file Pathname to the temporary upload file
805 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
806 * or a string containing feedback from the virus scanner if a virus was found.
807 * If textual feedback is missing but a virus was found, this function returns true.
809 function detectVirus($file) {
810 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
812 $fname= "SpecialUpload::detectVirus";
814 if (!$wgAntivirus) { #disabled?
815 wfDebug("$fname: virus scanner disabled\n");
820 if (!$wgAntivirusSetup[$wgAntivirus]) {
821 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
823 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
825 return "unknown antivirus: $wgAntivirus";
828 #look up scanner configuration
829 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
830 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
831 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
833 $scanner= $virus_scanner; #copy, so we can resolve the pattern
835 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
836 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
838 wfDebug("$fname: running virus scan: $scanner \n");
840 #execute virus scanner
843 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
844 # that does not seem to be worth the pain.
845 # Ask me (Duesentrieb) about it if it's ever needed.
846 if (wfIsWindows()) exec("$scanner",$output,$code);
847 else exec("$scanner 2>&1",$output,$code);
849 $exit_code= $code; #remeber for user feedback
851 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
852 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
853 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
856 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
857 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
859 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
862 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
863 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
866 else if ($code===AV_NO_VIRUS
) {
867 wfDebug("$fname: file passed virus scan.\n");
868 return false; #no virus found
871 $output= join("\n",$output);
872 $output= trim($output);
874 if (!$output) $output= true; #if ther's no output, return true
875 else if ($msg_pattern) {
877 if (preg_match($msg_pattern,$output,$groups)) {
878 if ($groups[1]) $output= $groups[1];
882 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");