5 * @subpackage SpecialPage
11 require_once 'Image.php';
15 function wfSpecialUpload() {
17 $form = new UploadForm( $wgRequest );
24 * @subpackage SpecialPage
30 var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError;
31 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
32 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
33 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile;
37 * Constructor : initialise object
38 * Get data POSTed through the form and assign them to the object
39 * @param $request Data posted.
41 function UploadForm( &$request ) {
42 $this->mDestFile
= $request->getText( 'wpDestFile' );
44 if( !$request->wasPosted() ) {
45 # GET requests just give the main form; no data except wpDestfile.
49 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' );
50 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
51 $this->mUpload
= $request->getCheck( 'wpUpload' );
53 $this->mUploadDescription
= $request->getText( 'wpUploadDescription' );
54 $this->mLicense
= $request->getText( 'wpLicense' );
55 $this->mUploadCopyStatus
= $request->getText( 'wpUploadCopyStatus' );
56 $this->mUploadSource
= $request->getText( 'wpUploadSource' );
57 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
58 wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
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 # Check uploading enabled
101 if( !$wgEnableUploads ) {
102 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
107 if( $wgUser->isLoggedIn() ) {
108 if( !$wgUser->isAllowed( 'upload' ) ) {
109 $wgOut->permissionRequired( 'upload' );
113 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
118 if( $wgUser->isBlocked() ) {
119 $wgOut->blockedPage();
124 $wgOut->readOnlyPage();
128 /** Check if the image directory is writeable, this is a common mistake */
129 if ( !is_writeable( $wgUploadDirectory ) ) {
130 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
134 if( $this->mReUpload
) {
135 if ( !$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>';
302 # If the file existed before and was deleted, warn the user of this
303 # Don't bother doing so if the image exists now, however
304 $image = new Image( $nt );
305 if( $image->wasDeleted() ) {
306 $skin = $wgUser->getSkin();
307 $ltitle = Title
::makeTitle( NS_SPECIAL
, 'Log' );
308 $llink = $skin->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
309 $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
313 if( $warning != '' ) {
315 * Stash the file in a temporary location; the user can choose
316 * to let it through and we'll complete the upload then.
318 return $this->uploadWarning( $warning );
323 * Try actually saving the thing...
324 * It will show an error form on failure.
326 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
327 if( $this->saveUploadedFile( $this->mUploadSaveName
,
328 $this->mUploadTempName
,
331 * Update the upload log and create the description page
332 * if it's a new file.
334 $img = Image
::newFromName( $this->mUploadSaveName
);
335 $success = $img->recordUpload( $this->mUploadOldVersion
,
336 $this->mUploadDescription
,
338 $this->mUploadCopyStatus
,
339 $this->mUploadSource
,
343 $this->showSuccess();
344 wfRunHooks( 'UploadComplete', array( &$img ) );
346 // Image::recordUpload() fails if the image went missing, which is
347 // unlikely, hence the lack of a specialised message
348 $wgOut->showFileNotFoundError( $this->mUploadSaveName
);
354 * Move the uploaded file from its temporary location to the final
355 * destination. If a previous version of the file exists, move
356 * it into the archive subdirectory.
358 * @todo If the later save fails, we may have disappeared the original file.
360 * @param string $saveName
361 * @param string $tempName full path to the temporary file
362 * @param bool $useRename if true, doesn't check that the source file
363 * is a PHP-managed upload temporary
365 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
368 $fname= "SpecialUpload::saveUploadedFile";
370 $dest = wfImageDir( $saveName );
371 $archive = wfImageArchiveDir( $saveName );
372 $this->mSavedFile
= "{$dest}/{$saveName}";
374 if( is_file( $this->mSavedFile
) ) {
375 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
376 wfSuppressWarnings();
377 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
381 $wgOut->showFileRenameError( $this->mSavedFile
,
382 "${archive}/{$this->mUploadOldVersion}" );
385 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
388 $this->mUploadOldVersion
= '';
391 wfSuppressWarnings();
392 $success = $useRename
393 ?
rename( $tempName, $this->mSavedFile
)
394 : move_uploaded_file( $tempName, $this->mSavedFile
);
398 $wgOut->showFileCopyError( $tempName, $this->mSavedFile
);
401 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
404 chmod( $this->mSavedFile
, 0644 );
409 * Stash a file in a temporary directory for later processing
410 * after the user has confirmed it.
412 * If the user doesn't explicitly cancel or accept, these files
413 * can accumulate in the temp directory.
415 * @param string $saveName - the destination filename
416 * @param string $tempName - the source temporary file to save
417 * @return string - full path the stashed file, or false on failure
420 function saveTempUploadedFile( $saveName, $tempName ) {
422 $archive = wfImageArchiveDir( $saveName, 'temp' );
423 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
425 $success = $this->mRemoveTempFile
426 ?
rename( $tempName, $stash )
427 : move_uploaded_file( $tempName, $stash );
429 $wgOut->showFileCopyError( $tempName, $stash );
437 * Stash a file in a temporary directory for later processing,
438 * and save the necessary descriptive info into the session.
439 * Returns a key value which will be passed through a form
440 * to pick up the path info on a later invocation.
445 function stashSession() {
446 $stash = $this->saveTempUploadedFile(
447 $this->mUploadSaveName
, $this->mUploadTempName
);
450 # Couldn't save the file.
454 $key = mt_rand( 0, 0x7fffffff );
455 $_SESSION['wsUploadData'][$key] = array(
456 'mUploadTempName' => $stash,
457 'mUploadSize' => $this->mUploadSize
,
458 'mOname' => $this->mOname
);
463 * Remove a temporarily kept file stashed by saveTempUploadedFile().
467 function unsaveUploadedFile() {
469 wfSuppressWarnings();
470 $success = unlink( $this->mUploadTempName
);
473 $wgOut->showFileDeleteError( $this->mUploadTempName
);
480 /* -------------------------------------------------------------- */
483 * Show some text and linkage on successful upload.
486 function showSuccess() {
487 global $wgUser, $wgOut, $wgContLang;
489 $sk = $wgUser->getSkin();
490 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
491 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
492 $dlink = $sk->makeKnownLink( $dname, $dname );
494 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
495 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
496 $wgOut->addHTML( $text );
497 $wgOut->returnToMain( false );
501 * @param string $error as HTML
504 function uploadError( $error ) {
506 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
507 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
511 * There's something wrong with this file, not enough to reject it
512 * totally but we require manual intervention to save it for real.
513 * Stash it away, then present a form asking to confirm or cancel.
515 * @param string $warning as HTML
518 function uploadWarning( $warning ) {
520 global $wgUseCopyrightUpload;
522 $this->mSessionKey
= $this->stashSession();
523 if( !$this->mSessionKey
) {
524 # Couldn't save file; an error has been displayed so let's go.
528 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
529 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
531 $save = wfMsgHtml( 'savefile' );
532 $reupload = wfMsgHtml( 'reupload' );
533 $iw = wfMsgWikiHtml( 'ignorewarning' );
534 $reup = wfMsgWikiHtml( 'reuploaddesc' );
535 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
536 $action = $titleObj->escapeLocalURL( 'action=submit' );
538 if ( $wgUseCopyrightUpload )
541 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
542 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
549 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
550 <input type='hidden' name='wpIgnoreWarning' value='1' />
551 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
552 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
553 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
554 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
555 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
561 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
563 <td align='left'>$iw</td>
567 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
569 <td align='left'>$reup</td>
572 </table></form>\n" );
576 * Displays the main upload form, optionally with a highlighted
577 * error message up at the top.
579 * @param string $msg as HTML
582 function mainUploadForm( $msg='' ) {
583 global $wgOut, $wgUser;
584 global $wgUseCopyrightUpload;
586 $cols = intval($wgUser->getOption( 'cols' ));
587 $ew = $wgUser->getOption( 'editwidth' );
588 if ( $ew ) $ew = " style=\"width:100%\"";
592 $sub = wfMsgHtml( 'uploaderror' );
593 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
594 "<span class='error'>{$msg}</span>\n" );
596 $wgOut->addHTML( '<div id="uploadtext">' );
597 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
598 $wgOut->addHTML( '</div>' );
599 $sk = $wgUser->getSkin();
602 $sourcefilename = wfMsgHtml( 'sourcefilename' );
603 $destfilename = wfMsgHtml( 'destfilename' );
604 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
606 $licenses = new Licenses();
607 $license = wfMsgHtml( 'license' );
608 $nolicense = wfMsgHtml( 'nolicense' );
609 $licenseshtml = $licenses->getHtml();
611 $ulb = wfMsgHtml( 'uploadbtn' );
614 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
615 $action = $titleObj->escapeLocalURL();
617 $encDestFile = htmlspecialchars( $this->mDestFile
);
619 $watchChecked = $wgUser->getOption( 'watchdefault' )
620 ?
'checked="checked"'
624 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
627 <td align='right'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
629 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?
"":"onchange='fillDestFilename()' ") . "size='40' />
633 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
635 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
639 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
641 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
646 if ( $licenseshtml != '' ) {
649 <td align='right'><label for='wpLicense'>$license:</label></td>
651 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
652 <select name='wpLicense' id='wpLicense' tabindex='4'
653 onchange='licenseSelectorCheck()'>
654 <option value=''>$nolicense</option>
663 if ( $wgUseCopyrightUpload ) {
664 $filestatus = wfMsgHtml ( 'filestatus' );
665 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
666 $filesource = wfMsgHtml ( 'filesource' );
667 $uploadsource = htmlspecialchars( $this->mUploadSource
);
670 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
671 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
674 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
675 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
685 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
686 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
687 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
688 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
696 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
703 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
712 /* -------------------------------------------------------------- */
715 * Split a file into a base name and all dot-delimited 'extensions'
716 * on the end. Some web server configurations will fall back to
717 * earlier pseudo-'extensions' to determine type and execute
718 * scripts, so the blacklist needs to check them all.
722 function splitExtensions( $filename ) {
723 $bits = explode( '.', $filename );
724 $basename = array_shift( $bits );
725 return array( $basename, $bits );
729 * Perform case-insensitive match against a list of file extensions.
730 * Returns true if the extension is in the list.
736 function checkFileExtension( $ext, $list ) {
737 return in_array( strtolower( $ext ), $list );
741 * Perform case-insensitive match against a list of file extensions.
742 * Returns true if any of the extensions are in the list.
748 function checkFileExtensionList( $ext, $list ) {
749 foreach( $ext as $e ) {
750 if( in_array( strtolower( $e ), $list ) ) {
758 * Verifies that it's ok to include the uploaded file
760 * @param string $tmpfile the full path of the temporary file to verify
761 * @param string $extension The filename extension that the file is to be served with
762 * @return mixed true of the file is verified, a WikiError object otherwise.
764 function verify( $tmpfile, $extension ) {
765 #magically determine mime type
766 $magic=& wfGetMimeMagic();
767 $mime= $magic->guessMimeType($tmpfile,false);
769 $fname= "SpecialUpload::verify";
771 #check mime type, if desired
772 global $wgVerifyMimeType;
773 if ($wgVerifyMimeType) {
775 #check mime type against file extension
776 if( !$this->verifyExtension( $mime, $extension ) ) {
777 return new WikiErrorMsg( 'uploadcorrupt' );
780 #check mime type blacklist
781 global $wgMimeTypeBlacklist;
782 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
783 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
784 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
788 #check for htmlish code and javascript
789 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
790 return new WikiErrorMsg( 'uploadscripted' );
794 * Scan the uploaded file for viruses
796 $virus= $this->detectVirus($tmpfile);
798 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
801 wfDebug( "$fname: all clear; passing.\n" );
806 * Checks if the mime type of the uploaded file matches the file extension.
808 * @param string $mime the mime type of the uploaded file
809 * @param string $extension The filename extension that the file is to be served with
812 function verifyExtension( $mime, $extension ) {
813 $fname = 'SpecialUpload::verifyExtension';
815 $magic =& wfGetMimeMagic();
817 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
818 if ( ! $magic->isRecognizableExtension( $extension ) ) {
819 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
822 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
826 $match= $magic->isMatchingExtension($extension,$mime);
829 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
831 } elseif ($match===true) {
832 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
834 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
838 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
843 /** Heuristig for detecting files that *could* contain JavaScript instructions or
844 * things that may look like HTML to a browser and are thus
845 * potentially harmful. The present implementation will produce false positives in some situations.
847 * @param string $file Pathname to the temporary upload file
848 * @param string $mime The mime type of the file
849 * @param string $extension The extension of the file
850 * @return bool true if the file contains something looking like embedded scripts
852 function detectScript($file, $mime, $extension) {
853 global $wgAllowTitlesInSVG;
855 #ugly hack: for text files, always look at the entire file.
856 #For binarie field, just check the first K.
858 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
860 $fp = fopen( $file, 'rb' );
861 $chunk = fread( $fp, 1024 );
865 $chunk= strtolower( $chunk );
867 if (!$chunk) return false;
869 #decode from UTF-16 if needed (could be used for obfuscation).
870 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
871 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
874 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
876 $chunk= trim($chunk);
878 #FIXME: convert from UTF-16 if necessarry!
880 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
882 #check for HTML doctype
883 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
886 * Internet Explorer for Windows performs some really stupid file type
887 * autodetection which can cause it to interpret valid image files as HTML
888 * and potentially execute JavaScript, creating a cross-site scripting
891 * Apple's Safari browser also performs some unsafe file type autodetection
892 * which can cause legitimate files to be interpreted as HTML if the
893 * web server is not correctly configured to send the right content-type
894 * (or if you're really uploading plain text and octet streams!)
896 * Returns true if IE is likely to mistake the given file for HTML.
897 * Also returns true if Safari would mistake the given file for HTML
898 * when served with a generic content-type.
904 '<html', #also in safari
907 '<script', #also in safari
910 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
914 foreach( $tags as $tag ) {
915 if( false !== strpos( $chunk, $tag ) ) {
921 * look for javascript
924 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
925 $chunk = Sanitizer
::decodeCharReferences( $chunk );
927 #look for script-types
928 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
930 #look for html-style script-urls
931 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
933 #look for css-style script-urls
934 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
936 wfDebug("SpecialUpload::detectScript: no scripts found\n");
940 /** Generic wrapper function for a virus scanner program.
941 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
942 * $wgAntivirusRequired may be used to deny upload if the scan fails.
944 * @param string $file Pathname to the temporary upload file
945 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
946 * or a string containing feedback from the virus scanner if a virus was found.
947 * If textual feedback is missing but a virus was found, this function returns true.
949 function detectVirus($file) {
950 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
952 $fname= "SpecialUpload::detectVirus";
954 if (!$wgAntivirus) { #disabled?
955 wfDebug("$fname: virus scanner disabled\n");
960 if (!$wgAntivirusSetup[$wgAntivirus]) {
961 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
963 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
965 return "unknown antivirus: $wgAntivirus";
968 #look up scanner configuration
969 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
970 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
971 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
973 $scanner= $virus_scanner; #copy, so we can resolve the pattern
975 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
976 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
978 wfDebug("$fname: running virus scan: $scanner \n");
980 #execute virus scanner
983 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
984 # that does not seem to be worth the pain.
985 # Ask me (Duesentrieb) about it if it's ever needed.
986 if (wfIsWindows()) exec("$scanner",$output,$code);
987 else exec("$scanner 2>&1",$output,$code);
989 $exit_code= $code; #remeber for user feedback
991 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
992 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
993 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
996 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
997 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
999 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
1002 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
1003 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1006 else if ($code===AV_NO_VIRUS
) {
1007 wfDebug("$fname: file passed virus scan.\n");
1008 return false; #no virus found
1011 $output= join("\n",$output);
1012 $output= trim($output);
1014 if (!$output) $output= true; #if ther's no output, return true
1015 else if ($msg_pattern) {
1017 if (preg_match($msg_pattern,$output,$groups)) {
1018 if ($groups[1]) $output= $groups[1];
1022 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1028 * Check if the temporary file is MacBinary-encoded, as some uploads
1029 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1030 * If so, the data fork will be extracted to a second temporary file,
1031 * which will then be checked for validity and either kept or discarded.
1035 function checkMacBinary() {
1036 $macbin = new MacBinary( $this->mUploadTempName
);
1037 if( $macbin->isValid() ) {
1038 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1039 $dataHandle = fopen( $dataFile, 'wb' );
1041 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1042 $macbin->extractData( $dataHandle );
1044 $this->mUploadTempName
= $dataFile;
1045 $this->mUploadSize
= $macbin->dataForkLength();
1047 // We'll have to manually remove the new file if it's not kept.
1048 $this->mRemoveTempFile
= true;
1054 * If we've modified the upload file we need to manually remove it
1055 * on exit to clean up.
1058 function cleanupTempFile() {
1059 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1060 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1061 unlink( $this->mUploadTempName
);
1066 * Check if there's an overwrite conflict and, if so, if restrictions
1067 * forbid this user from performing the upload.
1069 * @return mixed true on success, WikiError on failure
1072 function checkOverwrite( $name ) {
1073 $img = Image
::newFromName( $name );
1074 if( is_null( $img ) ) {
1075 // Uh... this shouldn't happen ;)
1076 // But if it does, fall through to previous behavior
1081 if( $img->exists() ) {
1082 global $wgUser, $wgOut;
1083 if( $img->isLocal() ) {
1084 if( !$wgUser->isAllowed( 'reupload' ) ) {
1085 $error = 'fileexists-forbidden';
1088 if( !$wgUser->isAllowed( 'reupload' ) ||
1089 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1090 $error = "fileexists-shared-forbidden";
1096 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1097 return new WikiError( $wgOut->parse( $errorText ) );
1100 // Rockin', go ahead and upload