5 * @subpackage SpecialPage
11 require_once 'Image.php';
12 require_once 'MacBinary.php';
13 require_once 'Licenses.php';
17 function wfSpecialUpload() {
19 $form = new UploadForm( $wgRequest );
26 * @subpackage SpecialPage
32 var $mUploadFile, $mUploadDescription, $mLicense ,$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->mLicense
= $request->getText( 'wpLicense' );
57 $this->mUploadCopyStatus
= $request->getText( 'wpUploadCopyStatus' );
58 $this->mUploadSource
= $request->getText( 'wpUploadSource');
60 $this->mAction
= $request->getVal( 'action' );
62 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
63 if( !empty( $this->mSessionKey
) &&
64 isset( $_SESSION['wsUploadData'][$this->mSessionKey
] ) ) {
66 * Confirming a temporarily stashed upload.
67 * We don't want path names to be forged, so we keep
68 * them in the session on the server and just give
69 * an opaque key to the user agent.
71 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
72 $this->mUploadTempName
= $data['mUploadTempName'];
73 $this->mUploadSize
= $data['mUploadSize'];
74 $this->mOname
= $data['mOname'];
75 $this->mUploadError
= 0/*UPLOAD_ERR_OK*/;
76 $this->mStashed
= true;
77 $this->mRemoveTempFile
= false;
80 *Check for a newly uploaded file.
82 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
83 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
84 $this->mOname
= $request->getFileName( 'wpUploadFile' );
85 $this->mUploadError
= $request->getUploadError( 'wpUploadFile' );
86 $this->mSessionKey
= false;
87 $this->mStashed
= false;
88 $this->mRemoveTempFile
= false; // PHP will handle this
97 global $wgUser, $wgOut;
98 global $wgEnableUploads, $wgUploadDirectory;
100 /** Show an error message if file upload is disabled */
101 if( ! $wgEnableUploads ) {
102 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
106 /** Various rights checks */
107 if( !$wgUser->isAllowed( 'upload' ) ||
$wgUser->isBlocked() ) {
108 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
112 $wgOut->readOnlyPage();
116 /** Check if the image directory is writeable, this is a common mistake */
117 if ( !is_writeable( $wgUploadDirectory ) ) {
118 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
122 if( $this->mReUpload
) {
123 $this->unsaveUploadedFile();
124 $this->mainUploadForm();
125 } else if ( 'submit' == $this->mAction ||
$this->mUpload
) {
126 $this->processUpload();
128 $this->mainUploadForm();
131 $this->cleanupTempFile();
134 /* -------------------------------------------------------------- */
137 * Really do the upload
138 * Checks are made in SpecialUpload::execute()
141 function processUpload() {
142 global $wgUser, $wgOut, $wgLang, $wgContLang;
143 global $wgUploadDirectory;
144 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
146 /* Check for PHP error if any, requires php 4.2 or newer */
147 if ( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
148 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
153 * If there was no filename or a zero size given, give up quick.
155 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
156 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
160 # Chop off any directories in the given filename
161 if ( $this->mDestFile
) {
162 $basename = basename( $this->mDestFile
);
164 $basename = basename( $this->mOname
);
168 * We'll want to blacklist against *any* 'extension', and use
169 * only the final one for the whitelist.
171 list( $partname, $ext ) = $this->splitExtensions( $basename );
172 if( count( $ext ) ) {
173 $finalExt = $ext[count( $ext ) - 1];
177 $fullExt = implode( '.', $ext );
179 if ( strlen( $partname ) < 3 ) {
180 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
185 * Filter out illegal characters, and try to make a legible name
186 * out of it. We'll strip some silently that Title would die on.
188 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
189 $nt = Title
::newFromText( $filtered );
190 if( is_null( $nt ) ) {
191 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
194 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
195 $this->mUploadSaveName
= $nt->getDBkey();
198 * If the image is protected, non-sysop users won't be able
199 * to modify it by uploading a new revision.
201 if( !$nt->userCanEdit() ) {
202 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
206 * In some cases we may forbid overwriting of existing files.
208 $overwrite = $this->checkOverwrite( $this->mUploadSaveName
);
209 if( WikiError
::isError( $overwrite ) ) {
210 return $this->uploadError( $overwrite->toString() );
213 /* Don't allow users to override the blacklist (check file extension) */
214 global $wgStrictFileExtensions;
215 global $wgFileExtensions, $wgFileBlacklist;
216 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
217 ($wgStrictFileExtensions &&
218 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
219 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
223 * Look at the contents of the file; if we can recognize the
224 * type but it's corrupt or data of the wrong type, we should
225 * probably not accept it.
227 if( !$this->mStashed
) {
228 $this->checkMacBinary();
229 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
231 if( $veri !== true ) { //it's a wiki error...
232 return $this->uploadError( $veri->toString() );
237 * Provide an opportunity for extensions to add futher checks
240 if( !wfRunHooks( 'UploadVerification',
241 array( $this->mUploadSaveName
, $this->mUploadTempName
, &$error ) ) ) {
242 return $this->uploadError( $error );
246 * Check for non-fatal conditions
248 if ( ! $this->mIgnoreWarning
) {
250 if( $this->mUploadSaveName
!= ucfirst( $filtered ) ) {
251 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
254 global $wgCheckFileExtensions;
255 if ( $wgCheckFileExtensions ) {
256 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
257 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
261 global $wgUploadSizeWarning;
262 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
263 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
264 # value, perhaps add GB,MB and KB suffixes?
265 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
267 if ( $this->mUploadSize
== 0 ) {
268 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
271 if( $nt->getArticleID() ) {
273 $sk = $wgUser->getSkin();
274 $dlink = $sk->makeKnownLinkObj( $nt );
275 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
278 if( $warning != '' ) {
280 * Stash the file in a temporary location; the user can choose
281 * to let it through and we'll complete the upload then.
283 return $this->uploadWarning( $warning );
288 * Try actually saving the thing...
289 * It will show an error form on failure.
291 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
292 if( $this->saveUploadedFile( $this->mUploadSaveName
,
293 $this->mUploadTempName
,
296 * Update the upload log and create the description page
297 * if it's a new file.
299 $img = Image
::newFromName( $this->mUploadSaveName
);
300 $success = $img->recordUpload( $this->mUploadOldVersion
,
301 $this->mUploadDescription
,
303 $this->mUploadCopyStatus
,
304 $this->mUploadSource
);
307 $this->showSuccess();
309 // Image::recordUpload() fails if the image went missing, which is
310 // unlikely, hence the lack of a specialised message
311 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
317 * Move the uploaded file from its temporary location to the final
318 * destination. If a previous version of the file exists, move
319 * it into the archive subdirectory.
321 * @todo If the later save fails, we may have disappeared the original file.
323 * @param string $saveName
324 * @param string $tempName full path to the temporary file
325 * @param bool $useRename if true, doesn't check that the source file
326 * is a PHP-managed upload temporary
328 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
329 global $wgUploadDirectory, $wgOut;
331 $fname= "SpecialUpload::saveUploadedFile";
333 $dest = wfImageDir( $saveName );
334 $archive = wfImageArchiveDir( $saveName );
335 $this->mSavedFile
= "{$dest}/{$saveName}";
337 if( is_file( $this->mSavedFile
) ) {
338 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
339 wfSuppressWarnings();
340 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
344 $wgOut->fileRenameError( $this->mSavedFile
,
345 "${archive}/{$this->mUploadOldVersion}" );
348 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
351 $this->mUploadOldVersion
= '';
354 wfSuppressWarnings();
355 $success = $useRename
356 ?
rename( $tempName, $this->mSavedFile
)
357 : move_uploaded_file( $tempName, $this->mSavedFile
);
361 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
364 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
367 chmod( $this->mSavedFile
, 0644 );
372 * Stash a file in a temporary directory for later processing
373 * after the user has confirmed it.
375 * If the user doesn't explicitly cancel or accept, these files
376 * can accumulate in the temp directory.
378 * @param string $saveName - the destination filename
379 * @param string $tempName - the source temporary file to save
380 * @return string - full path the stashed file, or false on failure
383 function saveTempUploadedFile( $saveName, $tempName ) {
385 $archive = wfImageArchiveDir( $saveName, 'temp' );
386 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
388 $success = $this->mRemoveTempFile
389 ?
rename( $tempName, $stash )
390 : move_uploaded_file( $tempName, $stash );
392 $wgOut->fileCopyError( $tempName, $stash );
400 * Stash a file in a temporary directory for later processing,
401 * and save the necessary descriptive info into the session.
402 * Returns a key value which will be passed through a form
403 * to pick up the path info on a later invocation.
408 function stashSession() {
409 $stash = $this->saveTempUploadedFile(
410 $this->mUploadSaveName
, $this->mUploadTempName
);
413 # Couldn't save the file.
417 $key = mt_rand( 0, 0x7fffffff );
418 $_SESSION['wsUploadData'][$key] = array(
419 'mUploadTempName' => $stash,
420 'mUploadSize' => $this->mUploadSize
,
421 'mOname' => $this->mOname
);
426 * Remove a temporarily kept file stashed by saveTempUploadedFile().
429 function unsaveUploadedFile() {
431 wfSuppressWarnings();
432 $success = unlink( $this->mUploadTempName
);
435 $wgOut->fileDeleteError( $this->mUploadTempName
);
439 /* -------------------------------------------------------------- */
442 * Show some text and linkage on successful upload.
445 function showSuccess() {
446 global $wgUser, $wgOut, $wgContLang;
448 $sk = $wgUser->getSkin();
449 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
450 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
451 $dlink = $sk->makeKnownLink( $dname, $dname );
453 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
454 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
455 $wgOut->addHTML( $text );
456 $wgOut->returnToMain( false );
460 * @param string $error as HTML
463 function uploadError( $error ) {
465 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
466 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
470 * There's something wrong with this file, not enough to reject it
471 * totally but we require manual intervention to save it for real.
472 * Stash it away, then present a form asking to confirm or cancel.
474 * @param string $warning as HTML
477 function uploadWarning( $warning ) {
478 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
479 global $wgUseCopyrightUpload;
481 $this->mSessionKey
= $this->stashSession();
482 if( !$this->mSessionKey
) {
483 # Couldn't save file; an error has been displayed so let's go.
487 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
488 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
490 $save = wfMsgHtml( 'savefile' );
491 $reupload = wfMsgHtml( 'reupload' );
492 $iw = wfMsgWikiHtml( 'ignorewarning' );
493 $reup = wfMsgWikiHtml( 'reuploaddesc' );
494 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
495 $action = $titleObj->escapeLocalURL( 'action=submit' );
497 if ( $wgUseCopyrightUpload )
500 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
501 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
508 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
509 <input type='hidden' name='wpIgnoreWarning' value='1' />
510 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
511 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
512 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
513 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
519 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
521 <td align='left'>$iw</td>
525 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
527 <td align='left'>$reup</td>
530 </table></form>\n" );
534 * Displays the main upload form, optionally with a highlighted
535 * error message up at the top.
537 * @param string $msg as HTML
540 function mainUploadForm( $msg='' ) {
541 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
542 global $wgUseCopyrightUpload;
544 $cols = intval($wgUser->getOption( 'cols' ));
545 $ew = $wgUser->getOption( 'editwidth' );
546 if ( $ew ) $ew = " style=\"width:100%\"";
550 $sub = wfMsgHtml( 'uploaderror' );
551 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
552 "<span class='error'>{$msg}</span>\n" );
554 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
555 $sk = $wgUser->getSkin();
558 $sourcefilename = wfMsgHtml( 'sourcefilename' );
559 $destfilename = wfMsgHtml( 'destfilename' );
560 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
562 $licenses = new Licenses();
563 $license = wfMsgHtml( 'license' );
564 $nolicense = wfMsgHtml( 'nolicense' );
565 $licenseshtml = $licenses->getHtml();
567 $ulb = wfMsgHtml( 'uploadbtn' );
570 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
571 $action = $titleObj->escapeLocalURL();
573 $encDestFile = htmlspecialchars( $this->mDestFile
);
576 if ( $wgUseCopyrightUpload )
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>
583 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
584 <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
585 htmlspecialchars($this->mUploadSource
). "\" size='40' /></td>
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' " . ($this->mDestFile?
"":"onchange='fillDestFilename()' ") . "size='40' />
597 <td align='right'>{$destfilename}:</td><td align='left'>
598 <input tabindex='1' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
601 <td align='right'>{$summary}</td><td align='left'>
602 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
603 . htmlspecialchars( $this->mUploadDescription
) .
607 if ( $licenseshtml != '' ) {
609 <td align='right'>$license:</td>
611 <select name='wpLicense'>
612 <option value=''>$nolicense</option>
618 $wgOut->addHtml( "{$source}
620 <tr><td></td><td align='left'>
621 <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
622 </td></tr></table></form>\n" );
625 /* -------------------------------------------------------------- */
628 * Split a file into a base name and all dot-delimited 'extensions'
629 * on the end. Some web server configurations will fall back to
630 * earlier pseudo-'extensions' to determine type and execute
631 * scripts, so the blacklist needs to check them all.
635 function splitExtensions( $filename ) {
636 $bits = explode( '.', $filename );
637 $basename = array_shift( $bits );
638 return array( $basename, $bits );
642 * Perform case-insensitive match against a list of file extensions.
643 * Returns true if the extension is in the list.
649 function checkFileExtension( $ext, $list ) {
650 return in_array( strtolower( $ext ), $list );
654 * Perform case-insensitive match against a list of file extensions.
655 * Returns true if any of the extensions are in the list.
661 function checkFileExtensionList( $ext, $list ) {
662 foreach( $ext as $e ) {
663 if( in_array( strtolower( $e ), $list ) ) {
671 * Verifies that it's ok to include the uploaded file
673 * @param string $tmpfile the full path of the temporary file to verify
674 * @param string $extension The filename extension that the file is to be served with
675 * @return mixed true of the file is verified, a WikiError object otherwise.
677 function verify( $tmpfile, $extension ) {
678 #magically determine mime type
679 $magic=& wfGetMimeMagic();
680 $mime= $magic->guessMimeType($tmpfile,false);
682 $fname= "SpecialUpload::verify";
684 #check mime type, if desired
685 global $wgVerifyMimeType;
686 if ($wgVerifyMimeType) {
688 #check mime type against file extension
689 if( !$this->verifyExtension( $mime, $extension ) ) {
690 return new WikiErrorMsg( 'uploadcorrupt' );
693 #check mime type blacklist
694 global $wgMimeTypeBlacklist;
695 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
696 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
697 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
701 #check for htmlish code and javascript
702 if( $this->detectScript ( $tmpfile, $mime ) ) {
703 return new WikiErrorMsg( 'uploadscripted' );
707 * Scan the uploaded file for viruses
709 $virus= $this->detectVirus($tmpfile);
711 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
714 wfDebug( "$fname: all clear; passing.\n" );
719 * Checks if the mime type of the uploaded file matches the file extension.
721 * @param string $mime the mime type of the uploaded file
722 * @param string $extension The filename extension that the file is to be served with
725 function verifyExtension( $mime, $extension ) {
726 $fname = 'SpecialUpload::verifyExtension';
728 if (!$mime ||
$mime=="unknown" ||
$mime=="unknown/unknown") {
729 wfDebug( "$fname: passing file with unknown mime type\n" );
733 $magic=& wfGetMimeMagic();
735 $match= $magic->isMatchingExtension($extension,$mime);
738 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
740 } elseif ($match===true) {
741 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
743 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
747 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
752 /** Heuristig for detecting files that *could* contain JavaScript instructions or
753 * things that may look like HTML to a browser and are thus
754 * potentially harmful. The present implementation will produce false positives in some situations.
756 * @param string $file Pathname to the temporary upload file
757 * @param string $mime The mime type of the file
758 * @return bool true if the file contains something looking like embedded scripts
760 function detectScript($file,$mime) {
762 #ugly hack: for text files, always look at the entire file.
763 #For binarie field, just check the first K.
765 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
767 $fp = fopen( $file, 'rb' );
768 $chunk = fread( $fp, 1024 );
772 $chunk= strtolower( $chunk );
774 if (!$chunk) return false;
776 #decode from UTF-16 if needed (could be used for obfuscation).
777 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
778 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
781 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
783 $chunk= trim($chunk);
785 #FIXME: convert from UTF-16 if necessarry!
787 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
789 #check for HTML doctype
790 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
793 * Internet Explorer for Windows performs some really stupid file type
794 * autodetection which can cause it to interpret valid image files as HTML
795 * and potentially execute JavaScript, creating a cross-site scripting
798 * Apple's Safari browser also performs some unsafe file type autodetection
799 * which can cause legitimate files to be interpreted as HTML if the
800 * web server is not correctly configured to send the right content-type
801 * (or if you're really uploading plain text and octet streams!)
803 * Returns true if IE is likely to mistake the given file for HTML.
804 * Also returns true if Safari would mistake the given file for HTML
805 * when served with a generic content-type.
811 '<html', #also in safari
814 '<script', #also in safari
816 '<title' #also in safari
819 foreach( $tags as $tag ) {
820 if( false !== strpos( $chunk, $tag ) ) {
826 * look for javascript
829 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
830 $chunk = Sanitizer
::decodeCharReferences( $chunk );
832 #look for script-types
833 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
835 #look for html-style script-urls
836 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
838 #look for css-style script-urls
839 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
841 wfDebug("SpecialUpload::detectScript: no scripts found\n");
845 /** Generic wrapper function for a virus scanner program.
846 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
847 * $wgAntivirusRequired may be used to deny upload if the scan fails.
849 * @param string $file Pathname to the temporary upload file
850 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
851 * or a string containing feedback from the virus scanner if a virus was found.
852 * If textual feedback is missing but a virus was found, this function returns true.
854 function detectVirus($file) {
855 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
857 $fname= "SpecialUpload::detectVirus";
859 if (!$wgAntivirus) { #disabled?
860 wfDebug("$fname: virus scanner disabled\n");
865 if (!$wgAntivirusSetup[$wgAntivirus]) {
866 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
868 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
870 return "unknown antivirus: $wgAntivirus";
873 #look up scanner configuration
874 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
875 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
876 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
878 $scanner= $virus_scanner; #copy, so we can resolve the pattern
880 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
881 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
883 wfDebug("$fname: running virus scan: $scanner \n");
885 #execute virus scanner
888 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
889 # that does not seem to be worth the pain.
890 # Ask me (Duesentrieb) about it if it's ever needed.
891 if (wfIsWindows()) exec("$scanner",$output,$code);
892 else exec("$scanner 2>&1",$output,$code);
894 $exit_code= $code; #remeber for user feedback
896 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
897 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
898 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
901 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
902 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
904 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
907 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
908 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
911 else if ($code===AV_NO_VIRUS
) {
912 wfDebug("$fname: file passed virus scan.\n");
913 return false; #no virus found
916 $output= join("\n",$output);
917 $output= trim($output);
919 if (!$output) $output= true; #if ther's no output, return true
920 else if ($msg_pattern) {
922 if (preg_match($msg_pattern,$output,$groups)) {
923 if ($groups[1]) $output= $groups[1];
927 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
933 * Check if the temporary file is MacBinary-encoded, as some uploads
934 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
935 * If so, the data fork will be extracted to a second temporary file,
936 * which will then be checked for validity and either kept or discarded.
940 function checkMacBinary() {
941 $macbin = new MacBinary( $this->mUploadTempName
);
942 if( $macbin->isValid() ) {
943 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
944 $dataHandle = fopen( $dataFile, 'wb' );
946 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
947 $macbin->extractData( $dataHandle );
949 $this->mUploadTempName
= $dataFile;
950 $this->mUploadSize
= $macbin->dataForkLength();
952 // We'll have to manually remove the new file if it's not kept.
953 $this->mRemoveTempFile
= true;
959 * If we've modified the upload file we need to manually remove it
960 * on exit to clean up.
963 function cleanupTempFile() {
964 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
965 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
966 unlink( $this->mUploadTempName
);
971 * Check if there's an overwrite conflict and, if so, if restrictions
972 * forbid this user from performing the upload.
974 * @return mixed true on success, WikiError on failure
977 function checkOverwrite( $name ) {
978 $img = Image
::newFromName( $name );
979 if( is_null( $img ) ) {
980 // Uh... this shouldn't happen ;)
981 // But if it does, fall through to previous behavior
986 if( $img->exists() ) {
987 global $wgUser, $wgOut;
988 if( $img->isLocal() ) {
989 if( !$wgUser->isAllowed( 'reupload' ) ) {
990 $error = 'fileexists-forbidden';
993 if( !$wgUser->isAllowed( 'reupload' ) ||
994 !$wgUser->isAllowed( 'reupload-shared' ) ) {
995 $error = "fileexists-shared-forbidden";
1001 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1002 return new WikiError( $wgOut->parse( $errorText ) );
1005 // Rockin', go ahead and upload