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