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 /** Show an error message if file upload is disabled */
103 if( ! $wgEnableUploads ) {
104 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
108 /** Various rights checks */
109 if( !$wgUser->isAllowed( 'upload' ) ||
$wgUser->isBlocked() ) {
110 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
114 $wgOut->readOnlyPage();
118 /** Check if the image directory is writeable, this is a common mistake */
119 if ( !is_writeable( $wgUploadDirectory ) ) {
120 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
124 if( $this->mReUpload
) {
125 $this->unsaveUploadedFile();
126 $this->mainUploadForm();
127 } else if ( 'submit' == $this->mAction ||
$this->mUpload
) {
128 $this->processUpload();
130 $this->mainUploadForm();
133 $this->cleanupTempFile();
136 /* -------------------------------------------------------------- */
139 * Really do the upload
140 * Checks are made in SpecialUpload::execute()
143 function processUpload() {
144 global $wgUser, $wgOut, $wgUploadDirectory;
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
) {
251 global $wgCapitalLinks;
252 if( $wgCapitalLinks ) {
253 $filtered = ucfirst( $filtered );
255 if( $this->mUploadSaveName
!= $filtered ) {
256 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
259 global $wgCheckFileExtensions;
260 if ( $wgCheckFileExtensions ) {
261 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
262 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
266 global $wgUploadSizeWarning;
267 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
268 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
269 # value, perhaps add GB,MB and KB suffixes?
270 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
272 if ( $this->mUploadSize
== 0 ) {
273 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
276 if( $nt->getArticleID() ) {
278 $sk = $wgUser->getSkin();
279 $dlink = $sk->makeKnownLinkObj( $nt );
280 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
283 if( $warning != '' ) {
285 * Stash the file in a temporary location; the user can choose
286 * to let it through and we'll complete the upload then.
288 return $this->uploadWarning( $warning );
293 * Try actually saving the thing...
294 * It will show an error form on failure.
296 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
297 if( $this->saveUploadedFile( $this->mUploadSaveName
,
298 $this->mUploadTempName
,
301 * Update the upload log and create the description page
302 * if it's a new file.
304 $img = Image
::newFromName( $this->mUploadSaveName
);
305 $success = $img->recordUpload( $this->mUploadOldVersion
,
306 $this->mUploadDescription
,
308 $this->mUploadCopyStatus
,
309 $this->mUploadSource
,
313 $this->showSuccess();
315 // Image::recordUpload() fails if the image went missing, which is
316 // unlikely, hence the lack of a specialised message
317 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
323 * Move the uploaded file from its temporary location to the final
324 * destination. If a previous version of the file exists, move
325 * it into the archive subdirectory.
327 * @todo If the later save fails, we may have disappeared the original file.
329 * @param string $saveName
330 * @param string $tempName full path to the temporary file
331 * @param bool $useRename if true, doesn't check that the source file
332 * is a PHP-managed upload temporary
334 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
335 global $wgUploadDirectory, $wgOut;
337 $fname= "SpecialUpload::saveUploadedFile";
339 $dest = wfImageDir( $saveName );
340 $archive = wfImageArchiveDir( $saveName );
341 $this->mSavedFile
= "{$dest}/{$saveName}";
343 if( is_file( $this->mSavedFile
) ) {
344 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
345 wfSuppressWarnings();
346 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
350 $wgOut->fileRenameError( $this->mSavedFile
,
351 "${archive}/{$this->mUploadOldVersion}" );
354 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
357 $this->mUploadOldVersion
= '';
360 wfSuppressWarnings();
361 $success = $useRename
362 ?
rename( $tempName, $this->mSavedFile
)
363 : move_uploaded_file( $tempName, $this->mSavedFile
);
367 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
370 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
373 chmod( $this->mSavedFile
, 0644 );
378 * Stash a file in a temporary directory for later processing
379 * after the user has confirmed it.
381 * If the user doesn't explicitly cancel or accept, these files
382 * can accumulate in the temp directory.
384 * @param string $saveName - the destination filename
385 * @param string $tempName - the source temporary file to save
386 * @return string - full path the stashed file, or false on failure
389 function saveTempUploadedFile( $saveName, $tempName ) {
391 $archive = wfImageArchiveDir( $saveName, 'temp' );
392 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
394 $success = $this->mRemoveTempFile
395 ?
rename( $tempName, $stash )
396 : move_uploaded_file( $tempName, $stash );
398 $wgOut->fileCopyError( $tempName, $stash );
406 * Stash a file in a temporary directory for later processing,
407 * and save the necessary descriptive info into the session.
408 * Returns a key value which will be passed through a form
409 * to pick up the path info on a later invocation.
414 function stashSession() {
415 $stash = $this->saveTempUploadedFile(
416 $this->mUploadSaveName
, $this->mUploadTempName
);
419 # Couldn't save the file.
423 $key = mt_rand( 0, 0x7fffffff );
424 $_SESSION['wsUploadData'][$key] = array(
425 'mUploadTempName' => $stash,
426 'mUploadSize' => $this->mUploadSize
,
427 'mOname' => $this->mOname
);
432 * Remove a temporarily kept file stashed by saveTempUploadedFile().
435 function unsaveUploadedFile() {
437 wfSuppressWarnings();
438 $success = unlink( $this->mUploadTempName
);
441 $wgOut->fileDeleteError( $this->mUploadTempName
);
445 /* -------------------------------------------------------------- */
448 * Show some text and linkage on successful upload.
451 function showSuccess() {
452 global $wgUser, $wgOut, $wgContLang;
454 $sk = $wgUser->getSkin();
455 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
456 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
457 $dlink = $sk->makeKnownLink( $dname, $dname );
459 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
460 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
461 $wgOut->addHTML( $text );
462 $wgOut->returnToMain( false );
466 * @param string $error as HTML
469 function uploadError( $error ) {
471 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
472 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
476 * There's something wrong with this file, not enough to reject it
477 * totally but we require manual intervention to save it for real.
478 * Stash it away, then present a form asking to confirm or cancel.
480 * @param string $warning as HTML
483 function uploadWarning( $warning ) {
484 global $wgOut, $wgUser, $wgUploadDirectory, $wgRequest;
485 global $wgUseCopyrightUpload;
487 $this->mSessionKey
= $this->stashSession();
488 if( !$this->mSessionKey
) {
489 # Couldn't save file; an error has been displayed so let's go.
493 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
494 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
496 $save = wfMsgHtml( 'savefile' );
497 $reupload = wfMsgHtml( 'reupload' );
498 $iw = wfMsgWikiHtml( 'ignorewarning' );
499 $reup = wfMsgWikiHtml( 'reuploaddesc' );
500 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
501 $action = $titleObj->escapeLocalURL( 'action=submit' );
503 if ( $wgUseCopyrightUpload )
506 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
507 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
514 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
515 <input type='hidden' name='wpIgnoreWarning' value='1' />
516 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
517 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
518 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
519 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
520 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
526 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
528 <td align='left'>$iw</td>
532 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
534 <td align='left'>$reup</td>
537 </table></form>\n" );
541 * Displays the main upload form, optionally with a highlighted
542 * error message up at the top.
544 * @param string $msg as HTML
547 function mainUploadForm( $msg='' ) {
548 global $wgOut, $wgUser, $wgUploadDirectory, $wgRequest;
549 global $wgUseCopyrightUpload;
551 $cols = intval($wgUser->getOption( 'cols' ));
552 $ew = $wgUser->getOption( 'editwidth' );
553 if ( $ew ) $ew = " style=\"width:100%\"";
557 $sub = wfMsgHtml( 'uploaderror' );
558 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
559 "<span class='error'>{$msg}</span>\n" );
561 $wgOut->addHTML( '<div id="uploadtext">' );
562 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
563 $wgOut->addHTML( '</div>' );
564 $sk = $wgUser->getSkin();
567 $sourcefilename = wfMsgHtml( 'sourcefilename' );
568 $destfilename = wfMsgHtml( 'destfilename' );
569 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
571 $licenses = new Licenses();
572 $license = wfMsgHtml( 'license' );
573 $nolicense = wfMsgHtml( 'nolicense' );
574 $licenseshtml = $licenses->getHtml();
576 $ulb = wfMsgHtml( 'uploadbtn' );
579 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
580 $action = $titleObj->escapeLocalURL();
582 $encDestFile = htmlspecialchars( $this->mDestFile
);
584 $watchChecked = $wgUser->getOption( 'watchdefault' )
585 ?
'checked="checked"'
589 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
592 <td align='right'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
594 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?
"":"onchange='fillDestFilename()' ") . "size='40' />
598 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
600 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
604 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
606 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
611 if ( $licenseshtml != '' ) {
613 <td align='right'><label for='wpLicense'>$license:</label></td>
615 <select name='wpLicense' id='wpLicense' tabindex='4'>
616 <option value=''>$nolicense</option>
625 if ( $wgUseCopyrightUpload ) {
626 $filestatus = wfMsgHtml ( 'filestatus' );
627 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
628 $filesource = wfMsgHtml ( 'filesource' );
629 $uploadsource = htmlspecialchars( $this->mUploadSource
);
632 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
633 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
636 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
637 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
647 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
648 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
649 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
650 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
658 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
665 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
674 /* -------------------------------------------------------------- */
677 * Split a file into a base name and all dot-delimited 'extensions'
678 * on the end. Some web server configurations will fall back to
679 * earlier pseudo-'extensions' to determine type and execute
680 * scripts, so the blacklist needs to check them all.
684 function splitExtensions( $filename ) {
685 $bits = explode( '.', $filename );
686 $basename = array_shift( $bits );
687 return array( $basename, $bits );
691 * Perform case-insensitive match against a list of file extensions.
692 * Returns true if the extension is in the list.
698 function checkFileExtension( $ext, $list ) {
699 return in_array( strtolower( $ext ), $list );
703 * Perform case-insensitive match against a list of file extensions.
704 * Returns true if any of the extensions are in the list.
710 function checkFileExtensionList( $ext, $list ) {
711 foreach( $ext as $e ) {
712 if( in_array( strtolower( $e ), $list ) ) {
720 * Verifies that it's ok to include the uploaded file
722 * @param string $tmpfile the full path of the temporary file to verify
723 * @param string $extension The filename extension that the file is to be served with
724 * @return mixed true of the file is verified, a WikiError object otherwise.
726 function verify( $tmpfile, $extension ) {
727 #magically determine mime type
728 $magic=& wfGetMimeMagic();
729 $mime= $magic->guessMimeType($tmpfile,false);
731 $fname= "SpecialUpload::verify";
733 #check mime type, if desired
734 global $wgVerifyMimeType;
735 if ($wgVerifyMimeType) {
737 #check mime type against file extension
738 if( !$this->verifyExtension( $mime, $extension ) ) {
739 return new WikiErrorMsg( 'uploadcorrupt' );
742 #check mime type blacklist
743 global $wgMimeTypeBlacklist;
744 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
745 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
746 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
750 #check for htmlish code and javascript
751 if( $this->detectScript ( $tmpfile, $mime ) ) {
752 return new WikiErrorMsg( 'uploadscripted' );
756 * Scan the uploaded file for viruses
758 $virus= $this->detectVirus($tmpfile);
760 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
763 wfDebug( "$fname: all clear; passing.\n" );
768 * Checks if the mime type of the uploaded file matches the file extension.
770 * @param string $mime the mime type of the uploaded file
771 * @param string $extension The filename extension that the file is to be served with
774 function verifyExtension( $mime, $extension ) {
775 $fname = 'SpecialUpload::verifyExtension';
777 $magic =& wfGetMimeMagic();
779 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
780 if ( ! $magic->isRecognizableExtension( $extension ) ) {
781 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
784 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
788 $match= $magic->isMatchingExtension($extension,$mime);
791 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
793 } elseif ($match===true) {
794 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
796 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
800 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
805 /** Heuristig for detecting files that *could* contain JavaScript instructions or
806 * things that may look like HTML to a browser and are thus
807 * potentially harmful. The present implementation will produce false positives in some situations.
809 * @param string $file Pathname to the temporary upload file
810 * @param string $mime The mime type of the file
811 * @return bool true if the file contains something looking like embedded scripts
813 function detectScript($file,$mime) {
815 #ugly hack: for text files, always look at the entire file.
816 #For binarie field, just check the first K.
818 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
820 $fp = fopen( $file, 'rb' );
821 $chunk = fread( $fp, 1024 );
825 $chunk= strtolower( $chunk );
827 if (!$chunk) return false;
829 #decode from UTF-16 if needed (could be used for obfuscation).
830 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
831 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
834 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
836 $chunk= trim($chunk);
838 #FIXME: convert from UTF-16 if necessarry!
840 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
842 #check for HTML doctype
843 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
846 * Internet Explorer for Windows performs some really stupid file type
847 * autodetection which can cause it to interpret valid image files as HTML
848 * and potentially execute JavaScript, creating a cross-site scripting
851 * Apple's Safari browser also performs some unsafe file type autodetection
852 * which can cause legitimate files to be interpreted as HTML if the
853 * web server is not correctly configured to send the right content-type
854 * (or if you're really uploading plain text and octet streams!)
856 * Returns true if IE is likely to mistake the given file for HTML.
857 * Also returns true if Safari would mistake the given file for HTML
858 * when served with a generic content-type.
864 '<html', #also in safari
867 '<script', #also in safari
869 '<title' #also in safari
872 foreach( $tags as $tag ) {
873 if( false !== strpos( $chunk, $tag ) ) {
879 * look for javascript
882 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
883 $chunk = Sanitizer
::decodeCharReferences( $chunk );
885 #look for script-types
886 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
888 #look for html-style script-urls
889 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
891 #look for css-style script-urls
892 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
894 wfDebug("SpecialUpload::detectScript: no scripts found\n");
898 /** Generic wrapper function for a virus scanner program.
899 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
900 * $wgAntivirusRequired may be used to deny upload if the scan fails.
902 * @param string $file Pathname to the temporary upload file
903 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
904 * or a string containing feedback from the virus scanner if a virus was found.
905 * If textual feedback is missing but a virus was found, this function returns true.
907 function detectVirus($file) {
908 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
910 $fname= "SpecialUpload::detectVirus";
912 if (!$wgAntivirus) { #disabled?
913 wfDebug("$fname: virus scanner disabled\n");
918 if (!$wgAntivirusSetup[$wgAntivirus]) {
919 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
921 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
923 return "unknown antivirus: $wgAntivirus";
926 #look up scanner configuration
927 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
928 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
929 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
931 $scanner= $virus_scanner; #copy, so we can resolve the pattern
933 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
934 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
936 wfDebug("$fname: running virus scan: $scanner \n");
938 #execute virus scanner
941 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
942 # that does not seem to be worth the pain.
943 # Ask me (Duesentrieb) about it if it's ever needed.
944 if (wfIsWindows()) exec("$scanner",$output,$code);
945 else exec("$scanner 2>&1",$output,$code);
947 $exit_code= $code; #remeber for user feedback
949 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
950 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
951 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
954 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
955 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
957 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
960 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
961 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
964 else if ($code===AV_NO_VIRUS
) {
965 wfDebug("$fname: file passed virus scan.\n");
966 return false; #no virus found
969 $output= join("\n",$output);
970 $output= trim($output);
972 if (!$output) $output= true; #if ther's no output, return true
973 else if ($msg_pattern) {
975 if (preg_match($msg_pattern,$output,$groups)) {
976 if ($groups[1]) $output= $groups[1];
980 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
986 * Check if the temporary file is MacBinary-encoded, as some uploads
987 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
988 * If so, the data fork will be extracted to a second temporary file,
989 * which will then be checked for validity and either kept or discarded.
993 function checkMacBinary() {
994 $macbin = new MacBinary( $this->mUploadTempName
);
995 if( $macbin->isValid() ) {
996 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
997 $dataHandle = fopen( $dataFile, 'wb' );
999 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1000 $macbin->extractData( $dataHandle );
1002 $this->mUploadTempName
= $dataFile;
1003 $this->mUploadSize
= $macbin->dataForkLength();
1005 // We'll have to manually remove the new file if it's not kept.
1006 $this->mRemoveTempFile
= true;
1012 * If we've modified the upload file we need to manually remove it
1013 * on exit to clean up.
1016 function cleanupTempFile() {
1017 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1018 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1019 unlink( $this->mUploadTempName
);
1024 * Check if there's an overwrite conflict and, if so, if restrictions
1025 * forbid this user from performing the upload.
1027 * @return mixed true on success, WikiError on failure
1030 function checkOverwrite( $name ) {
1031 $img = Image
::newFromName( $name );
1032 if( is_null( $img ) ) {
1033 // Uh... this shouldn't happen ;)
1034 // But if it does, fall through to previous behavior
1039 if( $img->exists() ) {
1040 global $wgUser, $wgOut;
1041 if( $img->isLocal() ) {
1042 if( !$wgUser->isAllowed( 'reupload' ) ) {
1043 $error = 'fileexists-forbidden';
1046 if( !$wgUser->isAllowed( 'reupload' ) ||
1047 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1048 $error = "fileexists-shared-forbidden";
1054 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1055 return new WikiError( $wgOut->parse( $errorText ) );
1058 // Rockin', go ahead and upload