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 * Check for non-fatal conditions
239 if ( ! $this->mIgnoreWarning
) {
241 if( $this->mUploadSaveName
!= ucfirst( $filtered ) ) {
242 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
245 global $wgCheckFileExtensions;
246 if ( $wgCheckFileExtensions ) {
247 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
248 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
252 global $wgUploadSizeWarning;
253 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
254 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
255 # value, perhaps add GB,MB and KB suffixes?
256 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
258 if ( $this->mUploadSize
== 0 ) {
259 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
262 if( $nt->getArticleID() ) {
264 $sk = $wgUser->getSkin();
265 $dlink = $sk->makeKnownLinkObj( $nt );
266 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
269 if( $warning != '' ) {
271 * Stash the file in a temporary location; the user can choose
272 * to let it through and we'll complete the upload then.
274 return $this->uploadWarning( $warning );
279 * Try actually saving the thing...
280 * It will show an error form on failure.
282 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
283 if( $this->saveUploadedFile( $this->mUploadSaveName
,
284 $this->mUploadTempName
,
287 * Update the upload log and create the description page
288 * if it's a new file.
290 $img = Image
::newFromName( $this->mUploadSaveName
);
291 $success = $img->recordUpload( $this->mUploadOldVersion
,
292 $this->mUploadDescription
,
294 $this->mUploadCopyStatus
,
295 $this->mUploadSource
);
298 $this->showSuccess();
300 // Image::recordUpload() fails if the image went missing, which is
301 // unlikely, hence the lack of a specialised message
302 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
308 * Move the uploaded file from its temporary location to the final
309 * destination. If a previous version of the file exists, move
310 * it into the archive subdirectory.
312 * @todo If the later save fails, we may have disappeared the original file.
314 * @param string $saveName
315 * @param string $tempName full path to the temporary file
316 * @param bool $useRename if true, doesn't check that the source file
317 * is a PHP-managed upload temporary
319 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
320 global $wgUploadDirectory, $wgOut;
322 $fname= "SpecialUpload::saveUploadedFile";
324 $dest = wfImageDir( $saveName );
325 $archive = wfImageArchiveDir( $saveName );
326 $this->mSavedFile
= "{$dest}/{$saveName}";
328 if( is_file( $this->mSavedFile
) ) {
329 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
330 wfSuppressWarnings();
331 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
335 $wgOut->fileRenameError( $this->mSavedFile
,
336 "${archive}/{$this->mUploadOldVersion}" );
339 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
342 $this->mUploadOldVersion
= '';
345 wfSuppressWarnings();
346 $success = $useRename
347 ?
rename( $tempName, $this->mSavedFile
)
348 : move_uploaded_file( $tempName, $this->mSavedFile
);
352 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
355 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
358 chmod( $this->mSavedFile
, 0644 );
363 * Stash a file in a temporary directory for later processing
364 * after the user has confirmed it.
366 * If the user doesn't explicitly cancel or accept, these files
367 * can accumulate in the temp directory.
369 * @param string $saveName - the destination filename
370 * @param string $tempName - the source temporary file to save
371 * @return string - full path the stashed file, or false on failure
374 function saveTempUploadedFile( $saveName, $tempName ) {
376 $archive = wfImageArchiveDir( $saveName, 'temp' );
377 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
379 $success = $this->mRemoveTempFile
380 ?
rename( $tempName, $stash )
381 : move_uploaded_file( $tempName, $stash );
383 $wgOut->fileCopyError( $tempName, $stash );
391 * Stash a file in a temporary directory for later processing,
392 * and save the necessary descriptive info into the session.
393 * Returns a key value which will be passed through a form
394 * to pick up the path info on a later invocation.
399 function stashSession() {
400 $stash = $this->saveTempUploadedFile(
401 $this->mUploadSaveName
, $this->mUploadTempName
);
404 # Couldn't save the file.
408 $key = mt_rand( 0, 0x7fffffff );
409 $_SESSION['wsUploadData'][$key] = array(
410 'mUploadTempName' => $stash,
411 'mUploadSize' => $this->mUploadSize
,
412 'mOname' => $this->mOname
);
417 * Remove a temporarily kept file stashed by saveTempUploadedFile().
420 function unsaveUploadedFile() {
422 wfSuppressWarnings();
423 $success = unlink( $this->mUploadTempName
);
426 $wgOut->fileDeleteError( $this->mUploadTempName
);
430 /* -------------------------------------------------------------- */
433 * Show some text and linkage on successful upload.
436 function showSuccess() {
437 global $wgUser, $wgOut, $wgContLang;
439 $sk = $wgUser->getSkin();
440 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
441 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
442 $dlink = $sk->makeKnownLink( $dname, $dname );
444 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
445 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
446 $wgOut->addHTML( $text );
447 $wgOut->returnToMain( false );
451 * @param string $error as HTML
454 function uploadError( $error ) {
456 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
457 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
461 * There's something wrong with this file, not enough to reject it
462 * totally but we require manual intervention to save it for real.
463 * Stash it away, then present a form asking to confirm or cancel.
465 * @param string $warning as HTML
468 function uploadWarning( $warning ) {
469 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
470 global $wgUseCopyrightUpload;
472 $this->mSessionKey
= $this->stashSession();
473 if( !$this->mSessionKey
) {
474 # Couldn't save file; an error has been displayed so let's go.
478 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
479 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
481 $save = wfMsgHtml( 'savefile' );
482 $reupload = wfMsgHtml( 'reupload' );
483 $iw = wfMsgWikiHtml( 'ignorewarning' );
484 $reup = wfMsgWikiHtml( 'reuploaddesc' );
485 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
486 $action = $titleObj->escapeLocalURL( 'action=submit' );
488 if ( $wgUseCopyrightUpload )
491 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
492 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
499 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
500 <input type='hidden' name='wpIgnoreWarning' value='1' />
501 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
502 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
503 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
504 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
510 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
512 <td align='left'>$iw</td>
516 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
518 <td align='left'>$reup</td>
521 </table></form>\n" );
525 * Displays the main upload form, optionally with a highlighted
526 * error message up at the top.
528 * @param string $msg as HTML
531 function mainUploadForm( $msg='' ) {
532 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
533 global $wgUseCopyrightUpload;
535 $cols = intval($wgUser->getOption( 'cols' ));
536 $ew = $wgUser->getOption( 'editwidth' );
537 if ( $ew ) $ew = " style=\"width:100%\"";
541 $sub = wfMsgHtml( 'uploaderror' );
542 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
543 "<span class='error'>{$msg}</span>\n" );
545 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
546 $sk = $wgUser->getSkin();
549 $sourcefilename = wfMsgHtml( 'sourcefilename' );
550 $destfilename = wfMsgHtml( 'destfilename' );
551 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
553 $licenses = new Licenses();
554 $license = wfMsgHtml( 'license' );
555 $nolicense = wfMsgHtml( 'nolicense' );
556 $licenseshtml = $licenses->getHtml();
558 $ulb = wfMsgHtml( 'uploadbtn' );
561 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
562 $action = $titleObj->escapeLocalURL();
564 $encDestFile = htmlspecialchars( $this->mDestFile
);
567 if ( $wgUseCopyrightUpload )
570 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
571 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
572 htmlspecialchars($this->mUploadCopyStatus
). "\" size='40' /></td>
574 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
575 <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
576 htmlspecialchars($this->mUploadSource
). "\" size='40' /></td>
581 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
582 <table border='0'><tr>
584 <td align='right'>{$sourcefilename}:</td><td align='left'>
585 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?
"":"onchange='fillDestFilename()' ") . "size='40' />
588 <td align='right'>{$destfilename}:</td><td align='left'>
589 <input tabindex='1' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
592 <td align='right'>{$summary}</td><td align='left'>
593 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
594 . htmlspecialchars( $this->mUploadDescription
) .
598 if ( $licenseshtml != '' ) {
600 <td align='right'>$license:</td>
602 <select name='wpLicense'>
603 <option value=''>$nolicense</option>
609 $wgOut->addHtml( "{$source}
611 <tr><td></td><td align='left'>
612 <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
613 </td></tr></table></form>\n" );
616 /* -------------------------------------------------------------- */
619 * Split a file into a base name and all dot-delimited 'extensions'
620 * on the end. Some web server configurations will fall back to
621 * earlier pseudo-'extensions' to determine type and execute
622 * scripts, so the blacklist needs to check them all.
626 function splitExtensions( $filename ) {
627 $bits = explode( '.', $filename );
628 $basename = array_shift( $bits );
629 return array( $basename, $bits );
633 * Perform case-insensitive match against a list of file extensions.
634 * Returns true if the extension is in the list.
640 function checkFileExtension( $ext, $list ) {
641 return in_array( strtolower( $ext ), $list );
645 * Perform case-insensitive match against a list of file extensions.
646 * Returns true if any of the extensions are in the list.
652 function checkFileExtensionList( $ext, $list ) {
653 foreach( $ext as $e ) {
654 if( in_array( strtolower( $e ), $list ) ) {
662 * Verifies that it's ok to include the uploaded file
664 * @param string $tmpfile the full path of the temporary file to verify
665 * @param string $extension The filename extension that the file is to be served with
666 * @return mixed true of the file is verified, a WikiError object otherwise.
668 function verify( $tmpfile, $extension ) {
669 #magically determine mime type
670 $magic=& wfGetMimeMagic();
671 $mime= $magic->guessMimeType($tmpfile,false);
673 $fname= "SpecialUpload::verify";
675 #check mime type, if desired
676 global $wgVerifyMimeType;
677 if ($wgVerifyMimeType) {
679 #check mime type against file extension
680 if( !$this->verifyExtension( $mime, $extension ) ) {
681 return new WikiErrorMsg( 'uploadcorrupt' );
684 #check mime type blacklist
685 global $wgMimeTypeBlacklist;
686 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
687 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
688 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
692 #check for htmlish code and javascript
693 if( $this->detectScript ( $tmpfile, $mime ) ) {
694 return new WikiErrorMsg( 'uploadscripted' );
698 * Scan the uploaded file for viruses
700 $virus= $this->detectVirus($tmpfile);
702 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
705 wfDebug( "$fname: all clear; passing.\n" );
710 * Checks if the mime type of the uploaded file matches the file extension.
712 * @param string $mime the mime type of the uploaded file
713 * @param string $extension The filename extension that the file is to be served with
716 function verifyExtension( $mime, $extension ) {
717 $fname = 'SpecialUpload::verifyExtension';
719 if (!$mime ||
$mime=="unknown" ||
$mime=="unknown/unknown") {
720 wfDebug( "$fname: passing file with unknown mime type\n" );
724 $magic=& wfGetMimeMagic();
726 $match= $magic->isMatchingExtension($extension,$mime);
729 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
731 } elseif ($match===true) {
732 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
734 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
738 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
743 /** Heuristig for detecting files that *could* contain JavaScript instructions or
744 * things that may look like HTML to a browser and are thus
745 * potentially harmful. The present implementation will produce false positives in some situations.
747 * @param string $file Pathname to the temporary upload file
748 * @param string $mime The mime type of the file
749 * @return bool true if the file contains something looking like embedded scripts
751 function detectScript($file,$mime) {
753 #ugly hack: for text files, always look at the entire file.
754 #For binarie field, just check the first K.
756 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
758 $fp = fopen( $file, 'rb' );
759 $chunk = fread( $fp, 1024 );
763 $chunk= strtolower( $chunk );
765 if (!$chunk) return false;
767 #decode from UTF-16 if needed (could be used for obfuscation).
768 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
769 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
772 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
774 $chunk= trim($chunk);
776 #FIXME: convert from UTF-16 if necessarry!
778 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
780 #check for HTML doctype
781 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
784 * Internet Explorer for Windows performs some really stupid file type
785 * autodetection which can cause it to interpret valid image files as HTML
786 * and potentially execute JavaScript, creating a cross-site scripting
789 * Apple's Safari browser also performs some unsafe file type autodetection
790 * which can cause legitimate files to be interpreted as HTML if the
791 * web server is not correctly configured to send the right content-type
792 * (or if you're really uploading plain text and octet streams!)
794 * Returns true if IE is likely to mistake the given file for HTML.
795 * Also returns true if Safari would mistake the given file for HTML
796 * when served with a generic content-type.
802 '<html', #also in safari
805 '<script', #also in safari
807 '<title' #also in safari
810 foreach( $tags as $tag ) {
811 if( false !== strpos( $chunk, $tag ) ) {
817 * look for javascript
820 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
821 $chunk = Sanitizer
::decodeCharReferences( $chunk );
823 #look for script-types
824 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
826 #look for html-style script-urls
827 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
829 #look for css-style script-urls
830 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
832 wfDebug("SpecialUpload::detectScript: no scripts found\n");
836 /** Generic wrapper function for a virus scanner program.
837 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
838 * $wgAntivirusRequired may be used to deny upload if the scan fails.
840 * @param string $file Pathname to the temporary upload file
841 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
842 * or a string containing feedback from the virus scanner if a virus was found.
843 * If textual feedback is missing but a virus was found, this function returns true.
845 function detectVirus($file) {
846 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
848 $fname= "SpecialUpload::detectVirus";
850 if (!$wgAntivirus) { #disabled?
851 wfDebug("$fname: virus scanner disabled\n");
856 if (!$wgAntivirusSetup[$wgAntivirus]) {
857 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
859 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
861 return "unknown antivirus: $wgAntivirus";
864 #look up scanner configuration
865 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
866 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
867 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
869 $scanner= $virus_scanner; #copy, so we can resolve the pattern
871 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
872 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
874 wfDebug("$fname: running virus scan: $scanner \n");
876 #execute virus scanner
879 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
880 # that does not seem to be worth the pain.
881 # Ask me (Duesentrieb) about it if it's ever needed.
882 if (wfIsWindows()) exec("$scanner",$output,$code);
883 else exec("$scanner 2>&1",$output,$code);
885 $exit_code= $code; #remeber for user feedback
887 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
888 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
889 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
892 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
893 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
895 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
898 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
899 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
902 else if ($code===AV_NO_VIRUS
) {
903 wfDebug("$fname: file passed virus scan.\n");
904 return false; #no virus found
907 $output= join("\n",$output);
908 $output= trim($output);
910 if (!$output) $output= true; #if ther's no output, return true
911 else if ($msg_pattern) {
913 if (preg_match($msg_pattern,$output,$groups)) {
914 if ($groups[1]) $output= $groups[1];
918 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
924 * Check if the temporary file is MacBinary-encoded, as some uploads
925 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
926 * If so, the data fork will be extracted to a second temporary file,
927 * which will then be checked for validity and either kept or discarded.
931 function checkMacBinary() {
932 $macbin = new MacBinary( $this->mUploadTempName
);
933 if( $macbin->isValid() ) {
934 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
935 $dataHandle = fopen( $dataFile, 'wb' );
937 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
938 $macbin->extractData( $dataHandle );
940 $this->mUploadTempName
= $dataFile;
941 $this->mUploadSize
= $macbin->dataForkLength();
943 // We'll have to manually remove the new file if it's not kept.
944 $this->mRemoveTempFile
= true;
950 * If we've modified the upload file we need to manually remove it
951 * on exit to clean up.
954 function cleanupTempFile() {
955 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
956 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
957 unlink( $this->mUploadTempName
);
962 * Check if there's an overwrite conflict and, if so, if restrictions
963 * forbid this user from performing the upload.
965 * @return mixed true on success, WikiError on failure
968 function checkOverwrite( $name ) {
969 $img = Image
::newFromName( $name );
970 if( is_null( $img ) ) {
971 // Uh... this shouldn't happen ;)
972 // But if it does, fall through to previous behavior
977 if( $img->exists() ) {
978 global $wgUser, $wgOut;
979 if( $img->isLocal() ) {
980 if( !$wgUser->isAllowed( 'reupload' ) ) {
981 $error = 'fileexists-forbidden';
984 if( !$wgUser->isAllowed( 'reupload' ) ||
985 !$wgUser->isAllowed( 'reupload-shared' ) ) {
986 $error = "fileexists-shared-forbidden";
992 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
993 return new WikiError( $wgOut->parse( $errorText ) );
996 // Rockin', go ahead and upload