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, $wgLang, $wgContLang;
145 global $wgUploadDirectory;
146 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
148 /* Check for PHP error if any, requires php 4.2 or newer */
149 if ( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
150 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
155 * If there was no filename or a zero size given, give up quick.
157 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
158 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
162 # Chop off any directories in the given filename
163 if ( $this->mDestFile
) {
164 $basename = basename( $this->mDestFile
);
166 $basename = basename( $this->mOname
);
170 * We'll want to blacklist against *any* 'extension', and use
171 * only the final one for the whitelist.
173 list( $partname, $ext ) = $this->splitExtensions( $basename );
174 if( count( $ext ) ) {
175 $finalExt = $ext[count( $ext ) - 1];
179 $fullExt = implode( '.', $ext );
181 if ( strlen( $partname ) < 3 ) {
182 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
187 * Filter out illegal characters, and try to make a legible name
188 * out of it. We'll strip some silently that Title would die on.
190 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
191 $nt = Title
::newFromText( $filtered );
192 if( is_null( $nt ) ) {
193 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
196 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
197 $this->mUploadSaveName
= $nt->getDBkey();
200 * If the image is protected, non-sysop users won't be able
201 * to modify it by uploading a new revision.
203 if( !$nt->userCanEdit() ) {
204 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
208 * In some cases we may forbid overwriting of existing files.
210 $overwrite = $this->checkOverwrite( $this->mUploadSaveName
);
211 if( WikiError
::isError( $overwrite ) ) {
212 return $this->uploadError( $overwrite->toString() );
215 /* Don't allow users to override the blacklist (check file extension) */
216 global $wgStrictFileExtensions;
217 global $wgFileExtensions, $wgFileBlacklist;
218 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
219 ($wgStrictFileExtensions &&
220 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
221 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
225 * Look at the contents of the file; if we can recognize the
226 * type but it's corrupt or data of the wrong type, we should
227 * probably not accept it.
229 if( !$this->mStashed
) {
230 $this->checkMacBinary();
231 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
233 if( $veri !== true ) { //it's a wiki error...
234 return $this->uploadError( $veri->toString() );
239 * Provide an opportunity for extensions to add futher checks
242 if( !wfRunHooks( 'UploadVerification',
243 array( $this->mUploadSaveName
, $this->mUploadTempName
, &$error ) ) ) {
244 return $this->uploadError( $error );
248 * Check for non-fatal conditions
250 if ( ! $this->mIgnoreWarning
) {
253 global $wgCapitalLinks;
254 if( $wgCapitalLinks ) {
255 $filtered = ucfirst( $filtered );
257 if( $this->mUploadSaveName
!= $filtered ) {
258 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
261 global $wgCheckFileExtensions;
262 if ( $wgCheckFileExtensions ) {
263 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
264 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
268 global $wgUploadSizeWarning;
269 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
270 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
271 # value, perhaps add GB,MB and KB suffixes?
272 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
274 if ( $this->mUploadSize
== 0 ) {
275 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
278 if( $nt->getArticleID() ) {
280 $sk = $wgUser->getSkin();
281 $dlink = $sk->makeKnownLinkObj( $nt );
282 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
285 if( $warning != '' ) {
287 * Stash the file in a temporary location; the user can choose
288 * to let it through and we'll complete the upload then.
290 return $this->uploadWarning( $warning );
295 * Try actually saving the thing...
296 * It will show an error form on failure.
298 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
299 if( $this->saveUploadedFile( $this->mUploadSaveName
,
300 $this->mUploadTempName
,
303 * Update the upload log and create the description page
304 * if it's a new file.
306 $img = Image
::newFromName( $this->mUploadSaveName
);
307 $success = $img->recordUpload( $this->mUploadOldVersion
,
308 $this->mUploadDescription
,
310 $this->mUploadCopyStatus
,
311 $this->mUploadSource
,
315 $this->showSuccess();
317 // Image::recordUpload() fails if the image went missing, which is
318 // unlikely, hence the lack of a specialised message
319 $wgOut->fileNotFoundError( $this->mUploadSaveName
);
325 * Move the uploaded file from its temporary location to the final
326 * destination. If a previous version of the file exists, move
327 * it into the archive subdirectory.
329 * @todo If the later save fails, we may have disappeared the original file.
331 * @param string $saveName
332 * @param string $tempName full path to the temporary file
333 * @param bool $useRename if true, doesn't check that the source file
334 * is a PHP-managed upload temporary
336 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
337 global $wgUploadDirectory, $wgOut;
339 $fname= "SpecialUpload::saveUploadedFile";
341 $dest = wfImageDir( $saveName );
342 $archive = wfImageArchiveDir( $saveName );
343 $this->mSavedFile
= "{$dest}/{$saveName}";
345 if( is_file( $this->mSavedFile
) ) {
346 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
347 wfSuppressWarnings();
348 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
352 $wgOut->fileRenameError( $this->mSavedFile
,
353 "${archive}/{$this->mUploadOldVersion}" );
356 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
359 $this->mUploadOldVersion
= '';
362 wfSuppressWarnings();
363 $success = $useRename
364 ?
rename( $tempName, $this->mSavedFile
)
365 : move_uploaded_file( $tempName, $this->mSavedFile
);
369 $wgOut->fileCopyError( $tempName, $this->mSavedFile
);
372 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
375 chmod( $this->mSavedFile
, 0644 );
380 * Stash a file in a temporary directory for later processing
381 * after the user has confirmed it.
383 * If the user doesn't explicitly cancel or accept, these files
384 * can accumulate in the temp directory.
386 * @param string $saveName - the destination filename
387 * @param string $tempName - the source temporary file to save
388 * @return string - full path the stashed file, or false on failure
391 function saveTempUploadedFile( $saveName, $tempName ) {
393 $archive = wfImageArchiveDir( $saveName, 'temp' );
394 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
396 $success = $this->mRemoveTempFile
397 ?
rename( $tempName, $stash )
398 : move_uploaded_file( $tempName, $stash );
400 $wgOut->fileCopyError( $tempName, $stash );
408 * Stash a file in a temporary directory for later processing,
409 * and save the necessary descriptive info into the session.
410 * Returns a key value which will be passed through a form
411 * to pick up the path info on a later invocation.
416 function stashSession() {
417 $stash = $this->saveTempUploadedFile(
418 $this->mUploadSaveName
, $this->mUploadTempName
);
421 # Couldn't save the file.
425 $key = mt_rand( 0, 0x7fffffff );
426 $_SESSION['wsUploadData'][$key] = array(
427 'mUploadTempName' => $stash,
428 'mUploadSize' => $this->mUploadSize
,
429 'mOname' => $this->mOname
);
434 * Remove a temporarily kept file stashed by saveTempUploadedFile().
437 function unsaveUploadedFile() {
439 wfSuppressWarnings();
440 $success = unlink( $this->mUploadTempName
);
443 $wgOut->fileDeleteError( $this->mUploadTempName
);
447 /* -------------------------------------------------------------- */
450 * Show some text and linkage on successful upload.
453 function showSuccess() {
454 global $wgUser, $wgOut, $wgContLang;
456 $sk = $wgUser->getSkin();
457 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
458 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
459 $dlink = $sk->makeKnownLink( $dname, $dname );
461 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
462 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
463 $wgOut->addHTML( $text );
464 $wgOut->returnToMain( false );
468 * @param string $error as HTML
471 function uploadError( $error ) {
473 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
474 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
478 * There's something wrong with this file, not enough to reject it
479 * totally but we require manual intervention to save it for real.
480 * Stash it away, then present a form asking to confirm or cancel.
482 * @param string $warning as HTML
485 function uploadWarning( $warning ) {
486 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
487 global $wgUseCopyrightUpload;
489 $this->mSessionKey
= $this->stashSession();
490 if( !$this->mSessionKey
) {
491 # Couldn't save file; an error has been displayed so let's go.
495 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
496 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
498 $save = wfMsgHtml( 'savefile' );
499 $reupload = wfMsgHtml( 'reupload' );
500 $iw = wfMsgWikiHtml( 'ignorewarning' );
501 $reup = wfMsgWikiHtml( 'reuploaddesc' );
502 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
503 $action = $titleObj->escapeLocalURL( 'action=submit' );
505 if ( $wgUseCopyrightUpload )
508 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
509 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
516 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
517 <input type='hidden' name='wpIgnoreWarning' value='1' />
518 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
519 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
520 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
521 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
522 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
528 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
530 <td align='left'>$iw</td>
534 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
536 <td align='left'>$reup</td>
539 </table></form>\n" );
543 * Displays the main upload form, optionally with a highlighted
544 * error message up at the top.
546 * @param string $msg as HTML
549 function mainUploadForm( $msg='' ) {
550 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
551 global $wgUseCopyrightUpload;
553 $cols = intval($wgUser->getOption( 'cols' ));
554 $ew = $wgUser->getOption( 'editwidth' );
555 if ( $ew ) $ew = " style=\"width:100%\"";
559 $sub = wfMsgHtml( 'uploaderror' );
560 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
561 "<span class='error'>{$msg}</span>\n" );
563 $wgOut->addHTML( '<div id="uploadtext">' );
564 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
565 $wgOut->addHTML( '</div>' );
566 $sk = $wgUser->getSkin();
569 $sourcefilename = wfMsgHtml( 'sourcefilename' );
570 $destfilename = wfMsgHtml( 'destfilename' );
571 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
573 $licenses = new Licenses();
574 $license = wfMsgHtml( 'license' );
575 $nolicense = wfMsgHtml( 'nolicense' );
576 $licenseshtml = $licenses->getHtml();
578 $ulb = wfMsgHtml( 'uploadbtn' );
581 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
582 $action = $titleObj->escapeLocalURL();
584 $encDestFile = htmlspecialchars( $this->mDestFile
);
586 $watchChecked = $wgUser->getOption( 'watchdefault' )
587 ?
'checked="checked"'
591 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
594 <td align='right'>{$sourcefilename}:</td>
596 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?
"":"onchange='fillDestFilename()' ") . "size='40' />
600 <td align='right'>{$destfilename}:</td>
602 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
606 <td align='right'>{$summary}</td>
608 <textarea tabindex='3' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
613 if ( $licenseshtml != '' ) {
615 <td align='right'>$license:</td>
617 <select name='wpLicense' tabindex='4'>
618 <option value=''>$nolicense</option>
627 if ( $wgUseCopyrightUpload ) {
628 $filestatus = wfMsgHtml ( 'filestatus' );
629 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
630 $filesource = wfMsgHtml ( 'filesource' );
631 $uploadsource = htmlspecialchars( $this->mUploadSource
);
634 <td align='right' nowrap='nowrap'>$filestatus:</td>
635 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
638 <td align='right'>$filesource:</td>
639 <td><input tabindex='6' type='text' name='wpUploadSource' value=\"$uploadsource\" size='40' /></td>
649 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
650 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
651 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
652 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
660 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
666 /* -------------------------------------------------------------- */
669 * Split a file into a base name and all dot-delimited 'extensions'
670 * on the end. Some web server configurations will fall back to
671 * earlier pseudo-'extensions' to determine type and execute
672 * scripts, so the blacklist needs to check them all.
676 function splitExtensions( $filename ) {
677 $bits = explode( '.', $filename );
678 $basename = array_shift( $bits );
679 return array( $basename, $bits );
683 * Perform case-insensitive match against a list of file extensions.
684 * Returns true if the extension is in the list.
690 function checkFileExtension( $ext, $list ) {
691 return in_array( strtolower( $ext ), $list );
695 * Perform case-insensitive match against a list of file extensions.
696 * Returns true if any of the extensions are in the list.
702 function checkFileExtensionList( $ext, $list ) {
703 foreach( $ext as $e ) {
704 if( in_array( strtolower( $e ), $list ) ) {
712 * Verifies that it's ok to include the uploaded file
714 * @param string $tmpfile the full path of the temporary file to verify
715 * @param string $extension The filename extension that the file is to be served with
716 * @return mixed true of the file is verified, a WikiError object otherwise.
718 function verify( $tmpfile, $extension ) {
719 #magically determine mime type
720 $magic=& wfGetMimeMagic();
721 $mime= $magic->guessMimeType($tmpfile,false);
723 $fname= "SpecialUpload::verify";
725 #check mime type, if desired
726 global $wgVerifyMimeType;
727 if ($wgVerifyMimeType) {
729 #check mime type against file extension
730 if( !$this->verifyExtension( $mime, $extension ) ) {
731 return new WikiErrorMsg( 'uploadcorrupt' );
734 #check mime type blacklist
735 global $wgMimeTypeBlacklist;
736 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
737 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
738 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
742 #check for htmlish code and javascript
743 if( $this->detectScript ( $tmpfile, $mime ) ) {
744 return new WikiErrorMsg( 'uploadscripted' );
748 * Scan the uploaded file for viruses
750 $virus= $this->detectVirus($tmpfile);
752 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
755 wfDebug( "$fname: all clear; passing.\n" );
760 * Checks if the mime type of the uploaded file matches the file extension.
762 * @param string $mime the mime type of the uploaded file
763 * @param string $extension The filename extension that the file is to be served with
766 function verifyExtension( $mime, $extension ) {
767 $fname = 'SpecialUpload::verifyExtension';
769 $magic =& wfGetMimeMagic();
771 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
772 if ( ! $magic->isRecognizableExtension( $extension ) ) {
773 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
776 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
780 $match= $magic->isMatchingExtension($extension,$mime);
783 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
785 } elseif ($match===true) {
786 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
788 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
792 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
797 /** Heuristig for detecting files that *could* contain JavaScript instructions or
798 * things that may look like HTML to a browser and are thus
799 * potentially harmful. The present implementation will produce false positives in some situations.
801 * @param string $file Pathname to the temporary upload file
802 * @param string $mime The mime type of the file
803 * @return bool true if the file contains something looking like embedded scripts
805 function detectScript($file,$mime) {
807 #ugly hack: for text files, always look at the entire file.
808 #For binarie field, just check the first K.
810 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
812 $fp = fopen( $file, 'rb' );
813 $chunk = fread( $fp, 1024 );
817 $chunk= strtolower( $chunk );
819 if (!$chunk) return false;
821 #decode from UTF-16 if needed (could be used for obfuscation).
822 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
823 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
826 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
828 $chunk= trim($chunk);
830 #FIXME: convert from UTF-16 if necessarry!
832 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
834 #check for HTML doctype
835 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
838 * Internet Explorer for Windows performs some really stupid file type
839 * autodetection which can cause it to interpret valid image files as HTML
840 * and potentially execute JavaScript, creating a cross-site scripting
843 * Apple's Safari browser also performs some unsafe file type autodetection
844 * which can cause legitimate files to be interpreted as HTML if the
845 * web server is not correctly configured to send the right content-type
846 * (or if you're really uploading plain text and octet streams!)
848 * Returns true if IE is likely to mistake the given file for HTML.
849 * Also returns true if Safari would mistake the given file for HTML
850 * when served with a generic content-type.
856 '<html', #also in safari
859 '<script', #also in safari
861 '<title' #also in safari
864 foreach( $tags as $tag ) {
865 if( false !== strpos( $chunk, $tag ) ) {
871 * look for javascript
874 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
875 $chunk = Sanitizer
::decodeCharReferences( $chunk );
877 #look for script-types
878 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
880 #look for html-style script-urls
881 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
883 #look for css-style script-urls
884 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
886 wfDebug("SpecialUpload::detectScript: no scripts found\n");
890 /** Generic wrapper function for a virus scanner program.
891 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
892 * $wgAntivirusRequired may be used to deny upload if the scan fails.
894 * @param string $file Pathname to the temporary upload file
895 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
896 * or a string containing feedback from the virus scanner if a virus was found.
897 * If textual feedback is missing but a virus was found, this function returns true.
899 function detectVirus($file) {
900 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
902 $fname= "SpecialUpload::detectVirus";
904 if (!$wgAntivirus) { #disabled?
905 wfDebug("$fname: virus scanner disabled\n");
910 if (!$wgAntivirusSetup[$wgAntivirus]) {
911 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
913 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
915 return "unknown antivirus: $wgAntivirus";
918 #look up scanner configuration
919 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
920 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
921 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
923 $scanner= $virus_scanner; #copy, so we can resolve the pattern
925 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
926 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
928 wfDebug("$fname: running virus scan: $scanner \n");
930 #execute virus scanner
933 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
934 # that does not seem to be worth the pain.
935 # Ask me (Duesentrieb) about it if it's ever needed.
936 if (wfIsWindows()) exec("$scanner",$output,$code);
937 else exec("$scanner 2>&1",$output,$code);
939 $exit_code= $code; #remeber for user feedback
941 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
942 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
943 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
946 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
947 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
949 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
952 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
953 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
956 else if ($code===AV_NO_VIRUS
) {
957 wfDebug("$fname: file passed virus scan.\n");
958 return false; #no virus found
961 $output= join("\n",$output);
962 $output= trim($output);
964 if (!$output) $output= true; #if ther's no output, return true
965 else if ($msg_pattern) {
967 if (preg_match($msg_pattern,$output,$groups)) {
968 if ($groups[1]) $output= $groups[1];
972 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
978 * Check if the temporary file is MacBinary-encoded, as some uploads
979 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
980 * If so, the data fork will be extracted to a second temporary file,
981 * which will then be checked for validity and either kept or discarded.
985 function checkMacBinary() {
986 $macbin = new MacBinary( $this->mUploadTempName
);
987 if( $macbin->isValid() ) {
988 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
989 $dataHandle = fopen( $dataFile, 'wb' );
991 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
992 $macbin->extractData( $dataHandle );
994 $this->mUploadTempName
= $dataFile;
995 $this->mUploadSize
= $macbin->dataForkLength();
997 // We'll have to manually remove the new file if it's not kept.
998 $this->mRemoveTempFile
= true;
1004 * If we've modified the upload file we need to manually remove it
1005 * on exit to clean up.
1008 function cleanupTempFile() {
1009 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1010 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1011 unlink( $this->mUploadTempName
);
1016 * Check if there's an overwrite conflict and, if so, if restrictions
1017 * forbid this user from performing the upload.
1019 * @return mixed true on success, WikiError on failure
1022 function checkOverwrite( $name ) {
1023 $img = Image
::newFromName( $name );
1024 if( is_null( $img ) ) {
1025 // Uh... this shouldn't happen ;)
1026 // But if it does, fall through to previous behavior
1031 if( $img->exists() ) {
1032 global $wgUser, $wgOut;
1033 if( $img->isLocal() ) {
1034 if( !$wgUser->isAllowed( 'reupload' ) ) {
1035 $error = 'fileexists-forbidden';
1038 if( !$wgUser->isAllowed( 'reupload' ) ||
1039 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1040 $error = "fileexists-shared-forbidden";
1046 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1047 return new WikiError( $wgOut->parse( $errorText ) );
1050 // Rockin', go ahead and upload