* Fixed unclosed <p> tag
[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 $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->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning');
51 $this->mReUpload = $request->getCheck( 'wpReUpload' );
52 $this->mUpload = $request->getCheck( 'wpUpload' );
53
54 $this->mUploadDescription = $request->getText( 'wpUploadDescription' );
55 $this->mUploadCopyStatus = $request->getText( 'wpUploadCopyStatus' );
56 $this->mUploadSource = $request->getText( 'wpUploadSource');
57
58 $this->mAction = $request->getVal( 'action' );
59
60 $this->mSessionKey = $request->getInt( 'wpSessionKey' );
61 if( !empty( $this->mSessionKey ) &&
62 isset( $_SESSION['wsUploadData'][$this->mSessionKey] ) ) {
63 /**
64 * Confirming a temporarily stashed upload.
65 * We don't want path names to be forged, so we keep
66 * them in the session on the server and just give
67 * an opaque key to the user agent.
68 */
69 $data = $_SESSION['wsUploadData'][$this->mSessionKey];
70 $this->mUploadTempName = $data['mUploadTempName'];
71 $this->mUploadSize = $data['mUploadSize'];
72 $this->mOname = $data['mOname'];
73 $this->mStashed = true;
74 } else {
75 /**
76 *Check for a newly uploaded file.
77 */
78 $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
79 $this->mUploadSize = $request->getFileSize( 'wpUploadFile' );
80 $this->mOname = $request->getFileName( 'wpUploadFile' );
81 $this->mSessionKey = false;
82 $this->mStashed = false;
83 }
84 }
85
86 /**
87 * Start doing stuff
88 * @access public
89 */
90 function execute() {
91 global $wgUser, $wgOut;
92 global $wgEnableUploads, $wgUploadDirectory;
93
94 /** Show an error message if file upload is disabled */
95 if( ! $wgEnableUploads ) {
96 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
97 return;
98 }
99
100 /** Various rights checks */
101 if( !$wgUser->isAllowed( 'upload' ) || $wgUser->isBlocked() ) {
102 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
103 return;
104 }
105 if( wfReadOnly() ) {
106 $wgOut->readOnlyPage();
107 return;
108 }
109
110 /** Check if the image directory is writeable, this is a common mistake */
111 if ( !is_writeable( $wgUploadDirectory ) ) {
112 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
113 return;
114 }
115
116 if( $this->mReUpload ) {
117 $this->unsaveUploadedFile();
118 $this->mainUploadForm();
119 } else if ( 'submit' == $this->mAction || $this->mUpload ) {
120 $this->processUpload();
121 } else {
122 $this->mainUploadForm();
123 }
124 }
125
126 /* -------------------------------------------------------------- */
127
128 /**
129 * Really do the upload
130 * Checks are made in SpecialUpload::execute()
131 * @access private
132 */
133 function processUpload() {
134 global $wgUser, $wgOut, $wgLang, $wgContLang;
135 global $wgUploadDirectory;
136 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
137
138 /**
139 * If there was no filename or a zero size given, give up quick.
140 */
141 if( trim( $this->mOname ) == '' || empty( $this->mUploadSize ) ) {
142 return $this->mainUploadForm('<li>'.wfMsg( 'emptyfile' ).'</li>');
143 }
144
145 # Chop off any directories in the given filename
146 if ( $this->mDestFile ) {
147 $basename = basename( $this->mDestFile );
148 } else {
149 $basename = basename( $this->mOname );
150 }
151
152 /**
153 * We'll want to blacklist against *any* 'extension', and use
154 * only the final one for the whitelist.
155 */
156 list( $partname, $ext ) = $this->splitExtensions( $basename );
157 if( count( $ext ) ) {
158 $finalExt = $ext[count( $ext ) - 1];
159 } else {
160 $finalExt = '';
161 }
162 $fullExt = implode( '.', $ext );
163
164 if ( strlen( $partname ) < 3 ) {
165 $this->mainUploadForm( wfMsg( 'minlength' ) );
166 return;
167 }
168
169 /**
170 * Filter out illegal characters, and try to make a legible name
171 * out of it. We'll strip some silently that Title would die on.
172 */
173 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
174 $nt = Title::newFromText( $filtered );
175 if( is_null( $nt ) ) {
176 return $this->uploadError( wfMsg( 'illegalfilename', htmlspecialchars( $filtered ) ) );
177 }
178 $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() );
179 $this->mUploadSaveName = $nt->getDBkey();
180
181 /**
182 * If the image is protected, non-sysop users won't be able
183 * to modify it by uploading a new revision.
184 */
185 if( !$nt->userCanEdit() ) {
186 return $this->uploadError( wfMsg( 'protectedpage' ) );
187 }
188
189 /* Don't allow users to override the blacklist (check file extension) */
190 global $wgStrictFileExtensions;
191 global $wgFileExtensions, $wgFileBlacklist;
192 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
193 ($wgStrictFileExtensions &&
194 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
195 return $this->uploadError( wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ) );
196 }
197
198 /**
199 * Look at the contents of the file; if we can recognize the
200 * type but it's corrupt or data of the wrong type, we should
201 * probably not accept it.
202 */
203 if( !$this->mStashed ) {
204 $veri= $this->verify($this->mUploadTempName, $finalExt);
205
206 if( $veri !== true ) { //it's a wiki error...
207 return $this->uploadError( $veri->toString() );
208 }
209 }
210
211 /**
212 * Check for non-fatal conditions
213 */
214 if ( ! $this->mIgnoreWarning ) {
215 $warning = '';
216 if( $this->mUploadSaveName != ucfirst( $filtered ) ) {
217 $warning .= '<li>'.wfMsg( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
218 }
219
220 global $wgCheckFileExtensions;
221 if ( $wgCheckFileExtensions ) {
222 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
223 $warning .= '<li>'.wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
224 }
225 }
226
227 global $wgUploadSizeWarning;
228 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
229 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
230 # value, perhaps add GB,MB and KB suffixes?
231 $warning .= '<li>'.wfMsg( 'largefile', $wgUploadSizeWarning, $this->mUploadSize ).'</li>';
232 }
233 if ( $this->mUploadSize == 0 ) {
234 $warning .= '<li>'.wfMsg( 'emptyfile' ).'</li>';
235 }
236
237 if( $nt->getArticleID() ) {
238 global $wgUser;
239 $sk = $wgUser->getSkin();
240 $dlink = $sk->makeKnownLinkObj( $nt );
241 $warning .= '<li>'.wfMsg( 'fileexists', $dlink ).'</li>';
242 }
243
244 if( $warning != '' ) {
245 /**
246 * Stash the file in a temporary location; the user can choose
247 * to let it through and we'll complete the upload then.
248 */
249 return $this->uploadWarning($warning);
250 }
251 }
252
253 /**
254 * Try actually saving the thing...
255 * It will show an error form on failure.
256 */
257 if( $this->saveUploadedFile( $this->mUploadSaveName,
258 $this->mUploadTempName,
259 !empty( $this->mSessionKey ) ) ) {
260 /**
261 * Update the upload log and create the description page
262 * if it's a new file.
263 */
264 $img = Image::newFromName( $this->mUploadSaveName );
265 $success = $img->recordUpload( $this->mUploadOldVersion,
266 $this->mUploadDescription,
267 $this->mUploadCopyStatus,
268 $this->mUploadSource );
269
270 if ( $success ) {
271 $this->showSuccess();
272 } else {
273 // Image::recordUpload() fails if the image went missing, which is
274 // unlikely, hence the lack of a specialised message
275 $wgOut->fileNotFoundError( $this->mUploadSaveName );
276 }
277 }
278 }
279
280 /**
281 * Move the uploaded file from its temporary location to the final
282 * destination. If a previous version of the file exists, move
283 * it into the archive subdirectory.
284 *
285 * @todo If the later save fails, we may have disappeared the original file.
286 *
287 * @param string $saveName
288 * @param string $tempName full path to the temporary file
289 * @param bool $useRename if true, doesn't check that the source file
290 * is a PHP-managed upload temporary
291 */
292 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
293 global $wgUploadDirectory, $wgOut;
294
295 $fname= "SpecialUpload::saveUploadedFile";
296
297 $dest = wfImageDir( $saveName );
298 $archive = wfImageArchiveDir( $saveName );
299 $this->mSavedFile = "{$dest}/{$saveName}";
300
301 if( is_file( $this->mSavedFile ) ) {
302 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
303 wfSuppressWarnings();
304 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
305 wfRestoreWarnings();
306
307 if( ! $success ) {
308 $wgOut->fileRenameError( $this->mSavedFile,
309 "${archive}/{$this->mUploadOldVersion}" );
310 return false;
311 }
312 else wfDebug("$fname: moved file ".$this->mSavedFile." to ${archive}/{$this->mUploadOldVersion}\n");
313 }
314 else {
315 $this->mUploadOldVersion = '';
316 }
317
318 if( $useRename ) {
319 wfSuppressWarnings();
320 $success = rename( $tempName, $this->mSavedFile );
321 wfRestoreWarnings();
322
323 if( ! $success ) {
324 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
325 return false;
326 } else {
327 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
328 }
329 } else {
330 wfSuppressWarnings();
331 $success = move_uploaded_file( $tempName, $this->mSavedFile );
332 wfRestoreWarnings();
333
334 if( ! $success ) {
335 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
336 return false;
337 }
338 else wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
339 }
340
341 chmod( $this->mSavedFile, 0644 );
342 return true;
343 }
344
345 /**
346 * Stash a file in a temporary directory for later processing
347 * after the user has confirmed it.
348 *
349 * If the user doesn't explicitly cancel or accept, these files
350 * can accumulate in the temp directory.
351 *
352 * @param string $saveName - the destination filename
353 * @param string $tempName - the source temporary file to save
354 * @return string - full path the stashed file, or false on failure
355 * @access private
356 */
357 function saveTempUploadedFile( $saveName, $tempName ) {
358 global $wgOut;
359 $archive = wfImageArchiveDir( $saveName, 'temp' );
360 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
361
362 if ( !move_uploaded_file( $tempName, $stash ) ) {
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 opf 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 }
889 ?>