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, $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->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->mUploadError
= 0/*UPLOAD_ERR_OK*/;
75 $this->mStashed
= true;
76 $this->mRemoveTempFile
= false;
79 *Check for a newly uploaded file.
81 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
82 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
83 $this->mOname
= $request->getFileName( 'wpUploadFile' );
84 $this->mUploadError
= $request->getUploadError( 'wpUploadFile' );
85 $this->mSessionKey
= false;
86 $this->mStashed
= false;
87 $this->mRemoveTempFile
= false; // PHP will handle this
96 global $wgUser, $wgOut;
97 global $wgEnableUploads, $wgUploadDirectory;
99 /** Show an error message if file upload is disabled */
100 if( ! $wgEnableUploads ) {
101 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
105 /** Various rights checks */
106 if( !$wgUser->isAllowed( 'upload' ) ||
$wgUser->isBlocked() ) {
107 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
111 $wgOut->readOnlyPage();
115 /** Check if the image directory is writeable, this is a common mistake */
116 if ( !is_writeable( $wgUploadDirectory ) ) {
117 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
121 if( $this->mReUpload
) {
122 $this->unsaveUploadedFile();
123 $this->mainUploadForm();
124 } else if ( 'submit' == $this->mAction ||
$this->mUpload
) {
125 $this->processUpload();
127 $this->mainUploadForm();
130 $this->cleanupTempFile();
133 /* -------------------------------------------------------------- */
136 * Really do the upload
137 * Checks are made in SpecialUpload::execute()
140 function processUpload() {
141 global $wgUser, $wgOut, $wgLang, $wgContLang;
142 global $wgUploadDirectory;
143 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
145 /* Check for PHP error if any, requires php 4.2 or newer */
146 if ( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
147 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
152 * If there was no filename or a zero size given, give up quick.
154 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
155 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
159 # Chop off any directories in the given filename
160 if ( $this->mDestFile
) {
161 $basename = basename( $this->mDestFile
);
163 $basename = basename( $this->mOname
);
167 * We'll want to blacklist against *any* 'extension', and use
168 * only the final one for the whitelist.
170 list( $partname, $ext ) = $this->splitExtensions( $basename );
171 if( count( $ext ) ) {
172 $finalExt = $ext[count( $ext ) - 1];
176 $fullExt = implode( '.', $ext );
178 if ( strlen( $partname ) < 3 ) {
179 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
184 * Filter out illegal characters, and try to make a legible name
185 * out of it. We'll strip some silently that Title would die on.
187 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
188 $nt = Title
::newFromText( $filtered );
189 if( is_null( $nt ) ) {
190 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
193 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
194 $this->mUploadSaveName
= $nt->getDBkey();
197 * If the image is protected, non-sysop users won't be able
198 * to modify it by uploading a new revision.
200 if( !$nt->userCanEdit() ) {
201 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
204 /* Don't allow users to override the blacklist (check file extension) */
205 global $wgStrictFileExtensions;
206 global $wgFileExtensions, $wgFileBlacklist;
207 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
208 ($wgStrictFileExtensions &&
209 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
210 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
214 * Look at the contents of the file; if we can recognize the
215 * type but it's corrupt or data of the wrong type, we should
216 * probably not accept it.
218 if( !$this->mStashed
) {
219 $this->checkMacBinary();
220 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
222 if( $veri !== true ) { //it's a wiki error...
223 return $this->uploadError( $veri->toString() );
228 * Check for non-fatal conditions
230 if ( ! $this->mIgnoreWarning
) {
232 if( $this->mUploadSaveName
!= ucfirst( $filtered ) ) {
233 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
236 global $wgCheckFileExtensions;
237 if ( $wgCheckFileExtensions ) {
238 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
239 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
243 global $wgUploadSizeWarning;
244 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
245 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
246 # value, perhaps add GB,MB and KB suffixes?
247 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
249 if ( $this->mUploadSize
== 0 ) {
250 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
253 if( $nt->getArticleID() ) {
255 $sk = $wgUser->getSkin();
256 $dlink = $sk->makeKnownLinkObj( $nt );
257 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
260 if( $warning != '' ) {
262 * Stash the file in a temporary location; the user can choose
263 * to let it through and we'll complete the upload then.
265 return $this->uploadWarning( $warning );
270 * Try actually saving the thing...
271 * It will show an error form on failure.
273 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
274 if( $this->saveUploadedFile( $this->mUploadSaveName
,
275 $this->mUploadTempName
,
278 * Update the upload log and create the description page
279 * if it's a new file.
281 $img = Image
::newFromName( $this->mUploadSaveName
);
282 $success = $img->recordUpload( $this->mUploadOldVersion
,
283 $this->mUploadDescription
,
284 $this->mUploadCopyStatus
,
285 $this->mUploadSource
);
288 $this->showSuccess();
290 // Image::recordUpload() fails if the image went missing, which is
291 // unlikely, hence the lack of a specialised message
292 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
298 * Move the uploaded file from its temporary location to the final
299 * destination. If a previous version of the file exists, move
300 * it into the archive subdirectory.
302 * @todo If the later save fails, we may have disappeared the original file.
304 * @param string $saveName
305 * @param string $tempName full path to the temporary file
306 * @param bool $useRename if true, doesn't check that the source file
307 * is a PHP-managed upload temporary
309 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
310 global $wgUploadDirectory, $wgOut;
312 $fname= "SpecialUpload::saveUploadedFile";
314 $dest = wfImageDir( $saveName );
315 $archive = wfImageArchiveDir( $saveName );
316 $this->mSavedFile
= "{$dest}/{$saveName}";
318 if( is_file( $this->mSavedFile
) ) {
319 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
320 wfSuppressWarnings();
321 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
325 $wgOut->fileRenameError( $this->mSavedFile
,
326 "${archive}/{$this->mUploadOldVersion}" );
329 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
332 $this->mUploadOldVersion
= '';
335 wfSuppressWarnings();
336 $success = $useRename
337 ?
rename( $tempName, $this->mSavedFile
)
338 : move_uploaded_file( $tempName, $this->mSavedFile
);
342 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
345 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
348 chmod( $this->mSavedFile
, 0644 );
353 * Stash a file in a temporary directory for later processing
354 * after the user has confirmed it.
356 * If the user doesn't explicitly cancel or accept, these files
357 * can accumulate in the temp directory.
359 * @param string $saveName - the destination filename
360 * @param string $tempName - the source temporary file to save
361 * @return string - full path the stashed file, or false on failure
364 function saveTempUploadedFile( $saveName, $tempName ) {
366 $archive = wfImageArchiveDir( $saveName, 'temp' );
367 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
369 $success = $this->mRemoveTempFile
370 ?
rename( $tempName, $stash )
371 : move_uploaded_file( $tempName, $stash );
373 $wgOut->fileCopyError( $tempName, $stash );
381 * Stash a file in a temporary directory for later processing,
382 * and save the necessary descriptive info into the session.
383 * Returns a key value which will be passed through a form
384 * to pick up the path info on a later invocation.
389 function stashSession() {
390 $stash = $this->saveTempUploadedFile(
391 $this->mUploadSaveName
, $this->mUploadTempName
);
394 # Couldn't save the file.
398 $key = mt_rand( 0, 0x7fffffff );
399 $_SESSION['wsUploadData'][$key] = array(
400 'mUploadTempName' => $stash,
401 'mUploadSize' => $this->mUploadSize
,
402 'mOname' => $this->mOname
);
407 * Remove a temporarily kept file stashed by saveTempUploadedFile().
410 function unsaveUploadedFile() {
412 wfSuppressWarnings();
413 $success = unlink( $this->mUploadTempName
);
416 $wgOut->fileDeleteError( $this->mUploadTempName
);
420 /* -------------------------------------------------------------- */
423 * Show some text and linkage on successful upload.
426 function showSuccess() {
427 global $wgUser, $wgOut, $wgContLang;
429 $sk = $wgUser->getSkin();
430 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
431 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
432 $dlink = $sk->makeKnownLink( $dname, $dname );
434 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
435 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
436 $wgOut->addHTML( $text );
437 $wgOut->returnToMain( false );
441 * @param string $error as HTML
444 function uploadError( $error ) {
446 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
447 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
451 * There's something wrong with this file, not enough to reject it
452 * totally but we require manual intervention to save it for real.
453 * Stash it away, then present a form asking to confirm or cancel.
455 * @param string $warning as HTML
458 function uploadWarning( $warning ) {
459 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
460 global $wgUseCopyrightUpload;
462 $this->mSessionKey
= $this->stashSession();
463 if( !$this->mSessionKey
) {
464 # Couldn't save file; an error has been displayed so let's go.
468 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
469 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
471 $save = wfMsgHtml( 'savefile' );
472 $reupload = wfMsgHtml( 'reupload' );
473 $iw = wfMsgWikiHtml( 'ignorewarning' );
474 $reup = wfMsgWikiHtml( 'reuploaddesc' );
475 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
476 $action = $titleObj->escapeLocalURL( 'action=submit' );
478 if ( $wgUseCopyrightUpload )
481 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
482 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
489 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
490 <input type='hidden' name='wpIgnoreWarning' value='1' />
491 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
492 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
493 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
499 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
501 <td align='left'>$iw</td>
505 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
507 <td align='left'>$reup</td>
510 </table></form>\n" );
514 * Displays the main upload form, optionally with a highlighted
515 * error message up at the top.
517 * @param string $msg as HTML
520 function mainUploadForm( $msg='' ) {
521 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
522 global $wgUseCopyrightUpload;
524 $cols = intval($wgUser->getOption( 'cols' ));
525 $ew = $wgUser->getOption( 'editwidth' );
526 if ( $ew ) $ew = " style=\"width:100%\"";
530 $sub = wfMsgHtml( 'uploaderror' );
531 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
532 "<span class='error'>{$msg}</span>\n" );
534 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
535 $sk = $wgUser->getSkin();
538 $sourcefilename = wfMsgHtml( 'sourcefilename' );
539 $destfilename = wfMsgHtml( 'destfilename' );
540 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
541 $ulb = wfMsgHtml( 'uploadbtn' );
544 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
545 $action = $titleObj->escapeLocalURL();
547 $encDestFile = htmlspecialchars( $this->mDestFile
);
550 if ( $wgUseCopyrightUpload )
553 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
554 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
555 htmlspecialchars($this->mUploadCopyStatus
). "\" size='40' /></td>
557 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
558 <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
559 htmlspecialchars($this->mUploadSource
). "\" size='40' /></td>
564 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
565 <table border='0'><tr>
567 <td align='right'>{$sourcefilename}:</td><td align='left'>
568 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onchange='fillDestFilename()' size='40' />
571 <td align='right'>{$destfilename}:</td><td align='left'>
572 <input tabindex='1' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
575 <td align='right'>{$summary}</td><td align='left'>
576 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
577 . htmlspecialchars( $this->mUploadDescription
) .
582 <tr><td></td><td align='left'>
583 <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
584 </td></tr></table></form>\n" );
587 /* -------------------------------------------------------------- */
590 * Split a file into a base name and all dot-delimited 'extensions'
591 * on the end. Some web server configurations will fall back to
592 * earlier pseudo-'extensions' to determine type and execute
593 * scripts, so the blacklist needs to check them all.
597 function splitExtensions( $filename ) {
598 $bits = explode( '.', $filename );
599 $basename = array_shift( $bits );
600 return array( $basename, $bits );
604 * Perform case-insensitive match against a list of file extensions.
605 * Returns true if the extension is in the list.
611 function checkFileExtension( $ext, $list ) {
612 return in_array( strtolower( $ext ), $list );
616 * Perform case-insensitive match against a list of file extensions.
617 * Returns true if any of the extensions are in the list.
623 function checkFileExtensionList( $ext, $list ) {
624 foreach( $ext as $e ) {
625 if( in_array( strtolower( $e ), $list ) ) {
633 * Verifies that it's ok to include the uploaded file
635 * @param string $tmpfile the full path of the temporary file to verify
636 * @param string $extension The filename extension that the file is to be served with
637 * @return mixed true of the file is verified, a WikiError object otherwise.
639 function verify( $tmpfile, $extension ) {
640 #magically determine mime type
641 $magic=& wfGetMimeMagic();
642 $mime= $magic->guessMimeType($tmpfile,false);
644 $fname= "SpecialUpload::verify";
646 #check mime type, if desired
647 global $wgVerifyMimeType;
648 if ($wgVerifyMimeType) {
650 #check mime type against file extension
651 if( !$this->verifyExtension( $mime, $extension ) ) {
652 return new WikiErrorMsg( 'uploadcorrupt' );
655 #check mime type blacklist
656 global $wgMimeTypeBlacklist;
657 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
658 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
659 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
663 #check for htmlish code and javascript
664 if( $this->detectScript ( $tmpfile, $mime ) ) {
665 return new WikiErrorMsg( 'uploadscripted' );
669 * Scan the uploaded file for viruses
671 $virus= $this->detectVirus($tmpfile);
673 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
676 wfDebug( "$fname: all clear; passing.\n" );
681 * Checks if the mime type of the uploaded file matches the file extension.
683 * @param string $mime the mime type of the uploaded file
684 * @param string $extension The filename extension that the file is to be served with
687 function verifyExtension( $mime, $extension ) {
688 $fname = 'SpecialUpload::verifyExtension';
690 if (!$mime ||
$mime=="unknown" ||
$mime=="unknown/unknown") {
691 wfDebug( "$fname: passing file with unknown mime type\n" );
695 $magic=& wfGetMimeMagic();
697 $match= $magic->isMatchingExtension($extension,$mime);
700 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
702 } elseif ($match===true) {
703 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
705 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
709 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
714 /** Heuristig for detecting files that *could* contain JavaScript instructions or
715 * things that may look like HTML to a browser and are thus
716 * potentially harmful. The present implementation will produce false positives in some situations.
718 * @param string $file Pathname to the temporary upload file
719 * @param string $mime The mime type of the file
720 * @return bool true if the file contains something looking like embedded scripts
722 function detectScript($file,$mime) {
724 #ugly hack: for text files, always look at the entire file.
725 #For binarie field, just check the first K.
727 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
729 $fp = fopen( $file, 'rb' );
730 $chunk = fread( $fp, 1024 );
734 $chunk= strtolower( $chunk );
736 if (!$chunk) return false;
738 #decode from UTF-16 if needed (could be used for obfuscation).
739 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
740 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
743 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
745 $chunk= trim($chunk);
747 #FIXME: convert from UTF-16 if necessarry!
749 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
751 #check for HTML doctype
752 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
755 * Internet Explorer for Windows performs some really stupid file type
756 * autodetection which can cause it to interpret valid image files as HTML
757 * and potentially execute JavaScript, creating a cross-site scripting
760 * Apple's Safari browser also performs some unsafe file type autodetection
761 * which can cause legitimate files to be interpreted as HTML if the
762 * web server is not correctly configured to send the right content-type
763 * (or if you're really uploading plain text and octet streams!)
765 * Returns true if IE is likely to mistake the given file for HTML.
766 * Also returns true if Safari would mistake the given file for HTML
767 * when served with a generic content-type.
773 '<html', #also in safari
776 '<script', #also in safari
778 '<title' #also in safari
781 foreach( $tags as $tag ) {
782 if( false !== strpos( $chunk, $tag ) ) {
788 * look for javascript
791 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
792 $chunk = Sanitizer
::decodeCharReferences( $chunk );
794 #look for script-types
795 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
797 #look for html-style script-urls
798 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
800 #look for css-style script-urls
801 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
803 wfDebug("SpecialUpload::detectScript: no scripts found\n");
807 /** Generic wrapper function for a virus scanner program.
808 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
809 * $wgAntivirusRequired may be used to deny upload if the scan fails.
811 * @param string $file Pathname to the temporary upload file
812 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
813 * or a string containing feedback from the virus scanner if a virus was found.
814 * If textual feedback is missing but a virus was found, this function returns true.
816 function detectVirus($file) {
817 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
819 $fname= "SpecialUpload::detectVirus";
821 if (!$wgAntivirus) { #disabled?
822 wfDebug("$fname: virus scanner disabled\n");
827 if (!$wgAntivirusSetup[$wgAntivirus]) {
828 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
830 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
832 return "unknown antivirus: $wgAntivirus";
835 #look up scanner configuration
836 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
837 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
838 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
840 $scanner= $virus_scanner; #copy, so we can resolve the pattern
842 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
843 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
845 wfDebug("$fname: running virus scan: $scanner \n");
847 #execute virus scanner
850 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
851 # that does not seem to be worth the pain.
852 # Ask me (Duesentrieb) about it if it's ever needed.
853 if (wfIsWindows()) exec("$scanner",$output,$code);
854 else exec("$scanner 2>&1",$output,$code);
856 $exit_code= $code; #remeber for user feedback
858 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
859 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
860 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
863 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
864 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
866 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
869 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
870 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
873 else if ($code===AV_NO_VIRUS
) {
874 wfDebug("$fname: file passed virus scan.\n");
875 return false; #no virus found
878 $output= join("\n",$output);
879 $output= trim($output);
881 if (!$output) $output= true; #if ther's no output, return true
882 else if ($msg_pattern) {
884 if (preg_match($msg_pattern,$output,$groups)) {
885 if ($groups[1]) $output= $groups[1];
889 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
895 * Check if the temporary file is MacBinary-encoded, as some uploads
896 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
897 * If so, the data fork will be extracted to a second temporary file,
898 * which will then be checked for validity and either kept or discarded.
902 function checkMacBinary() {
903 $macbin = new MacBinary( $this->mUploadTempName
);
904 if( $macbin->isValid() ) {
905 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
906 $dataHandle = fopen( $dataFile, 'wb' );
908 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
909 $macbin->extractData( $dataHandle );
911 $this->mUploadTempName
= $dataFile;
912 $this->mUploadSize
= $macbin->dataForkLength();
914 // We'll have to manually remove the new file if it's not kept.
915 $this->mRemoveTempFile
= true;
921 * If we've modified the upload file we need to manually remove it
922 * on exit to clean up.
925 function cleanupTempFile() {
926 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
927 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
928 unlink( $this->mUploadTempName
);