typo, exclude the disamb link as articles obviously point to it
[mediawiki.git] / includes / SpecialUpload.php
blobb88b0983904fb25b6d08c70b5a408696e55a9e87
1 <?php
2 /**
4 * @package MediaWiki
5 * @subpackage SpecialPage
6 */
8 /**
11 require_once( 'Image.php' );
13 /**
14 * Entry point
16 function wfSpecialUpload() {
17 global $wgRequest;
18 $form = new UploadForm( $wgRequest );
19 $form->execute();
22 /**
24 * @package MediaWiki
25 * @subpackage SpecialPage
27 class UploadForm {
28 /**#@+
29 * @access private
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;
35 /**#@-*/
37 /**
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.
47 return;
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] ) ) {
64 /**
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 } else {
76 /**
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;
87 /**
88 * Start doing stuff
89 * @access public
91 function execute() {
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' ) );
98 return;
101 /** Various rights checks */
102 if( !$wgUser->isAllowed( 'upload' ) || $wgUser->isBlocked() ) {
103 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
104 return;
106 if( wfReadOnly() ) {
107 $wgOut->readOnlyPage();
108 return;
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 ) );
114 return;
117 if( $this->mReUpload ) {
118 $this->unsaveUploadedFile();
119 $this->mainUploadForm();
120 } else if ( 'submit' == $this->mAction || $this->mUpload ) {
121 $this->processUpload();
122 } else {
123 $this->mainUploadForm();
127 /* -------------------------------------------------------------- */
130 * Really do the upload
131 * Checks are made in SpecialUpload::execute()
132 * @access private
134 function processUpload() {
135 global $wgUser, $wgOut, $wgLang, $wgContLang;
136 global $wgUploadDirectory, $wgCopyrightAffirmation;
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>');
146 if ( !$wgCopyrightAffirmation )
147 $this->mUploadAffirm = true;
149 * When using detailed copyright, if user filled field, assume he
150 * confirmed the upload
152 if ( $wgUseCopyrightUpload ) {
153 $this->mUploadAffirm = true;
154 if( $wgCheckCopyrightUpload &&
155 ( trim( $this->mUploadCopyStatus ) == '' ||
156 trim( $this->mUploadSource ) == '' ) ) {
157 $this->mUploadAffirm = false;
161 /** User need to confirm his upload */
162 if( !$this->mUploadAffirm ) {
163 $this->mainUploadForm( wfMsg( 'noaffirmation' ) );
164 return;
167 # Chop off any directories in the given filename
168 if ( $this->mDestFile ) {
169 $basename = basename( $this->mDestFile );
170 } else {
171 $basename = basename( $this->mOname );
175 * We'll want to blacklist against *any* 'extension', and use
176 * only the final one for the whitelist.
178 list( $partname, $ext ) = $this->splitExtensions( $basename );
179 if( count( $ext ) ) {
180 $finalExt = $ext[count( $ext ) - 1];
181 } else {
182 $finalExt = '';
184 $fullExt = implode( '.', $ext );
186 if ( strlen( $partname ) < 3 ) {
187 $this->mainUploadForm( wfMsg( 'minlength' ) );
188 return;
192 * Filter out illegal characters, and try to make a legible name
193 * out of it. We'll strip some silently that Title would die on.
195 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
196 $nt = Title::newFromText( $filtered );
197 if( is_null( $nt ) ) {
198 return $this->uploadError( wfMsg( 'illegalfilename', htmlspecialchars( $filtered ) ) );
200 $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() );
201 $this->mUploadSaveName = $nt->getDBkey();
204 * If the image is protected, non-sysop users won't be able
205 * to modify it by uploading a new revision.
207 if( !$nt->userCanEdit() ) {
208 return $this->uploadError( wfMsg( 'protectedpage' ) );
211 /* Don't allow users to override the blacklist (check file extension) */
212 global $wgStrictFileExtensions;
213 global $wgFileExtensions, $wgFileBlacklist;
214 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
215 ($wgStrictFileExtensions &&
216 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
217 return $this->uploadError( wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ) );
221 * Look at the contents of the file; if we can recognize the
222 * type but it's corrupt or data of the wrong type, we should
223 * probably not accept it.
225 if( !$this->mStashed ) {
226 $veri= $this->verify($this->mUploadTempName, $finalExt);
228 if( $veri !== true ) { //it's a wiki error...
229 return $this->uploadError( $veri->toString() );
234 * Check for non-fatal conditions
236 if ( ! $this->mIgnoreWarning ) {
237 $warning = '';
238 if( $this->mUploadSaveName != ucfirst( $filtered ) ) {
239 $warning .= '<li>'.wfMsg( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
242 global $wgCheckFileExtensions;
243 if ( $wgCheckFileExtensions ) {
244 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
245 $warning .= '<li>'.wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
249 global $wgUploadSizeWarning;
250 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
251 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
252 # value, perhaps add GB,MB and KB suffixes?
253 $warning .= '<li>'.wfMsg( 'largefile', $wgUploadSizeWarning, $this->mUploadSize ).'</li>';
255 if ( $this->mUploadSize == 0 ) {
256 $warning .= '<li>'.wfMsg( 'emptyfile' ).'</li>';
259 if( $nt->getArticleID() ) {
260 global $wgUser;
261 $sk = $wgUser->getSkin();
262 $dlink = $sk->makeKnownLinkObj( $nt );
263 $warning .= '<li>'.wfMsg( 'fileexists', $dlink ).'</li>';
266 if( $warning != '' ) {
268 * Stash the file in a temporary location; the user can choose
269 * to let it through and we'll complete the upload then.
271 return $this->uploadWarning($warning);
276 * Try actually saving the thing...
277 * It will show an error form on failure.
279 if( $this->saveUploadedFile( $this->mUploadSaveName,
280 $this->mUploadTempName,
281 !empty( $this->mSessionKey ) ) ) {
283 * Update the upload log and create the description page
284 * if it's a new file.
286 $img = Image::newFromName( $this->mUploadSaveName );
287 $success = $img->recordUpload( $this->mUploadOldVersion,
288 $this->mUploadDescription,
289 $this->mUploadCopyStatus,
290 $this->mUploadSource );
292 if ( $success ) {
293 $this->showSuccess();
294 } else {
295 // Image::recordUpload() fails if the image went missing, which is
296 // unlikely, hence the lack of a specialised message
297 $wgOut->fileNotFoundError( $this->mUploadSaveName );
303 * Move the uploaded file from its temporary location to the final
304 * destination. If a previous version of the file exists, move
305 * it into the archive subdirectory.
307 * @todo If the later save fails, we may have disappeared the original file.
309 * @param string $saveName
310 * @param string $tempName full path to the temporary file
311 * @param bool $useRename if true, doesn't check that the source file
312 * is a PHP-managed upload temporary
314 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
315 global $wgUploadDirectory, $wgOut;
317 $fname= "SpecialUpload::saveUploadedFile";
319 $dest = wfImageDir( $saveName );
320 $archive = wfImageArchiveDir( $saveName );
321 $this->mSavedFile = "{$dest}/{$saveName}";
323 if( is_file( $this->mSavedFile ) ) {
324 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
325 wfSuppressWarnings();
326 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
327 wfRestoreWarnings();
329 if( ! $success ) {
330 $wgOut->fileRenameError( $this->mSavedFile,
331 "${archive}/{$this->mUploadOldVersion}" );
332 return false;
334 else wfDebug("$fname: moved file ".$this->mSavedFile." to ${archive}/{$this->mUploadOldVersion}\n");
336 else {
337 $this->mUploadOldVersion = '';
340 if( $useRename ) {
341 wfSuppressWarnings();
342 $success = rename( $tempName, $this->mSavedFile );
343 wfRestoreWarnings();
345 if( ! $success ) {
346 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
347 return false;
348 } else {
349 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
351 } else {
352 wfSuppressWarnings();
353 $success = move_uploaded_file( $tempName, $this->mSavedFile );
354 wfRestoreWarnings();
356 if( ! $success ) {
357 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
358 return false;
360 else wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
363 chmod( $this->mSavedFile, 0644 );
364 return true;
368 * Stash a file in a temporary directory for later processing
369 * after the user has confirmed it.
371 * If the user doesn't explicitly cancel or accept, these files
372 * can accumulate in the temp directory.
374 * @param string $saveName - the destination filename
375 * @param string $tempName - the source temporary file to save
376 * @return string - full path the stashed file, or false on failure
377 * @access private
379 function saveTempUploadedFile( $saveName, $tempName ) {
380 global $wgOut;
381 $archive = wfImageArchiveDir( $saveName, 'temp' );
382 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
384 if ( !move_uploaded_file( $tempName, $stash ) ) {
385 $wgOut->fileCopyError( $tempName, $stash );
386 return false;
389 return $stash;
393 * Stash a file in a temporary directory for later processing,
394 * and save the necessary descriptive info into the session.
395 * Returns a key value which will be passed through a form
396 * to pick up the path info on a later invocation.
398 * @return int
399 * @access private
401 function stashSession() {
402 $stash = $this->saveTempUploadedFile(
403 $this->mUploadSaveName, $this->mUploadTempName );
405 if( !$stash ) {
406 # Couldn't save the file.
407 return false;
410 $key = mt_rand( 0, 0x7fffffff );
411 $_SESSION['wsUploadData'][$key] = array(
412 'mUploadTempName' => $stash,
413 'mUploadSize' => $this->mUploadSize,
414 'mOname' => $this->mOname );
415 return $key;
419 * Remove a temporarily kept file stashed by saveTempUploadedFile().
420 * @access private
422 function unsaveUploadedFile() {
423 wfSuppressWarnings();
424 $success = unlink( $this->mUploadTempName );
425 wfRestoreWarnings();
426 if ( ! $success ) {
427 $wgOut->fileDeleteError( $this->mUploadTempName );
431 /* -------------------------------------------------------------- */
434 * Show some text and linkage on successful upload.
435 * @access private
437 function showSuccess() {
438 global $wgUser, $wgOut, $wgContLang;
440 $sk = $wgUser->getSkin();
441 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
442 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
443 $dlink = $sk->makeKnownLink( $dname, $dname );
445 $wgOut->addHTML( '<h2>' . wfMsg( 'successfulupload' ) . "</h2>\n" );
446 $text = wfMsg( 'fileuploaded', $ilink, $dlink );
447 $wgOut->addHTML( '<p>'.$text."\n" );
448 $wgOut->returnToMain( false );
452 * @param string $error as HTML
453 * @access private
455 function uploadError( $error ) {
456 global $wgOut;
457 $sub = wfMsg( 'uploadwarning' );
458 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
459 $wgOut->addHTML( "<h4 class='error'>{$error}</h4>\n" );
463 * There's something wrong with this file, not enough to reject it
464 * totally but we require manual intervention to save it for real.
465 * Stash it away, then present a form asking to confirm or cancel.
467 * @param string $warning as HTML
468 * @access private
470 function uploadWarning( $warning ) {
471 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
472 global $wgUseCopyrightUpload;
474 $this->mSessionKey = $this->stashSession();
475 if( !$this->mSessionKey ) {
476 # Couldn't save file; an error has been displayed so let's go.
477 return;
480 $sub = wfMsg( 'uploadwarning' );
481 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
482 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
484 $save = wfMsg( 'savefile' );
485 $reupload = wfMsg( 'reupload' );
486 $iw = wfMsg( 'ignorewarning' );
487 $reup = wfMsg( 'reuploaddesc' );
488 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
489 $action = $titleObj->escapeLocalURL( 'action=submit' );
491 if ( $wgUseCopyrightUpload )
493 $copyright = "
494 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
495 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
497 } else {
498 $copyright = "";
501 $wgOut->addHTML( "
502 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
503 <input type='hidden' name='wpUploadAffirm' value='1' />
504 <input type='hidden' name='wpIgnoreWarning' value='1' />
505 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
506 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
507 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile ) . "\" />
508 {$copyright}
509 <table border='0'>
510 <tr>
511 <tr>
512 <td align='right'>
513 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
514 </td>
515 <td align='left'>$iw</td>
516 </tr>
517 <tr>
518 <td align='right'>
519 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
520 </td>
521 <td align='left'>$reup</td>
522 </tr>
523 </tr>
524 </table></form>\n" );
528 * Displays the main upload form, optionally with a highlighted
529 * error message up at the top.
531 * @param string $msg as HTML
532 * @access private
534 function mainUploadForm( $msg='' ) {
535 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
536 global $wgUseCopyrightUpload, $wgCopyrightAffirmation;
538 $cols = intval($wgUser->getOption( 'cols' ));
539 $ew = $wgUser->getOption( 'editwidth' );
540 if ( $ew ) $ew = " style=\"width:100%\"";
541 else $ew = '';
543 if ( '' != $msg ) {
544 $sub = wfMsg( 'uploaderror' );
545 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
546 "<h4 class='error'>{$msg}</h4>\n" );
548 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
549 $sk = $wgUser->getSkin();
552 $sourcefilename = wfMsg( 'sourcefilename' );
553 $destfilename = wfMsg( 'destfilename' );
555 $fd = wfMsg( 'filedesc' );
556 $ulb = wfMsg( 'uploadbtn' );
558 $clink = $sk->makeKnownLink( wfMsgForContent( 'copyrightpage' ),
559 wfMsg( 'copyrightpagename' ) );
560 $ca = wfMsg( 'affirmation', $clink );
561 $iw = wfMsg( 'ignorewarning' );
563 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
564 $action = $titleObj->escapeLocalURL();
566 $encDestFile = htmlspecialchars( $this->mDestFile );
567 $source = null;
569 if ( $wgCopyrightAffirmation ) {
570 $source = "
571 <td align='right'>
572 <input tabindex='3' type='checkbox' name='wpUploadAffirm' value='1' id='wpUploadAffirm' />
573 </td><td align='left'><label for='wpUploadAffirm'>{$ca}</label></td>
576 if ( $wgUseCopyrightUpload )
578 $source = "
579 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
580 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
581 htmlspecialchars($this->mUploadCopyStatus). "\" size='40' /></td>
582 </tr><tr>
583 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
584 <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
585 htmlspecialchars($this->mUploadSource). "\" size='40' /></td>
589 $wgOut->addHTML( "
590 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
591 <table border='0'><tr>
593 <td align='right'>{$sourcefilename}:</td><td align='left'>
594 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onchange='fillDestFilename()' size='40' />
595 </td></tr><tr>
597 <td align='right'>{$destfilename}:</td><td align='left'>
598 <input tabindex='1' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
599 </td></tr><tr>
601 <td align='right'>{$fd}:</td><td align='left'>
602 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
603 . htmlspecialchars( $this->mUploadDescription ) .
604 "</textarea>
605 </td></tr><tr>
606 {$source}
607 </tr>
608 <tr><td></td><td align='left'>
609 <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
610 </td></tr></table></form>\n" );
613 /* -------------------------------------------------------------- */
616 * Split a file into a base name and all dot-delimited 'extensions'
617 * on the end. Some web server configurations will fall back to
618 * earlier pseudo-'extensions' to determine type and execute
619 * scripts, so the blacklist needs to check them all.
621 * @return array
623 function splitExtensions( $filename ) {
624 $bits = explode( '.', $filename );
625 $basename = array_shift( $bits );
626 return array( $basename, $bits );
630 * Perform case-insensitive match against a list of file extensions.
631 * Returns true if the extension is in the list.
633 * @param string $ext
634 * @param array $list
635 * @return bool
637 function checkFileExtension( $ext, $list ) {
638 return in_array( strtolower( $ext ), $list );
642 * Perform case-insensitive match against a list of file extensions.
643 * Returns true if any of the extensions are in the list.
645 * @param array $ext
646 * @param array $list
647 * @return bool
649 function checkFileExtensionList( $ext, $list ) {
650 foreach( $ext as $e ) {
651 if( in_array( strtolower( $e ), $list ) ) {
652 return true;
655 return false;
659 * Verifies that it's ok to include the uploaded file
661 * @param string $tmpfile the full path opf the temporary file to verify
662 * @param string $extension The filename extension that the file is to be served with
663 * @return mixed true of the file is verified, a WikiError object otherwise.
665 function verify( $tmpfile, $extension ) {
666 #magically determine mime type
667 $magic=& wfGetMimeMagic();
668 $mime= $magic->guessMimeType($tmpfile,false);
670 $fname= "SpecialUpload::verify";
672 #check mime type, if desired
673 global $wgVerifyMimeType;
674 if ($wgVerifyMimeType) {
676 #check mime type against file extension
677 if( !$this->verifyExtension( $mime, $extension ) ) {
678 return new WikiErrorMsg( 'uploadcorrupt' );
681 #check mime type blacklist
682 global $wgMimeTypeBlacklist;
683 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
684 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
685 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
689 #check for htmlish code and javascript
690 if( $this->detectScript ( $tmpfile, $mime ) ) {
691 return new WikiErrorMsg( 'uploadscripted' );
695 * Scan the uploaded file for viruses
697 $virus= $this->detectVirus($tmpfile);
698 if ( $virus ) {
699 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
702 wfDebug( "$fname: all clear; passing.\n" );
703 return true;
707 * Checks if the mime type of the uploaded file matches the file extension.
709 * @param string $mime the mime type of the uploaded file
710 * @param string $extension The filename extension that the file is to be served with
711 * @return bool
713 function verifyExtension( $mime, $extension ) {
714 $fname = 'SpecialUpload::verifyExtension';
716 if (!$mime || $mime=="unknown" || $mime=="unknown/unknown") {
717 wfDebug( "$fname: passing file with unknown mime type\n" );
718 return true;
721 $magic=& wfGetMimeMagic();
723 $match= $magic->isMatchingExtension($extension,$mime);
725 if ($match===NULL) {
726 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
727 return true;
728 } elseif ($match===true) {
729 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
731 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
732 return true;
734 } else {
735 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
736 return false;
740 /** Heuristig for detecting files that *could* contain JavaScript instructions or
741 * things that may look like HTML to a browser and are thus
742 * potentially harmful. The present implementation will produce false positives in some situations.
744 * @param string $file Pathname to the temporary upload file
745 * @param string $mime The mime type of the file
746 * @return bool true if the file contains something looking like embedded scripts
748 function detectScript($file,$mime) {
750 #ugly hack: for text files, always look at the entire file.
751 #For binarie field, just check the first K.
753 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
754 else {
755 $fp = fopen( $file, 'rb' );
756 $chunk = fread( $fp, 1024 );
757 fclose( $fp );
760 $chunk= strtolower( $chunk );
762 if (!$chunk) return false;
764 #decode from UTF-16 if needed (could be used for obfuscation).
765 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
766 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
767 else $enc= NULL;
769 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
771 $chunk= trim($chunk);
773 #FIXME: convert from UTF-16 if necessarry!
775 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
777 #check for HTML doctype
778 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
781 * Internet Explorer for Windows performs some really stupid file type
782 * autodetection which can cause it to interpret valid image files as HTML
783 * and potentially execute JavaScript, creating a cross-site scripting
784 * attack vectors.
786 * Apple's Safari browser also performs some unsafe file type autodetection
787 * which can cause legitimate files to be interpreted as HTML if the
788 * web server is not correctly configured to send the right content-type
789 * (or if you're really uploading plain text and octet streams!)
791 * Returns true if IE is likely to mistake the given file for HTML.
792 * Also returns true if Safari would mistake the given file for HTML
793 * when served with a generic content-type.
796 $tags = array(
797 '<body',
798 '<head',
799 '<html', #also in safari
800 '<img',
801 '<pre',
802 '<script', #also in safari
803 '<table',
804 '<title' #also in safari
807 foreach( $tags as $tag ) {
808 if( false !== strpos( $chunk, $tag ) ) {
809 return true;
814 * look for javascript
817 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
818 $chunk = Sanitizer::decodeCharReferences( $chunk );
820 #look for script-types
821 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
823 #look for html-style script-urls
824 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
826 #look for css-style script-urls
827 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
829 wfDebug("SpecialUpload::detectScript: no scripts found\n");
830 return false;
833 /** Generic wrapper function for a virus scanner program.
834 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
835 * $wgAntivirusRequired may be used to deny upload if the scan fails.
837 * @param string $file Pathname to the temporary upload file
838 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
839 * or a string containing feedback from the virus scanner if a virus was found.
840 * If textual feedback is missing but a virus was found, this function returns true.
842 function detectVirus($file) {
843 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
845 $fname= "SpecialUpload::detectVirus";
847 if (!$wgAntivirus) { #disabled?
848 wfDebug("$fname: virus scanner disabled\n");
850 return NULL;
853 if (!$wgAntivirusSetup[$wgAntivirus]) {
854 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
856 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
858 return "unknown antivirus: $wgAntivirus";
861 #look up scanner configuration
862 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
863 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
864 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
866 $scanner= $virus_scanner; #copy, so we can resolve the pattern
868 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
869 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
871 wfDebug("$fname: running virus scan: $scanner \n");
873 #execute virus scanner
874 $code= false;
876 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
877 # that does not seem to be worth the pain.
878 # Ask me (Duesentrieb) about it if it's ever needed.
879 if (wfIsWindows()) exec("$scanner",$output,$code);
880 else exec("$scanner 2>&1",$output,$code);
882 $exit_code= $code; #remeber for user feedback
884 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
885 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
886 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
889 if ($code===AV_SCAN_FAILED) { #scan failed (code was mapped to false by $virus_scanner_codes)
890 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
892 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
893 else return NULL;
895 else if ($code===AV_SCAN_ABORTED) { #scan failed because filetype is unknown (probably imune)
896 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
897 return NULL;
899 else if ($code===AV_NO_VIRUS) {
900 wfDebug("$fname: file passed virus scan.\n");
901 return false; #no virus found
903 else {
904 $output= join("\n",$output);
905 $output= trim($output);
907 if (!$output) $output= true; #if ther's no output, return true
908 else if ($msg_pattern) {
909 $groups= array();
910 if (preg_match($msg_pattern,$output,$groups)) {
911 if ($groups[1]) $output= $groups[1];
915 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
916 return $output;