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