* (bug 3076) Support MacBinary-encoded uploads from IE/Mac
[lhc/web/wiklou.git] / includes / SpecialUpload.php
1 <?php
2 /**
3 *
4 * @package MediaWiki
5 * @subpackage SpecialPage
6 */
7
8 /**
9 *
10 */
11 require_once( 'Image.php' );
12 require_once( 'MacBinary.php' );
13
14 /**
15 * Entry point
16 */
17 function wfSpecialUpload() {
18 global $wgRequest;
19 $form = new UploadForm( $wgRequest );
20 $form->execute();
21 }
22
23 /**
24 *
25 * @package MediaWiki
26 * @subpackage SpecialPage
27 */
28 class UploadForm {
29 /**#@+
30 * @access private
31 */
32 var $mUploadFile, $mUploadDescription, $mIgnoreWarning;
33 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
34 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
35 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile;
36 /**#@-*/
37
38 /**
39 * Constructor : initialise object
40 * Get data POSTed through the form and assign them to the object
41 * @param $request Data posted.
42 */
43 function UploadForm( &$request ) {
44 $this->mDestFile = $request->getText( 'wpDestFile' );
45
46 if( !$request->wasPosted() ) {
47 # GET requests just give the main form; no data except wpDestfile.
48 return;
49 }
50
51 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning');
52 $this->mReUpload = $request->getCheck( 'wpReUpload' );
53 $this->mUpload = $request->getCheck( 'wpUpload' );
54
55 $this->mUploadDescription = $request->getText( 'wpUploadDescription' );
56 $this->mUploadCopyStatus = $request->getText( 'wpUploadCopyStatus' );
57 $this->mUploadSource = $request->getText( 'wpUploadSource');
58
59 $this->mAction = $request->getVal( 'action' );
60
61 $this->mSessionKey = $request->getInt( 'wpSessionKey' );
62 if( !empty( $this->mSessionKey ) &&
63 isset( $_SESSION['wsUploadData'][$this->mSessionKey] ) ) {
64 /**
65 * Confirming a temporarily stashed upload.
66 * We don't want path names to be forged, so we keep
67 * them in the session on the server and just give
68 * an opaque key to the user agent.
69 */
70 $data = $_SESSION['wsUploadData'][$this->mSessionKey];
71 $this->mUploadTempName = $data['mUploadTempName'];
72 $this->mUploadSize = $data['mUploadSize'];
73 $this->mOname = $data['mOname'];
74 $this->mStashed = true;
75 $this->mRemoveTempFile = false;
76 } else {
77 /**
78 *Check for a newly uploaded file.
79 */
80 $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
81 $this->mUploadSize = $request->getFileSize( 'wpUploadFile' );
82 $this->mOname = $request->getFileName( 'wpUploadFile' );
83 $this->mSessionKey = false;
84 $this->mStashed = false;
85 $this->mRemoveTempFile = false; // PHP will handle this
86 }
87 }
88
89 /**
90 * Start doing stuff
91 * @access public
92 */
93 function execute() {
94 global $wgUser, $wgOut;
95 global $wgEnableUploads, $wgUploadDirectory;
96
97 /** Show an error message if file upload is disabled */
98 if( ! $wgEnableUploads ) {
99 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
100 return;
101 }
102
103 /** Various rights checks */
104 if( !$wgUser->isAllowed( 'upload' ) || $wgUser->isBlocked() ) {
105 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
106 return;
107 }
108 if( wfReadOnly() ) {
109 $wgOut->readOnlyPage();
110 return;
111 }
112
113 /** Check if the image directory is writeable, this is a common mistake */
114 if ( !is_writeable( $wgUploadDirectory ) ) {
115 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
116 return;
117 }
118
119 if( $this->mReUpload ) {
120 $this->unsaveUploadedFile();
121 $this->mainUploadForm();
122 } else if ( 'submit' == $this->mAction || $this->mUpload ) {
123 $this->processUpload();
124 } else {
125 $this->mainUploadForm();
126 }
127
128 $this->cleanupTempFile();
129 }
130
131 /* -------------------------------------------------------------- */
132
133 /**
134 * Really do the upload
135 * Checks are made in SpecialUpload::execute()
136 * @access private
137 */
138 function processUpload() {
139 global $wgUser, $wgOut, $wgLang, $wgContLang;
140 global $wgUploadDirectory;
141 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
142
143 /**
144 * If there was no filename or a zero size given, give up quick.
145 */
146 if( trim( $this->mOname ) == '' || empty( $this->mUploadSize ) ) {
147 return $this->mainUploadForm('<li>'.wfMsg( 'emptyfile' ).'</li>');
148 }
149
150 # Chop off any directories in the given filename
151 if ( $this->mDestFile ) {
152 $basename = basename( $this->mDestFile );
153 } else {
154 $basename = basename( $this->mOname );
155 }
156
157 /**
158 * We'll want to blacklist against *any* 'extension', and use
159 * only the final one for the whitelist.
160 */
161 list( $partname, $ext ) = $this->splitExtensions( $basename );
162 if( count( $ext ) ) {
163 $finalExt = $ext[count( $ext ) - 1];
164 } else {
165 $finalExt = '';
166 }
167 $fullExt = implode( '.', $ext );
168
169 if ( strlen( $partname ) < 3 ) {
170 $this->mainUploadForm( wfMsg( 'minlength' ) );
171 return;
172 }
173
174 /**
175 * Filter out illegal characters, and try to make a legible name
176 * out of it. We'll strip some silently that Title would die on.
177 */
178 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
179 $nt = Title::newFromText( $filtered );
180 if( is_null( $nt ) ) {
181 return $this->uploadError( wfMsg( 'illegalfilename', htmlspecialchars( $filtered ) ) );
182 }
183 $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() );
184 $this->mUploadSaveName = $nt->getDBkey();
185
186 /**
187 * If the image is protected, non-sysop users won't be able
188 * to modify it by uploading a new revision.
189 */
190 if( !$nt->userCanEdit() ) {
191 return $this->uploadError( wfMsg( 'protectedpage' ) );
192 }
193
194 /* Don't allow users to override the blacklist (check file extension) */
195 global $wgStrictFileExtensions;
196 global $wgFileExtensions, $wgFileBlacklist;
197 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
198 ($wgStrictFileExtensions &&
199 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
200 return $this->uploadError( wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ) );
201 }
202
203 /**
204 * Look at the contents of the file; if we can recognize the
205 * type but it's corrupt or data of the wrong type, we should
206 * probably not accept it.
207 */
208 if( !$this->mStashed ) {
209 $this->checkMacBinary();
210 $veri = $this->verify( $this->mUploadTempName, $finalExt );
211
212 if( $veri !== true ) { //it's a wiki error...
213 return $this->uploadError( $veri->toString() );
214 }
215 }
216
217 /**
218 * Check for non-fatal conditions
219 */
220 if ( ! $this->mIgnoreWarning ) {
221 $warning = '';
222 if( $this->mUploadSaveName != ucfirst( $filtered ) ) {
223 $warning .= '<li>'.wfMsg( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
224 }
225
226 global $wgCheckFileExtensions;
227 if ( $wgCheckFileExtensions ) {
228 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
229 $warning .= '<li>'.wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
230 }
231 }
232
233 global $wgUploadSizeWarning;
234 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
235 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
236 # value, perhaps add GB,MB and KB suffixes?
237 $warning .= '<li>'.wfMsg( 'largefile', $wgUploadSizeWarning, $this->mUploadSize ).'</li>';
238 }
239 if ( $this->mUploadSize == 0 ) {
240 $warning .= '<li>'.wfMsg( 'emptyfile' ).'</li>';
241 }
242
243 if( $nt->getArticleID() ) {
244 global $wgUser;
245 $sk = $wgUser->getSkin();
246 $dlink = $sk->makeKnownLinkObj( $nt );
247 $warning .= '<li>'.wfMsg( 'fileexists', $dlink ).'</li>';
248 }
249
250 if( $warning != '' ) {
251 /**
252 * Stash the file in a temporary location; the user can choose
253 * to let it through and we'll complete the upload then.
254 */
255 return $this->uploadWarning($warning);
256 }
257 }
258
259 /**
260 * Try actually saving the thing...
261 * It will show an error form on failure.
262 */
263 $hasBeenMunged = !empty( $this->mSessionKey ) || $this->mRemoveTempFile;
264 if( $this->saveUploadedFile( $this->mUploadSaveName,
265 $this->mUploadTempName,
266 $hasBeenMunged ) ) {
267 /**
268 * Update the upload log and create the description page
269 * if it's a new file.
270 */
271 $img = Image::newFromName( $this->mUploadSaveName );
272 $success = $img->recordUpload( $this->mUploadOldVersion,
273 $this->mUploadDescription,
274 $this->mUploadCopyStatus,
275 $this->mUploadSource );
276
277 if ( $success ) {
278 $this->showSuccess();
279 } else {
280 // Image::recordUpload() fails if the image went missing, which is
281 // unlikely, hence the lack of a specialised message
282 $wgOut->fileNotFoundError( $this->mUploadSaveName );
283 }
284 }
285 }
286
287 /**
288 * Move the uploaded file from its temporary location to the final
289 * destination. If a previous version of the file exists, move
290 * it into the archive subdirectory.
291 *
292 * @todo If the later save fails, we may have disappeared the original file.
293 *
294 * @param string $saveName
295 * @param string $tempName full path to the temporary file
296 * @param bool $useRename if true, doesn't check that the source file
297 * is a PHP-managed upload temporary
298 */
299 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
300 global $wgUploadDirectory, $wgOut;
301
302 $fname= "SpecialUpload::saveUploadedFile";
303
304 $dest = wfImageDir( $saveName );
305 $archive = wfImageArchiveDir( $saveName );
306 $this->mSavedFile = "{$dest}/{$saveName}";
307
308 if( is_file( $this->mSavedFile ) ) {
309 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
310 wfSuppressWarnings();
311 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
312 wfRestoreWarnings();
313
314 if( ! $success ) {
315 $wgOut->fileRenameError( $this->mSavedFile,
316 "${archive}/{$this->mUploadOldVersion}" );
317 return false;
318 }
319 else wfDebug("$fname: moved file ".$this->mSavedFile." to ${archive}/{$this->mUploadOldVersion}\n");
320 }
321 else {
322 $this->mUploadOldVersion = '';
323 }
324
325 wfSuppressWarnings();
326 $success = $useRename
327 ? rename( $tempName, $this->mSavedFile )
328 : move_uploaded_file( $tempName, $this->mSavedFile );
329 wfRestoreWarnings();
330
331 if( ! $success ) {
332 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
333 return false;
334 } else {
335 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
336 }
337
338 chmod( $this->mSavedFile, 0644 );
339 return true;
340 }
341
342 /**
343 * Stash a file in a temporary directory for later processing
344 * after the user has confirmed it.
345 *
346 * If the user doesn't explicitly cancel or accept, these files
347 * can accumulate in the temp directory.
348 *
349 * @param string $saveName - the destination filename
350 * @param string $tempName - the source temporary file to save
351 * @return string - full path the stashed file, or false on failure
352 * @access private
353 */
354 function saveTempUploadedFile( $saveName, $tempName ) {
355 global $wgOut;
356 $archive = wfImageArchiveDir( $saveName, 'temp' );
357 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
358
359 $success = $this->mRemoveTempFile
360 ? rename( $tempName, $stash )
361 : move_uploaded_file( $tempName, $stash );
362 if ( !$success ) {
363 $wgOut->fileCopyError( $tempName, $stash );
364 return false;
365 }
366
367 return $stash;
368 }
369
370 /**
371 * Stash a file in a temporary directory for later processing,
372 * and save the necessary descriptive info into the session.
373 * Returns a key value which will be passed through a form
374 * to pick up the path info on a later invocation.
375 *
376 * @return int
377 * @access private
378 */
379 function stashSession() {
380 $stash = $this->saveTempUploadedFile(
381 $this->mUploadSaveName, $this->mUploadTempName );
382
383 if( !$stash ) {
384 # Couldn't save the file.
385 return false;
386 }
387
388 $key = mt_rand( 0, 0x7fffffff );
389 $_SESSION['wsUploadData'][$key] = array(
390 'mUploadTempName' => $stash,
391 'mUploadSize' => $this->mUploadSize,
392 'mOname' => $this->mOname );
393 return $key;
394 }
395
396 /**
397 * Remove a temporarily kept file stashed by saveTempUploadedFile().
398 * @access private
399 */
400 function unsaveUploadedFile() {
401 wfSuppressWarnings();
402 $success = unlink( $this->mUploadTempName );
403 wfRestoreWarnings();
404 if ( ! $success ) {
405 $wgOut->fileDeleteError( $this->mUploadTempName );
406 }
407 }
408
409 /* -------------------------------------------------------------- */
410
411 /**
412 * Show some text and linkage on successful upload.
413 * @access private
414 */
415 function showSuccess() {
416 global $wgUser, $wgOut, $wgContLang;
417
418 $sk = $wgUser->getSkin();
419 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
420 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
421 $dlink = $sk->makeKnownLink( $dname, $dname );
422
423 $wgOut->addHTML( '<h2>' . wfMsg( 'successfulupload' ) . "</h2>\n" );
424 $text = wfMsg( 'fileuploaded', $ilink, $dlink );
425 $wgOut->addHTML( $text );
426 $wgOut->returnToMain( false );
427 }
428
429 /**
430 * @param string $error as HTML
431 * @access private
432 */
433 function uploadError( $error ) {
434 global $wgOut;
435 $sub = wfMsg( 'uploadwarning' );
436 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
437 $wgOut->addHTML( "<h4 class='error'>{$error}</h4>\n" );
438 }
439
440 /**
441 * There's something wrong with this file, not enough to reject it
442 * totally but we require manual intervention to save it for real.
443 * Stash it away, then present a form asking to confirm or cancel.
444 *
445 * @param string $warning as HTML
446 * @access private
447 */
448 function uploadWarning( $warning ) {
449 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
450 global $wgUseCopyrightUpload;
451
452 $this->mSessionKey = $this->stashSession();
453 if( !$this->mSessionKey ) {
454 # Couldn't save file; an error has been displayed so let's go.
455 return;
456 }
457
458 $sub = wfMsg( 'uploadwarning' );
459 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
460 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
461
462 $save = wfMsg( 'savefile' );
463 $reupload = wfMsg( 'reupload' );
464 $iw = wfMsg( 'ignorewarning' );
465 $reup = wfMsg( 'reuploaddesc' );
466 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
467 $action = $titleObj->escapeLocalURL( 'action=submit' );
468
469 if ( $wgUseCopyrightUpload )
470 {
471 $copyright = "
472 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
473 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
474 ";
475 } else {
476 $copyright = "";
477 }
478
479 $wgOut->addHTML( "
480 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
481 <input type='hidden' name='wpIgnoreWarning' value='1' />
482 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
483 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
484 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile ) . "\" />
485 {$copyright}
486 <table border='0'>
487 <tr>
488 <tr>
489 <td align='right'>
490 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
491 </td>
492 <td align='left'>$iw</td>
493 </tr>
494 <tr>
495 <td align='right'>
496 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
497 </td>
498 <td align='left'>$reup</td>
499 </tr>
500 </tr>
501 </table></form>\n" );
502 }
503
504 /**
505 * Displays the main upload form, optionally with a highlighted
506 * error message up at the top.
507 *
508 * @param string $msg as HTML
509 * @access private
510 */
511 function mainUploadForm( $msg='' ) {
512 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
513 global $wgUseCopyrightUpload;
514
515 $cols = intval($wgUser->getOption( 'cols' ));
516 $ew = $wgUser->getOption( 'editwidth' );
517 if ( $ew ) $ew = " style=\"width:100%\"";
518 else $ew = '';
519
520 if ( '' != $msg ) {
521 $sub = wfMsg( 'uploaderror' );
522 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
523 "<h4 class='error'>{$msg}</h4>\n" );
524 }
525 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
526 $sk = $wgUser->getSkin();
527
528
529 $sourcefilename = wfMsg( 'sourcefilename' );
530 $destfilename = wfMsg( 'destfilename' );
531
532 $fd = wfMsg( 'filedesc' );
533 $ulb = wfMsg( 'uploadbtn' );
534
535 $iw = wfMsg( 'ignorewarning' );
536
537 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
538 $action = $titleObj->escapeLocalURL();
539
540 $encDestFile = htmlspecialchars( $this->mDestFile );
541 $source = null;
542
543 if ( $wgUseCopyrightUpload )
544 {
545 $source = "
546 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
547 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
548 htmlspecialchars($this->mUploadCopyStatus). "\" size='40' /></td>
549 </tr><tr>
550 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
551 <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
552 htmlspecialchars($this->mUploadSource). "\" size='40' /></td>
553 " ;
554 }
555
556 $wgOut->addHTML( "
557 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
558 <table border='0'><tr>
559
560 <td align='right'>{$sourcefilename}:</td><td align='left'>
561 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onchange='fillDestFilename()' size='40' />
562 </td></tr><tr>
563
564 <td align='right'>{$destfilename}:</td><td align='left'>
565 <input tabindex='1' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
566 </td></tr><tr>
567
568 <td align='right'>{$fd}:</td><td align='left'>
569 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
570 . htmlspecialchars( $this->mUploadDescription ) .
571 "</textarea>
572 </td></tr><tr>
573 {$source}
574 </tr>
575 <tr><td></td><td align='left'>
576 <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
577 </td></tr></table></form>\n" );
578 }
579
580 /* -------------------------------------------------------------- */
581
582 /**
583 * Split a file into a base name and all dot-delimited 'extensions'
584 * on the end. Some web server configurations will fall back to
585 * earlier pseudo-'extensions' to determine type and execute
586 * scripts, so the blacklist needs to check them all.
587 *
588 * @return array
589 */
590 function splitExtensions( $filename ) {
591 $bits = explode( '.', $filename );
592 $basename = array_shift( $bits );
593 return array( $basename, $bits );
594 }
595
596 /**
597 * Perform case-insensitive match against a list of file extensions.
598 * Returns true if the extension is in the list.
599 *
600 * @param string $ext
601 * @param array $list
602 * @return bool
603 */
604 function checkFileExtension( $ext, $list ) {
605 return in_array( strtolower( $ext ), $list );
606 }
607
608 /**
609 * Perform case-insensitive match against a list of file extensions.
610 * Returns true if any of the extensions are in the list.
611 *
612 * @param array $ext
613 * @param array $list
614 * @return bool
615 */
616 function checkFileExtensionList( $ext, $list ) {
617 foreach( $ext as $e ) {
618 if( in_array( strtolower( $e ), $list ) ) {
619 return true;
620 }
621 }
622 return false;
623 }
624
625 /**
626 * Verifies that it's ok to include the uploaded file
627 *
628 * @param string $tmpfile the full path of the temporary file to verify
629 * @param string $extension The filename extension that the file is to be served with
630 * @return mixed true of the file is verified, a WikiError object otherwise.
631 */
632 function verify( $tmpfile, $extension ) {
633 #magically determine mime type
634 $magic=& wfGetMimeMagic();
635 $mime= $magic->guessMimeType($tmpfile,false);
636
637 $fname= "SpecialUpload::verify";
638
639 #check mime type, if desired
640 global $wgVerifyMimeType;
641 if ($wgVerifyMimeType) {
642
643 #check mime type against file extension
644 if( !$this->verifyExtension( $mime, $extension ) ) {
645 return new WikiErrorMsg( 'uploadcorrupt' );
646 }
647
648 #check mime type blacklist
649 global $wgMimeTypeBlacklist;
650 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
651 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
652 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
653 }
654 }
655
656 #check for htmlish code and javascript
657 if( $this->detectScript ( $tmpfile, $mime ) ) {
658 return new WikiErrorMsg( 'uploadscripted' );
659 }
660
661 /**
662 * Scan the uploaded file for viruses
663 */
664 $virus= $this->detectVirus($tmpfile);
665 if ( $virus ) {
666 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
667 }
668
669 wfDebug( "$fname: all clear; passing.\n" );
670 return true;
671 }
672
673 /**
674 * Checks if the mime type of the uploaded file matches the file extension.
675 *
676 * @param string $mime the mime type of the uploaded file
677 * @param string $extension The filename extension that the file is to be served with
678 * @return bool
679 */
680 function verifyExtension( $mime, $extension ) {
681 $fname = 'SpecialUpload::verifyExtension';
682
683 if (!$mime || $mime=="unknown" || $mime=="unknown/unknown") {
684 wfDebug( "$fname: passing file with unknown mime type\n" );
685 return true;
686 }
687
688 $magic=& wfGetMimeMagic();
689
690 $match= $magic->isMatchingExtension($extension,$mime);
691
692 if ($match===NULL) {
693 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
694 return true;
695 } elseif ($match===true) {
696 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
697
698 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
699 return true;
700
701 } else {
702 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
703 return false;
704 }
705 }
706
707 /** Heuristig for detecting files that *could* contain JavaScript instructions or
708 * things that may look like HTML to a browser and are thus
709 * potentially harmful. The present implementation will produce false positives in some situations.
710 *
711 * @param string $file Pathname to the temporary upload file
712 * @param string $mime The mime type of the file
713 * @return bool true if the file contains something looking like embedded scripts
714 */
715 function detectScript($file,$mime) {
716
717 #ugly hack: for text files, always look at the entire file.
718 #For binarie field, just check the first K.
719
720 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
721 else {
722 $fp = fopen( $file, 'rb' );
723 $chunk = fread( $fp, 1024 );
724 fclose( $fp );
725 }
726
727 $chunk= strtolower( $chunk );
728
729 if (!$chunk) return false;
730
731 #decode from UTF-16 if needed (could be used for obfuscation).
732 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
733 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
734 else $enc= NULL;
735
736 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
737
738 $chunk= trim($chunk);
739
740 #FIXME: convert from UTF-16 if necessarry!
741
742 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
743
744 #check for HTML doctype
745 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
746
747 /**
748 * Internet Explorer for Windows performs some really stupid file type
749 * autodetection which can cause it to interpret valid image files as HTML
750 * and potentially execute JavaScript, creating a cross-site scripting
751 * attack vectors.
752 *
753 * Apple's Safari browser also performs some unsafe file type autodetection
754 * which can cause legitimate files to be interpreted as HTML if the
755 * web server is not correctly configured to send the right content-type
756 * (or if you're really uploading plain text and octet streams!)
757 *
758 * Returns true if IE is likely to mistake the given file for HTML.
759 * Also returns true if Safari would mistake the given file for HTML
760 * when served with a generic content-type.
761 */
762
763 $tags = array(
764 '<body',
765 '<head',
766 '<html', #also in safari
767 '<img',
768 '<pre',
769 '<script', #also in safari
770 '<table',
771 '<title' #also in safari
772 );
773
774 foreach( $tags as $tag ) {
775 if( false !== strpos( $chunk, $tag ) ) {
776 return true;
777 }
778 }
779
780 /*
781 * look for javascript
782 */
783
784 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
785 $chunk = Sanitizer::decodeCharReferences( $chunk );
786
787 #look for script-types
788 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
789
790 #look for html-style script-urls
791 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
792
793 #look for css-style script-urls
794 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
795
796 wfDebug("SpecialUpload::detectScript: no scripts found\n");
797 return false;
798 }
799
800 /** Generic wrapper function for a virus scanner program.
801 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
802 * $wgAntivirusRequired may be used to deny upload if the scan fails.
803 *
804 * @param string $file Pathname to the temporary upload file
805 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
806 * or a string containing feedback from the virus scanner if a virus was found.
807 * If textual feedback is missing but a virus was found, this function returns true.
808 */
809 function detectVirus($file) {
810 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
811
812 $fname= "SpecialUpload::detectVirus";
813
814 if (!$wgAntivirus) { #disabled?
815 wfDebug("$fname: virus scanner disabled\n");
816
817 return NULL;
818 }
819
820 if (!$wgAntivirusSetup[$wgAntivirus]) {
821 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
822
823 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
824
825 return "unknown antivirus: $wgAntivirus";
826 }
827
828 #look up scanner configuration
829 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
830 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
831 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
832
833 $scanner= $virus_scanner; #copy, so we can resolve the pattern
834
835 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
836 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
837
838 wfDebug("$fname: running virus scan: $scanner \n");
839
840 #execute virus scanner
841 $code= false;
842
843 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
844 # that does not seem to be worth the pain.
845 # Ask me (Duesentrieb) about it if it's ever needed.
846 if (wfIsWindows()) exec("$scanner",$output,$code);
847 else exec("$scanner 2>&1",$output,$code);
848
849 $exit_code= $code; #remeber for user feedback
850
851 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
852 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
853 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
854 }
855
856 if ($code===AV_SCAN_FAILED) { #scan failed (code was mapped to false by $virus_scanner_codes)
857 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
858
859 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
860 else return NULL;
861 }
862 else if ($code===AV_SCAN_ABORTED) { #scan failed because filetype is unknown (probably imune)
863 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
864 return NULL;
865 }
866 else if ($code===AV_NO_VIRUS) {
867 wfDebug("$fname: file passed virus scan.\n");
868 return false; #no virus found
869 }
870 else {
871 $output= join("\n",$output);
872 $output= trim($output);
873
874 if (!$output) $output= true; #if ther's no output, return true
875 else if ($msg_pattern) {
876 $groups= array();
877 if (preg_match($msg_pattern,$output,$groups)) {
878 if ($groups[1]) $output= $groups[1];
879 }
880 }
881
882 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
883 return $output;
884 }
885 }
886
887 /**
888 * Check if the temporary file is MacBinary-encoded, as some uploads
889 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
890 * If so, the data fork will be extracted to a second temporary file,
891 * which will then be checked for validity and either kept or discarded.
892 *
893 * @access private
894 */
895 function checkMacBinary() {
896 $macbin = new MacBinary( $this->mUploadTempName );
897 if( $macbin->isValid() ) {
898 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
899 $dataHandle = fopen( $dataFile, 'wb' );
900
901 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
902 $macbin->extractData( $dataHandle );
903
904 $this->mUploadTempName = $dataFile;
905 $this->mUploadSize = $macbin->dataForkLength();
906
907 // We'll have to manually remove the new file if it's not kept.
908 $this->mRemoveTempFile = true;
909 }
910 $macbin->close();
911 }
912
913 /**
914 * If we've modified the upload file we need to manually remove it
915 * on exit to clean up.
916 * @access private
917 */
918 function cleanupTempFile() {
919 if( $this->mRemoveTempFile && file_exists( $this->mUploadTempName ) ) {
920 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
921 unlink( $this->mUploadTempName );
922 }
923 }
924
925 }
926 ?>