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