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