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' );
59 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
60 wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
62 $this->mAction
= $request->getVal( 'action' );
64 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
65 if( !empty( $this->mSessionKey
) &&
66 isset( $_SESSION['wsUploadData'][$this->mSessionKey
] ) ) {
68 * Confirming a temporarily stashed upload.
69 * We don't want path names to be forged, so we keep
70 * them in the session on the server and just give
71 * an opaque key to the user agent.
73 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
74 $this->mUploadTempName
= $data['mUploadTempName'];
75 $this->mUploadSize
= $data['mUploadSize'];
76 $this->mOname
= $data['mOname'];
77 $this->mUploadError
= 0/*UPLOAD_ERR_OK*/;
78 $this->mStashed
= true;
79 $this->mRemoveTempFile
= false;
82 *Check for a newly uploaded file.
84 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
85 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
86 $this->mOname
= $request->getFileName( 'wpUploadFile' );
87 $this->mUploadError
= $request->getUploadError( 'wpUploadFile' );
88 $this->mSessionKey
= false;
89 $this->mStashed
= false;
90 $this->mRemoveTempFile
= false; // PHP will handle this
99 global $wgUser, $wgOut;
100 global $wgEnableUploads, $wgUploadDirectory;
102 # Check uploading enabled
103 if( !$wgEnableUploads ) {
104 $wgOut->errorPage( 'uploaddisabled', 'uploaddisabledtext' );
109 if( $wgUser->isLoggedIn() ) {
110 if( !$wgUser->isAllowed( 'upload' ) ) {
111 $wgOut->permissionRequired( 'upload' );
115 $wgOut->errorPage( 'uploadnologin', 'uploadnologintext' );
120 if( $wgUser->isBlocked() ) {
121 $wgOut->blockedPage();
126 $wgOut->readOnlyPage();
130 /** Check if the image directory is writeable, this is a common mistake */
131 if ( !is_writeable( $wgUploadDirectory ) ) {
132 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
136 if( $this->mReUpload
) {
137 $this->unsaveUploadedFile();
138 $this->mainUploadForm();
139 } else if ( 'submit' == $this->mAction ||
$this->mUpload
) {
140 $this->processUpload();
142 $this->mainUploadForm();
145 $this->cleanupTempFile();
148 /* -------------------------------------------------------------- */
151 * Really do the upload
152 * Checks are made in SpecialUpload::execute()
155 function processUpload() {
156 global $wgUser, $wgOut;
158 /* Check for PHP error if any, requires php 4.2 or newer */
159 if ( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
160 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
165 * If there was no filename or a zero size given, give up quick.
167 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
168 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
172 # Chop off any directories in the given filename
173 if ( $this->mDestFile
) {
174 $basename = wfBaseName( $this->mDestFile
);
176 $basename = wfBaseName( $this->mOname
);
180 * We'll want to blacklist against *any* 'extension', and use
181 * only the final one for the whitelist.
183 list( $partname, $ext ) = $this->splitExtensions( $basename );
184 if( count( $ext ) ) {
185 $finalExt = $ext[count( $ext ) - 1];
189 $fullExt = implode( '.', $ext );
191 if ( strlen( $partname ) < 3 ) {
192 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
197 * Filter out illegal characters, and try to make a legible name
198 * out of it. We'll strip some silently that Title would die on.
200 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
201 $nt = Title
::newFromText( $filtered );
202 if( is_null( $nt ) ) {
203 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
206 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
207 $this->mUploadSaveName
= $nt->getDBkey();
210 * If the image is protected, non-sysop users won't be able
211 * to modify it by uploading a new revision.
213 if( !$nt->userCanEdit() ) {
214 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
218 * In some cases we may forbid overwriting of existing files.
220 $overwrite = $this->checkOverwrite( $this->mUploadSaveName
);
221 if( WikiError
::isError( $overwrite ) ) {
222 return $this->uploadError( $overwrite->toString() );
225 /* Don't allow users to override the blacklist (check file extension) */
226 global $wgStrictFileExtensions;
227 global $wgFileExtensions, $wgFileBlacklist;
228 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
229 ($wgStrictFileExtensions &&
230 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
231 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
235 * Look at the contents of the file; if we can recognize the
236 * type but it's corrupt or data of the wrong type, we should
237 * probably not accept it.
239 if( !$this->mStashed
) {
240 $this->checkMacBinary();
241 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
243 if( $veri !== true ) { //it's a wiki error...
244 return $this->uploadError( $veri->toString() );
249 * Provide an opportunity for extensions to add futher checks
252 if( !wfRunHooks( 'UploadVerification',
253 array( $this->mUploadSaveName
, $this->mUploadTempName
, &$error ) ) ) {
254 return $this->uploadError( $error );
258 * Check for non-fatal conditions
260 if ( ! $this->mIgnoreWarning
) {
263 global $wgCapitalLinks;
264 if( $wgCapitalLinks ) {
265 $filtered = ucfirst( $filtered );
267 if( $this->mUploadSaveName
!= $filtered ) {
268 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
271 global $wgCheckFileExtensions;
272 if ( $wgCheckFileExtensions ) {
273 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
274 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
278 global $wgUploadSizeWarning;
279 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
280 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
281 # value, perhaps add GB,MB and KB suffixes?
282 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
284 if ( $this->mUploadSize
== 0 ) {
285 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
288 if( $nt->getArticleID() ) {
290 $sk = $wgUser->getSkin();
291 $dlink = $sk->makeKnownLinkObj( $nt );
292 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
295 if( $warning != '' ) {
297 * Stash the file in a temporary location; the user can choose
298 * to let it through and we'll complete the upload then.
300 return $this->uploadWarning( $warning );
305 * Try actually saving the thing...
306 * It will show an error form on failure.
308 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
309 if( $this->saveUploadedFile( $this->mUploadSaveName
,
310 $this->mUploadTempName
,
313 * Update the upload log and create the description page
314 * if it's a new file.
316 $img = Image
::newFromName( $this->mUploadSaveName
);
317 $success = $img->recordUpload( $this->mUploadOldVersion
,
318 $this->mUploadDescription
,
320 $this->mUploadCopyStatus
,
321 $this->mUploadSource
,
325 $this->showSuccess();
327 // Image::recordUpload() fails if the image went missing, which is
328 // unlikely, hence the lack of a specialised message
329 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
335 * Move the uploaded file from its temporary location to the final
336 * destination. If a previous version of the file exists, move
337 * it into the archive subdirectory.
339 * @todo If the later save fails, we may have disappeared the original file.
341 * @param string $saveName
342 * @param string $tempName full path to the temporary file
343 * @param bool $useRename if true, doesn't check that the source file
344 * is a PHP-managed upload temporary
346 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
349 $fname= "SpecialUpload::saveUploadedFile";
351 $dest = wfImageDir( $saveName );
352 $archive = wfImageArchiveDir( $saveName );
353 $this->mSavedFile
= "{$dest}/{$saveName}";
355 if( is_file( $this->mSavedFile
) ) {
356 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
357 wfSuppressWarnings();
358 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
362 $wgOut->fileRenameError( $this->mSavedFile
,
363 "${archive}/{$this->mUploadOldVersion}" );
366 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
369 $this->mUploadOldVersion
= '';
372 wfSuppressWarnings();
373 $success = $useRename
374 ?
rename( $tempName, $this->mSavedFile
)
375 : move_uploaded_file( $tempName, $this->mSavedFile
);
379 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
382 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
385 chmod( $this->mSavedFile
, 0644 );
390 * Stash a file in a temporary directory for later processing
391 * after the user has confirmed it.
393 * If the user doesn't explicitly cancel or accept, these files
394 * can accumulate in the temp directory.
396 * @param string $saveName - the destination filename
397 * @param string $tempName - the source temporary file to save
398 * @return string - full path the stashed file, or false on failure
401 function saveTempUploadedFile( $saveName, $tempName ) {
403 $archive = wfImageArchiveDir( $saveName, 'temp' );
404 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
406 $success = $this->mRemoveTempFile
407 ?
rename( $tempName, $stash )
408 : move_uploaded_file( $tempName, $stash );
410 $wgOut->fileCopyError( $tempName, $stash );
418 * Stash a file in a temporary directory for later processing,
419 * and save the necessary descriptive info into the session.
420 * Returns a key value which will be passed through a form
421 * to pick up the path info on a later invocation.
426 function stashSession() {
427 $stash = $this->saveTempUploadedFile(
428 $this->mUploadSaveName
, $this->mUploadTempName
);
431 # Couldn't save the file.
435 $key = mt_rand( 0, 0x7fffffff );
436 $_SESSION['wsUploadData'][$key] = array(
437 'mUploadTempName' => $stash,
438 'mUploadSize' => $this->mUploadSize
,
439 'mOname' => $this->mOname
);
444 * Remove a temporarily kept file stashed by saveTempUploadedFile().
447 function unsaveUploadedFile() {
449 wfSuppressWarnings();
450 $success = unlink( $this->mUploadTempName
);
453 $wgOut->fileDeleteError( $this->mUploadTempName
);
457 /* -------------------------------------------------------------- */
460 * Show some text and linkage on successful upload.
463 function showSuccess() {
464 global $wgUser, $wgOut, $wgContLang;
466 $sk = $wgUser->getSkin();
467 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
468 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
469 $dlink = $sk->makeKnownLink( $dname, $dname );
471 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
472 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
473 $wgOut->addHTML( $text );
474 $wgOut->returnToMain( false );
478 * @param string $error as HTML
481 function uploadError( $error ) {
483 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
484 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
488 * There's something wrong with this file, not enough to reject it
489 * totally but we require manual intervention to save it for real.
490 * Stash it away, then present a form asking to confirm or cancel.
492 * @param string $warning as HTML
495 function uploadWarning( $warning ) {
497 global $wgUseCopyrightUpload;
499 $this->mSessionKey
= $this->stashSession();
500 if( !$this->mSessionKey
) {
501 # Couldn't save file; an error has been displayed so let's go.
505 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
506 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
508 $save = wfMsgHtml( 'savefile' );
509 $reupload = wfMsgHtml( 'reupload' );
510 $iw = wfMsgWikiHtml( 'ignorewarning' );
511 $reup = wfMsgWikiHtml( 'reuploaddesc' );
512 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
513 $action = $titleObj->escapeLocalURL( 'action=submit' );
515 if ( $wgUseCopyrightUpload )
518 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
519 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
526 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
527 <input type='hidden' name='wpIgnoreWarning' value='1' />
528 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
529 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
530 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
531 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
532 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
538 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
540 <td align='left'>$iw</td>
544 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
546 <td align='left'>$reup</td>
549 </table></form>\n" );
553 * Displays the main upload form, optionally with a highlighted
554 * error message up at the top.
556 * @param string $msg as HTML
559 function mainUploadForm( $msg='' ) {
560 global $wgOut, $wgUser;
561 global $wgUseCopyrightUpload;
563 $cols = intval($wgUser->getOption( 'cols' ));
564 $ew = $wgUser->getOption( 'editwidth' );
565 if ( $ew ) $ew = " style=\"width:100%\"";
569 $sub = wfMsgHtml( 'uploaderror' );
570 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
571 "<span class='error'>{$msg}</span>\n" );
573 $wgOut->addHTML( '<div id="uploadtext">' );
574 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
575 $wgOut->addHTML( '</div>' );
576 $sk = $wgUser->getSkin();
579 $sourcefilename = wfMsgHtml( 'sourcefilename' );
580 $destfilename = wfMsgHtml( 'destfilename' );
581 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
583 $licenses = new Licenses();
584 $license = wfMsgHtml( 'license' );
585 $nolicense = wfMsgHtml( 'nolicense' );
586 $licenseshtml = $licenses->getHtml();
588 $ulb = wfMsgHtml( 'uploadbtn' );
591 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
592 $action = $titleObj->escapeLocalURL();
594 $encDestFile = htmlspecialchars( $this->mDestFile
);
596 $watchChecked = $wgUser->getOption( 'watchdefault' )
597 ?
'checked="checked"'
601 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
604 <td align='right'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
606 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?
"":"onchange='fillDestFilename()' ") . "size='40' />
610 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
612 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
616 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
618 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
623 if ( $licenseshtml != '' ) {
626 <td align='right'><label for='wpLicense'>$license:</label></td>
628 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
629 <select name='wpLicense' id='wpLicense' tabindex='4'
630 onchange='licenseSelectorCheck()'>
631 <option value=''>$nolicense</option>
640 if ( $wgUseCopyrightUpload ) {
641 $filestatus = wfMsgHtml ( 'filestatus' );
642 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
643 $filesource = wfMsgHtml ( 'filesource' );
644 $uploadsource = htmlspecialchars( $this->mUploadSource
);
647 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
648 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
651 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
652 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
662 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
663 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
664 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
665 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
673 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
680 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
689 /* -------------------------------------------------------------- */
692 * Split a file into a base name and all dot-delimited 'extensions'
693 * on the end. Some web server configurations will fall back to
694 * earlier pseudo-'extensions' to determine type and execute
695 * scripts, so the blacklist needs to check them all.
699 function splitExtensions( $filename ) {
700 $bits = explode( '.', $filename );
701 $basename = array_shift( $bits );
702 return array( $basename, $bits );
706 * Perform case-insensitive match against a list of file extensions.
707 * Returns true if the extension is in the list.
713 function checkFileExtension( $ext, $list ) {
714 return in_array( strtolower( $ext ), $list );
718 * Perform case-insensitive match against a list of file extensions.
719 * Returns true if any of the extensions are in the list.
725 function checkFileExtensionList( $ext, $list ) {
726 foreach( $ext as $e ) {
727 if( in_array( strtolower( $e ), $list ) ) {
735 * Verifies that it's ok to include the uploaded file
737 * @param string $tmpfile the full path of the temporary file to verify
738 * @param string $extension The filename extension that the file is to be served with
739 * @return mixed true of the file is verified, a WikiError object otherwise.
741 function verify( $tmpfile, $extension ) {
742 #magically determine mime type
743 $magic=& wfGetMimeMagic();
744 $mime= $magic->guessMimeType($tmpfile,false);
746 $fname= "SpecialUpload::verify";
748 #check mime type, if desired
749 global $wgVerifyMimeType;
750 if ($wgVerifyMimeType) {
752 #check mime type against file extension
753 if( !$this->verifyExtension( $mime, $extension ) ) {
754 return new WikiErrorMsg( 'uploadcorrupt' );
757 #check mime type blacklist
758 global $wgMimeTypeBlacklist;
759 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
760 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
761 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
765 #check for htmlish code and javascript
766 if( $this->detectScript ( $tmpfile, $mime ) ) {
767 return new WikiErrorMsg( 'uploadscripted' );
771 * Scan the uploaded file for viruses
773 $virus= $this->detectVirus($tmpfile);
775 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
778 wfDebug( "$fname: all clear; passing.\n" );
783 * Checks if the mime type of the uploaded file matches the file extension.
785 * @param string $mime the mime type of the uploaded file
786 * @param string $extension The filename extension that the file is to be served with
789 function verifyExtension( $mime, $extension ) {
790 $fname = 'SpecialUpload::verifyExtension';
792 $magic =& wfGetMimeMagic();
794 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
795 if ( ! $magic->isRecognizableExtension( $extension ) ) {
796 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
799 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
803 $match= $magic->isMatchingExtension($extension,$mime);
806 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
808 } elseif ($match===true) {
809 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
811 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
815 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
820 /** Heuristig for detecting files that *could* contain JavaScript instructions or
821 * things that may look like HTML to a browser and are thus
822 * potentially harmful. The present implementation will produce false positives in some situations.
824 * @param string $file Pathname to the temporary upload file
825 * @param string $mime The mime type of the file
826 * @return bool true if the file contains something looking like embedded scripts
828 function detectScript($file,$mime) {
830 #ugly hack: for text files, always look at the entire file.
831 #For binarie field, just check the first K.
833 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
835 $fp = fopen( $file, 'rb' );
836 $chunk = fread( $fp, 1024 );
840 $chunk= strtolower( $chunk );
842 if (!$chunk) return false;
844 #decode from UTF-16 if needed (could be used for obfuscation).
845 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
846 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
849 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
851 $chunk= trim($chunk);
853 #FIXME: convert from UTF-16 if necessarry!
855 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
857 #check for HTML doctype
858 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
861 * Internet Explorer for Windows performs some really stupid file type
862 * autodetection which can cause it to interpret valid image files as HTML
863 * and potentially execute JavaScript, creating a cross-site scripting
866 * Apple's Safari browser also performs some unsafe file type autodetection
867 * which can cause legitimate files to be interpreted as HTML if the
868 * web server is not correctly configured to send the right content-type
869 * (or if you're really uploading plain text and octet streams!)
871 * Returns true if IE is likely to mistake the given file for HTML.
872 * Also returns true if Safari would mistake the given file for HTML
873 * when served with a generic content-type.
879 '<html', #also in safari
882 '<script', #also in safari
884 '<title' #also in safari
887 foreach( $tags as $tag ) {
888 if( false !== strpos( $chunk, $tag ) ) {
894 * look for javascript
897 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
898 $chunk = Sanitizer
::decodeCharReferences( $chunk );
900 #look for script-types
901 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
903 #look for html-style script-urls
904 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
906 #look for css-style script-urls
907 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
909 wfDebug("SpecialUpload::detectScript: no scripts found\n");
913 /** Generic wrapper function for a virus scanner program.
914 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
915 * $wgAntivirusRequired may be used to deny upload if the scan fails.
917 * @param string $file Pathname to the temporary upload file
918 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
919 * or a string containing feedback from the virus scanner if a virus was found.
920 * If textual feedback is missing but a virus was found, this function returns true.
922 function detectVirus($file) {
923 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
925 $fname= "SpecialUpload::detectVirus";
927 if (!$wgAntivirus) { #disabled?
928 wfDebug("$fname: virus scanner disabled\n");
933 if (!$wgAntivirusSetup[$wgAntivirus]) {
934 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
936 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
938 return "unknown antivirus: $wgAntivirus";
941 #look up scanner configuration
942 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
943 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
944 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
946 $scanner= $virus_scanner; #copy, so we can resolve the pattern
948 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
949 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
951 wfDebug("$fname: running virus scan: $scanner \n");
953 #execute virus scanner
956 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
957 # that does not seem to be worth the pain.
958 # Ask me (Duesentrieb) about it if it's ever needed.
959 if (wfIsWindows()) exec("$scanner",$output,$code);
960 else exec("$scanner 2>&1",$output,$code);
962 $exit_code= $code; #remeber for user feedback
964 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
965 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
966 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
969 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
970 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
972 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
975 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
976 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
979 else if ($code===AV_NO_VIRUS
) {
980 wfDebug("$fname: file passed virus scan.\n");
981 return false; #no virus found
984 $output= join("\n",$output);
985 $output= trim($output);
987 if (!$output) $output= true; #if ther's no output, return true
988 else if ($msg_pattern) {
990 if (preg_match($msg_pattern,$output,$groups)) {
991 if ($groups[1]) $output= $groups[1];
995 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1001 * Check if the temporary file is MacBinary-encoded, as some uploads
1002 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1003 * If so, the data fork will be extracted to a second temporary file,
1004 * which will then be checked for validity and either kept or discarded.
1008 function checkMacBinary() {
1009 $macbin = new MacBinary( $this->mUploadTempName
);
1010 if( $macbin->isValid() ) {
1011 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1012 $dataHandle = fopen( $dataFile, 'wb' );
1014 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1015 $macbin->extractData( $dataHandle );
1017 $this->mUploadTempName
= $dataFile;
1018 $this->mUploadSize
= $macbin->dataForkLength();
1020 // We'll have to manually remove the new file if it's not kept.
1021 $this->mRemoveTempFile
= true;
1027 * If we've modified the upload file we need to manually remove it
1028 * on exit to clean up.
1031 function cleanupTempFile() {
1032 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1033 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1034 unlink( $this->mUploadTempName
);
1039 * Check if there's an overwrite conflict and, if so, if restrictions
1040 * forbid this user from performing the upload.
1042 * @return mixed true on success, WikiError on failure
1045 function checkOverwrite( $name ) {
1046 $img = Image
::newFromName( $name );
1047 if( is_null( $img ) ) {
1048 // Uh... this shouldn't happen ;)
1049 // But if it does, fall through to previous behavior
1054 if( $img->exists() ) {
1055 global $wgUser, $wgOut;
1056 if( $img->isLocal() ) {
1057 if( !$wgUser->isAllowed( 'reupload' ) ) {
1058 $error = 'fileexists-forbidden';
1061 if( !$wgUser->isAllowed( 'reupload' ) ||
1062 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1063 $error = "fileexists-shared-forbidden";
1069 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1070 return new WikiError( $wgOut->parse( $errorText ) );
1073 // Rockin', go ahead and upload