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 );
185 if( count( $ext ) ) {
186 $finalExt = $ext[count( $ext ) - 1];
190 $fullExt = implode( '.', $ext );
192 # If there was more than one "extension", reassemble the base
193 # filename to prevent bogus complaints about length
194 if( count( $ext ) > 1 ) {
195 for( $i = 0; $i < count( $ext ) - 1; $i++
)
196 $partname .= '.' . $ext[$i];
199 if ( strlen( $partname ) < 3 ) {
200 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
205 * Filter out illegal characters, and try to make a legible name
206 * out of it. We'll strip some silently that Title would die on.
208 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
209 $nt = Title
::newFromText( $filtered );
210 if( is_null( $nt ) ) {
211 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
214 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
215 $this->mUploadSaveName
= $nt->getDBkey();
218 * If the image is protected, non-sysop users won't be able
219 * to modify it by uploading a new revision.
221 if( !$nt->userCanEdit() ) {
222 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
226 * In some cases we may forbid overwriting of existing files.
228 $overwrite = $this->checkOverwrite( $this->mUploadSaveName
);
229 if( WikiError
::isError( $overwrite ) ) {
230 return $this->uploadError( $overwrite->toString() );
233 /* Don't allow users to override the blacklist (check file extension) */
234 global $wgStrictFileExtensions;
235 global $wgFileExtensions, $wgFileBlacklist;
236 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
237 ($wgStrictFileExtensions &&
238 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
239 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
243 * Look at the contents of the file; if we can recognize the
244 * type but it's corrupt or data of the wrong type, we should
245 * probably not accept it.
247 if( !$this->mStashed
) {
248 $this->checkMacBinary();
249 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
251 if( $veri !== true ) { //it's a wiki error...
252 return $this->uploadError( $veri->toString() );
257 * Provide an opportunity for extensions to add futher checks
260 if( !wfRunHooks( 'UploadVerification',
261 array( $this->mUploadSaveName
, $this->mUploadTempName
, &$error ) ) ) {
262 return $this->uploadError( $error );
266 * Check for non-fatal conditions
268 if ( ! $this->mIgnoreWarning
) {
271 global $wgCapitalLinks;
272 if( $wgCapitalLinks ) {
273 $filtered = ucfirst( $filtered );
275 if( $this->mUploadSaveName
!= $filtered ) {
276 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
279 global $wgCheckFileExtensions;
280 if ( $wgCheckFileExtensions ) {
281 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
282 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
286 global $wgUploadSizeWarning;
287 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
288 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
289 # value, perhaps add GB,MB and KB suffixes?
290 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
292 if ( $this->mUploadSize
== 0 ) {
293 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
296 if( $nt->getArticleID() ) {
298 $sk = $wgUser->getSkin();
299 $dlink = $sk->makeKnownLinkObj( $nt );
300 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
303 if( $warning != '' ) {
305 * Stash the file in a temporary location; the user can choose
306 * to let it through and we'll complete the upload then.
308 return $this->uploadWarning( $warning );
313 * Try actually saving the thing...
314 * It will show an error form on failure.
316 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
317 if( $this->saveUploadedFile( $this->mUploadSaveName
,
318 $this->mUploadTempName
,
321 * Update the upload log and create the description page
322 * if it's a new file.
324 $img = Image
::newFromName( $this->mUploadSaveName
);
325 $success = $img->recordUpload( $this->mUploadOldVersion
,
326 $this->mUploadDescription
,
328 $this->mUploadCopyStatus
,
329 $this->mUploadSource
,
333 $this->showSuccess();
335 // Image::recordUpload() fails if the image went missing, which is
336 // unlikely, hence the lack of a specialised message
337 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
343 * Move the uploaded file from its temporary location to the final
344 * destination. If a previous version of the file exists, move
345 * it into the archive subdirectory.
347 * @todo If the later save fails, we may have disappeared the original file.
349 * @param string $saveName
350 * @param string $tempName full path to the temporary file
351 * @param bool $useRename if true, doesn't check that the source file
352 * is a PHP-managed upload temporary
354 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
357 $fname= "SpecialUpload::saveUploadedFile";
359 $dest = wfImageDir( $saveName );
360 $archive = wfImageArchiveDir( $saveName );
361 $this->mSavedFile
= "{$dest}/{$saveName}";
363 if( is_file( $this->mSavedFile
) ) {
364 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
365 wfSuppressWarnings();
366 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
370 $wgOut->fileRenameError( $this->mSavedFile
,
371 "${archive}/{$this->mUploadOldVersion}" );
374 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
377 $this->mUploadOldVersion
= '';
380 wfSuppressWarnings();
381 $success = $useRename
382 ?
rename( $tempName, $this->mSavedFile
)
383 : move_uploaded_file( $tempName, $this->mSavedFile
);
387 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
390 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
393 chmod( $this->mSavedFile
, 0644 );
398 * Stash a file in a temporary directory for later processing
399 * after the user has confirmed it.
401 * If the user doesn't explicitly cancel or accept, these files
402 * can accumulate in the temp directory.
404 * @param string $saveName - the destination filename
405 * @param string $tempName - the source temporary file to save
406 * @return string - full path the stashed file, or false on failure
409 function saveTempUploadedFile( $saveName, $tempName ) {
411 $archive = wfImageArchiveDir( $saveName, 'temp' );
412 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
414 $success = $this->mRemoveTempFile
415 ?
rename( $tempName, $stash )
416 : move_uploaded_file( $tempName, $stash );
418 $wgOut->fileCopyError( $tempName, $stash );
426 * Stash a file in a temporary directory for later processing,
427 * and save the necessary descriptive info into the session.
428 * Returns a key value which will be passed through a form
429 * to pick up the path info on a later invocation.
434 function stashSession() {
435 $stash = $this->saveTempUploadedFile(
436 $this->mUploadSaveName
, $this->mUploadTempName
);
439 # Couldn't save the file.
443 $key = mt_rand( 0, 0x7fffffff );
444 $_SESSION['wsUploadData'][$key] = array(
445 'mUploadTempName' => $stash,
446 'mUploadSize' => $this->mUploadSize
,
447 'mOname' => $this->mOname
);
452 * Remove a temporarily kept file stashed by saveTempUploadedFile().
455 function unsaveUploadedFile() {
457 wfSuppressWarnings();
458 $success = unlink( $this->mUploadTempName
);
461 $wgOut->fileDeleteError( $this->mUploadTempName
);
465 /* -------------------------------------------------------------- */
468 * Show some text and linkage on successful upload.
471 function showSuccess() {
472 global $wgUser, $wgOut, $wgContLang;
474 $sk = $wgUser->getSkin();
475 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
476 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
477 $dlink = $sk->makeKnownLink( $dname, $dname );
479 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
480 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
481 $wgOut->addHTML( $text );
482 $wgOut->returnToMain( false );
486 * @param string $error as HTML
489 function uploadError( $error ) {
491 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
492 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
496 * There's something wrong with this file, not enough to reject it
497 * totally but we require manual intervention to save it for real.
498 * Stash it away, then present a form asking to confirm or cancel.
500 * @param string $warning as HTML
503 function uploadWarning( $warning ) {
505 global $wgUseCopyrightUpload;
507 $this->mSessionKey
= $this->stashSession();
508 if( !$this->mSessionKey
) {
509 # Couldn't save file; an error has been displayed so let's go.
513 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
514 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
516 $save = wfMsgHtml( 'savefile' );
517 $reupload = wfMsgHtml( 'reupload' );
518 $iw = wfMsgWikiHtml( 'ignorewarning' );
519 $reup = wfMsgWikiHtml( 'reuploaddesc' );
520 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
521 $action = $titleObj->escapeLocalURL( 'action=submit' );
523 if ( $wgUseCopyrightUpload )
526 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
527 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
534 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
535 <input type='hidden' name='wpIgnoreWarning' value='1' />
536 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
537 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
538 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
539 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
540 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
546 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
548 <td align='left'>$iw</td>
552 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
554 <td align='left'>$reup</td>
557 </table></form>\n" );
561 * Displays the main upload form, optionally with a highlighted
562 * error message up at the top.
564 * @param string $msg as HTML
567 function mainUploadForm( $msg='' ) {
568 global $wgOut, $wgUser;
569 global $wgUseCopyrightUpload;
571 $cols = intval($wgUser->getOption( 'cols' ));
572 $ew = $wgUser->getOption( 'editwidth' );
573 if ( $ew ) $ew = " style=\"width:100%\"";
577 $sub = wfMsgHtml( 'uploaderror' );
578 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
579 "<span class='error'>{$msg}</span>\n" );
581 $wgOut->addHTML( '<div id="uploadtext">' );
582 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
583 $wgOut->addHTML( '</div>' );
584 $sk = $wgUser->getSkin();
587 $sourcefilename = wfMsgHtml( 'sourcefilename' );
588 $destfilename = wfMsgHtml( 'destfilename' );
589 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
591 $licenses = new Licenses();
592 $license = wfMsgHtml( 'license' );
593 $nolicense = wfMsgHtml( 'nolicense' );
594 $licenseshtml = $licenses->getHtml();
596 $ulb = wfMsgHtml( 'uploadbtn' );
599 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
600 $action = $titleObj->escapeLocalURL();
602 $encDestFile = htmlspecialchars( $this->mDestFile
);
604 $watchChecked = $wgUser->getOption( 'watchdefault' )
605 ?
'checked="checked"'
609 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
612 <td align='right'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
614 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?
"":"onchange='fillDestFilename()' ") . "size='40' />
618 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
620 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
624 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
626 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
631 if ( $licenseshtml != '' ) {
634 <td align='right'><label for='wpLicense'>$license:</label></td>
636 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
637 <select name='wpLicense' id='wpLicense' tabindex='4'
638 onchange='licenseSelectorCheck()'>
639 <option value=''>$nolicense</option>
648 if ( $wgUseCopyrightUpload ) {
649 $filestatus = wfMsgHtml ( 'filestatus' );
650 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
651 $filesource = wfMsgHtml ( 'filesource' );
652 $uploadsource = htmlspecialchars( $this->mUploadSource
);
655 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
656 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
659 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
660 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
670 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
671 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
672 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
673 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
681 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
688 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
697 /* -------------------------------------------------------------- */
700 * Split a file into a base name and all dot-delimited 'extensions'
701 * on the end. Some web server configurations will fall back to
702 * earlier pseudo-'extensions' to determine type and execute
703 * scripts, so the blacklist needs to check them all.
707 function splitExtensions( $filename ) {
708 $bits = explode( '.', $filename );
709 $basename = array_shift( $bits );
710 return array( $basename, $bits );
714 * Perform case-insensitive match against a list of file extensions.
715 * Returns true if the extension is in the list.
721 function checkFileExtension( $ext, $list ) {
722 return in_array( strtolower( $ext ), $list );
726 * Perform case-insensitive match against a list of file extensions.
727 * Returns true if any of the extensions are in the list.
733 function checkFileExtensionList( $ext, $list ) {
734 foreach( $ext as $e ) {
735 if( in_array( strtolower( $e ), $list ) ) {
743 * Verifies that it's ok to include the uploaded file
745 * @param string $tmpfile the full path of the temporary file to verify
746 * @param string $extension The filename extension that the file is to be served with
747 * @return mixed true of the file is verified, a WikiError object otherwise.
749 function verify( $tmpfile, $extension ) {
750 #magically determine mime type
751 $magic=& wfGetMimeMagic();
752 $mime= $magic->guessMimeType($tmpfile,false);
754 $fname= "SpecialUpload::verify";
756 #check mime type, if desired
757 global $wgVerifyMimeType;
758 if ($wgVerifyMimeType) {
760 #check mime type against file extension
761 if( !$this->verifyExtension( $mime, $extension ) ) {
762 return new WikiErrorMsg( 'uploadcorrupt' );
765 #check mime type blacklist
766 global $wgMimeTypeBlacklist;
767 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
768 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
769 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
773 #check for htmlish code and javascript
774 if( $this->detectScript ( $tmpfile, $mime ) ) {
775 return new WikiErrorMsg( 'uploadscripted' );
779 * Scan the uploaded file for viruses
781 $virus= $this->detectVirus($tmpfile);
783 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
786 wfDebug( "$fname: all clear; passing.\n" );
791 * Checks if the mime type of the uploaded file matches the file extension.
793 * @param string $mime the mime type of the uploaded file
794 * @param string $extension The filename extension that the file is to be served with
797 function verifyExtension( $mime, $extension ) {
798 $fname = 'SpecialUpload::verifyExtension';
800 $magic =& wfGetMimeMagic();
802 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
803 if ( ! $magic->isRecognizableExtension( $extension ) ) {
804 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
807 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
811 $match= $magic->isMatchingExtension($extension,$mime);
814 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
816 } elseif ($match===true) {
817 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
819 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
823 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
828 /** Heuristig for detecting files that *could* contain JavaScript instructions or
829 * things that may look like HTML to a browser and are thus
830 * potentially harmful. The present implementation will produce false positives in some situations.
832 * @param string $file Pathname to the temporary upload file
833 * @param string $mime The mime type of the file
834 * @return bool true if the file contains something looking like embedded scripts
836 function detectScript($file,$mime) {
838 #ugly hack: for text files, always look at the entire file.
839 #For binarie field, just check the first K.
841 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
843 $fp = fopen( $file, 'rb' );
844 $chunk = fread( $fp, 1024 );
848 $chunk= strtolower( $chunk );
850 if (!$chunk) return false;
852 #decode from UTF-16 if needed (could be used for obfuscation).
853 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
854 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
857 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
859 $chunk= trim($chunk);
861 #FIXME: convert from UTF-16 if necessarry!
863 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
865 #check for HTML doctype
866 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
869 * Internet Explorer for Windows performs some really stupid file type
870 * autodetection which can cause it to interpret valid image files as HTML
871 * and potentially execute JavaScript, creating a cross-site scripting
874 * Apple's Safari browser also performs some unsafe file type autodetection
875 * which can cause legitimate files to be interpreted as HTML if the
876 * web server is not correctly configured to send the right content-type
877 * (or if you're really uploading plain text and octet streams!)
879 * Returns true if IE is likely to mistake the given file for HTML.
880 * Also returns true if Safari would mistake the given file for HTML
881 * when served with a generic content-type.
887 '<html', #also in safari
890 '<script', #also in safari
892 '<title' #also in safari
895 foreach( $tags as $tag ) {
896 if( false !== strpos( $chunk, $tag ) ) {
902 * look for javascript
905 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
906 $chunk = Sanitizer
::decodeCharReferences( $chunk );
908 #look for script-types
909 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
911 #look for html-style script-urls
912 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
914 #look for css-style script-urls
915 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
917 wfDebug("SpecialUpload::detectScript: no scripts found\n");
921 /** Generic wrapper function for a virus scanner program.
922 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
923 * $wgAntivirusRequired may be used to deny upload if the scan fails.
925 * @param string $file Pathname to the temporary upload file
926 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
927 * or a string containing feedback from the virus scanner if a virus was found.
928 * If textual feedback is missing but a virus was found, this function returns true.
930 function detectVirus($file) {
931 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
933 $fname= "SpecialUpload::detectVirus";
935 if (!$wgAntivirus) { #disabled?
936 wfDebug("$fname: virus scanner disabled\n");
941 if (!$wgAntivirusSetup[$wgAntivirus]) {
942 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
944 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
946 return "unknown antivirus: $wgAntivirus";
949 #look up scanner configuration
950 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
951 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
952 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
954 $scanner= $virus_scanner; #copy, so we can resolve the pattern
956 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
957 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
959 wfDebug("$fname: running virus scan: $scanner \n");
961 #execute virus scanner
964 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
965 # that does not seem to be worth the pain.
966 # Ask me (Duesentrieb) about it if it's ever needed.
967 if (wfIsWindows()) exec("$scanner",$output,$code);
968 else exec("$scanner 2>&1",$output,$code);
970 $exit_code= $code; #remeber for user feedback
972 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
973 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
974 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
977 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
978 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
980 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
983 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
984 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
987 else if ($code===AV_NO_VIRUS
) {
988 wfDebug("$fname: file passed virus scan.\n");
989 return false; #no virus found
992 $output= join("\n",$output);
993 $output= trim($output);
995 if (!$output) $output= true; #if ther's no output, return true
996 else if ($msg_pattern) {
998 if (preg_match($msg_pattern,$output,$groups)) {
999 if ($groups[1]) $output= $groups[1];
1003 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1009 * Check if the temporary file is MacBinary-encoded, as some uploads
1010 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1011 * If so, the data fork will be extracted to a second temporary file,
1012 * which will then be checked for validity and either kept or discarded.
1016 function checkMacBinary() {
1017 $macbin = new MacBinary( $this->mUploadTempName
);
1018 if( $macbin->isValid() ) {
1019 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1020 $dataHandle = fopen( $dataFile, 'wb' );
1022 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1023 $macbin->extractData( $dataHandle );
1025 $this->mUploadTempName
= $dataFile;
1026 $this->mUploadSize
= $macbin->dataForkLength();
1028 // We'll have to manually remove the new file if it's not kept.
1029 $this->mRemoveTempFile
= true;
1035 * If we've modified the upload file we need to manually remove it
1036 * on exit to clean up.
1039 function cleanupTempFile() {
1040 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1041 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1042 unlink( $this->mUploadTempName
);
1047 * Check if there's an overwrite conflict and, if so, if restrictions
1048 * forbid this user from performing the upload.
1050 * @return mixed true on success, WikiError on failure
1053 function checkOverwrite( $name ) {
1054 $img = Image
::newFromName( $name );
1055 if( is_null( $img ) ) {
1056 // Uh... this shouldn't happen ;)
1057 // But if it does, fall through to previous behavior
1062 if( $img->exists() ) {
1063 global $wgUser, $wgOut;
1064 if( $img->isLocal() ) {
1065 if( !$wgUser->isAllowed( 'reupload' ) ) {
1066 $error = 'fileexists-forbidden';
1069 if( !$wgUser->isAllowed( 'reupload' ) ||
1070 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1071 $error = "fileexists-shared-forbidden";
1077 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1078 return new WikiError( $wgOut->parse( $errorText ) );
1081 // Rockin', go ahead and upload