5 * @subpackage SpecialPage
11 require_once( 'Image.php' );
12 require_once( 'MacBinary.php' );
17 function wfSpecialUpload() {
19 $form = new UploadForm( $wgRequest );
26 * @subpackage SpecialPage
32 var $mUploadFile, $mUploadDescription, $mIgnoreWarning;
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->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;
75 $this->mRemoveTempFile
= false;
78 *Check for a newly uploaded file.
80 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
81 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
82 $this->mOname
= $request->getFileName( 'wpUploadFile' );
83 $this->mSessionKey
= false;
84 $this->mStashed
= false;
85 $this->mRemoveTempFile
= false; // PHP will handle this
94 global $wgUser, $wgOut;
95 global $wgEnableUploads, $wgUploadDirectory;
97 /** Show an error message if file upload is disabled */
98 if( ! $wgEnableUploads ) {
99 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
103 /** Various rights checks */
104 if( !$wgUser->isAllowed( 'upload' ) ||
$wgUser->isBlocked() ) {
105 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
109 $wgOut->readOnlyPage();
113 /** Check if the image directory is writeable, this is a common mistake */
114 if ( !is_writeable( $wgUploadDirectory ) ) {
115 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
119 if( $this->mReUpload
) {
120 $this->unsaveUploadedFile();
121 $this->mainUploadForm();
122 } else if ( 'submit' == $this->mAction ||
$this->mUpload
) {
123 $this->processUpload();
125 $this->mainUploadForm();
128 $this->cleanupTempFile();
131 /* -------------------------------------------------------------- */
134 * Really do the upload
135 * Checks are made in SpecialUpload::execute()
138 function processUpload() {
139 global $wgUser, $wgOut, $wgLang, $wgContLang;
140 global $wgUploadDirectory;
141 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
144 * If there was no filename or a zero size given, give up quick.
146 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
147 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
151 # Chop off any directories in the given filename
152 if ( $this->mDestFile
) {
153 $basename = basename( $this->mDestFile
);
155 $basename = basename( $this->mOname
);
159 * We'll want to blacklist against *any* 'extension', and use
160 * only the final one for the whitelist.
162 list( $partname, $ext ) = $this->splitExtensions( $basename );
163 if( count( $ext ) ) {
164 $finalExt = $ext[count( $ext ) - 1];
168 $fullExt = implode( '.', $ext );
170 if ( strlen( $partname ) < 3 ) {
171 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
176 * Filter out illegal characters, and try to make a legible name
177 * out of it. We'll strip some silently that Title would die on.
179 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
180 $nt = Title
::newFromText( $filtered );
181 if( is_null( $nt ) ) {
182 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
185 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
186 $this->mUploadSaveName
= $nt->getDBkey();
189 * If the image is protected, non-sysop users won't be able
190 * to modify it by uploading a new revision.
192 if( !$nt->userCanEdit() ) {
193 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
196 /* Don't allow users to override the blacklist (check file extension) */
197 global $wgStrictFileExtensions;
198 global $wgFileExtensions, $wgFileBlacklist;
199 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
200 ($wgStrictFileExtensions &&
201 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
202 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
206 * Look at the contents of the file; if we can recognize the
207 * type but it's corrupt or data of the wrong type, we should
208 * probably not accept it.
210 if( !$this->mStashed
) {
211 $this->checkMacBinary();
212 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
214 if( $veri !== true ) { //it's a wiki error...
215 return $this->uploadError( $veri->toString() );
220 * Check for non-fatal conditions
222 if ( ! $this->mIgnoreWarning
) {
224 if( $this->mUploadSaveName
!= ucfirst( $filtered ) ) {
225 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
228 global $wgCheckFileExtensions;
229 if ( $wgCheckFileExtensions ) {
230 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
231 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
235 global $wgUploadSizeWarning;
236 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
237 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
238 # value, perhaps add GB,MB and KB suffixes?
239 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
241 if ( $this->mUploadSize
== 0 ) {
242 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
245 if( $nt->getArticleID() ) {
247 $sk = $wgUser->getSkin();
248 $dlink = $sk->makeKnownLinkObj( $nt );
249 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
252 if( $warning != '' ) {
254 * Stash the file in a temporary location; the user can choose
255 * to let it through and we'll complete the upload then.
257 return $this->uploadWarning($warning . "</ul>");
262 * Try actually saving the thing...
263 * It will show an error form on failure.
265 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
266 if( $this->saveUploadedFile( $this->mUploadSaveName
,
267 $this->mUploadTempName
,
270 * Update the upload log and create the description page
271 * if it's a new file.
273 $img = Image
::newFromName( $this->mUploadSaveName
);
274 $success = $img->recordUpload( $this->mUploadOldVersion
,
275 $this->mUploadDescription
,
276 $this->mUploadCopyStatus
,
277 $this->mUploadSource
);
280 $this->showSuccess();
282 // Image::recordUpload() fails if the image went missing, which is
283 // unlikely, hence the lack of a specialised message
284 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
290 * Move the uploaded file from its temporary location to the final
291 * destination. If a previous version of the file exists, move
292 * it into the archive subdirectory.
294 * @todo If the later save fails, we may have disappeared the original file.
296 * @param string $saveName
297 * @param string $tempName full path to the temporary file
298 * @param bool $useRename if true, doesn't check that the source file
299 * is a PHP-managed upload temporary
301 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
302 global $wgUploadDirectory, $wgOut;
304 $fname= "SpecialUpload::saveUploadedFile";
306 $dest = wfImageDir( $saveName );
307 $archive = wfImageArchiveDir( $saveName );
308 $this->mSavedFile
= "{$dest}/{$saveName}";
310 if( is_file( $this->mSavedFile
) ) {
311 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
312 wfSuppressWarnings();
313 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
317 $wgOut->fileRenameError( $this->mSavedFile
,
318 "${archive}/{$this->mUploadOldVersion}" );
321 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
324 $this->mUploadOldVersion
= '';
327 wfSuppressWarnings();
328 $success = $useRename
329 ?
rename( $tempName, $this->mSavedFile
)
330 : move_uploaded_file( $tempName, $this->mSavedFile
);
334 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
337 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
340 chmod( $this->mSavedFile
, 0644 );
345 * Stash a file in a temporary directory for later processing
346 * after the user has confirmed it.
348 * If the user doesn't explicitly cancel or accept, these files
349 * can accumulate in the temp directory.
351 * @param string $saveName - the destination filename
352 * @param string $tempName - the source temporary file to save
353 * @return string - full path the stashed file, or false on failure
356 function saveTempUploadedFile( $saveName, $tempName ) {
358 $archive = wfImageArchiveDir( $saveName, 'temp' );
359 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
361 $success = $this->mRemoveTempFile
362 ?
rename( $tempName, $stash )
363 : move_uploaded_file( $tempName, $stash );
365 $wgOut->fileCopyError( $tempName, $stash );
373 * Stash a file in a temporary directory for later processing,
374 * and save the necessary descriptive info into the session.
375 * Returns a key value which will be passed through a form
376 * to pick up the path info on a later invocation.
381 function stashSession() {
382 $stash = $this->saveTempUploadedFile(
383 $this->mUploadSaveName
, $this->mUploadTempName
);
386 # Couldn't save the file.
390 $key = mt_rand( 0, 0x7fffffff );
391 $_SESSION['wsUploadData'][$key] = array(
392 'mUploadTempName' => $stash,
393 'mUploadSize' => $this->mUploadSize
,
394 'mOname' => $this->mOname
);
399 * Remove a temporarily kept file stashed by saveTempUploadedFile().
402 function unsaveUploadedFile() {
404 wfSuppressWarnings();
405 $success = unlink( $this->mUploadTempName
);
408 $wgOut->fileDeleteError( $this->mUploadTempName
);
412 /* -------------------------------------------------------------- */
415 * Show some text and linkage on successful upload.
418 function showSuccess() {
419 global $wgUser, $wgOut, $wgContLang;
421 $sk = $wgUser->getSkin();
422 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
423 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
424 $dlink = $sk->makeKnownLink( $dname, $dname );
426 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
427 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
428 $wgOut->addHTML( $text );
429 $wgOut->returnToMain( false );
433 * @param string $error as HTML
436 function uploadError( $error ) {
438 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
439 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
443 * There's something wrong with this file, not enough to reject it
444 * totally but we require manual intervention to save it for real.
445 * Stash it away, then present a form asking to confirm or cancel.
447 * @param string $warning as HTML
450 function uploadWarning( $warning ) {
451 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
452 global $wgUseCopyrightUpload;
454 $this->mSessionKey
= $this->stashSession();
455 if( !$this->mSessionKey
) {
456 # Couldn't save file; an error has been displayed so let's go.
460 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
461 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
463 $save = wfMsgHtml( 'savefile' );
464 $reupload = wfMsgHtml( 'reupload' );
465 $iw = wfMsgWikiHtml( 'ignorewarning' );
466 $reup = wfMsgWikiHtml( 'reuploaddesc' );
467 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
468 $action = $titleObj->escapeLocalURL( 'action=submit' );
470 if ( $wgUseCopyrightUpload )
473 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
474 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
481 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
482 <input type='hidden' name='wpIgnoreWarning' value='1' />
483 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
484 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
485 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
491 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
493 <td align='left'>$iw</td>
497 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
499 <td align='left'>$reup</td>
502 </table></form>\n" );
506 * Displays the main upload form, optionally with a highlighted
507 * error message up at the top.
509 * @param string $msg as HTML
512 function mainUploadForm( $msg='' ) {
513 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
514 global $wgUseCopyrightUpload;
516 $cols = intval($wgUser->getOption( 'cols' ));
517 $ew = $wgUser->getOption( 'editwidth' );
518 if ( $ew ) $ew = " style=\"width:100%\"";
522 $sub = wfMsgHtml( 'uploaderror' );
523 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
524 "<span class='error'>{$msg}</span>\n" );
526 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
527 $sk = $wgUser->getSkin();
530 $sourcefilename = wfMsgHtml( 'sourcefilename' );
531 $destfilename = wfMsgHtml( 'destfilename' );
533 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
534 $ulb = wfMsgHtml( 'uploadbtn' );
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'>{$summary}</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 of 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");
888 * Check if the temporary file is MacBinary-encoded, as some uploads
889 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
890 * If so, the data fork will be extracted to a second temporary file,
891 * which will then be checked for validity and either kept or discarded.
895 function checkMacBinary() {
896 $macbin = new MacBinary( $this->mUploadTempName
);
897 if( $macbin->isValid() ) {
898 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
899 $dataHandle = fopen( $dataFile, 'wb' );
901 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
902 $macbin->extractData( $dataHandle );
904 $this->mUploadTempName
= $dataFile;
905 $this->mUploadSize
= $macbin->dataForkLength();
907 // We'll have to manually remove the new file if it's not kept.
908 $this->mRemoveTempFile
= true;
914 * If we've modified the upload file we need to manually remove it
915 * on exit to clean up.
918 function cleanupTempFile() {
919 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
920 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
921 unlink( $this->mUploadTempName
);