* Removed redudant global decleration
[lhc/web/wiklou.git] / includes / SpecialUpload.php
1 <?php
2 /**
3 *
4 * @package MediaWiki
5 * @subpackage SpecialPage
6 */
7
8 /**
9 *
10 */
11 require_once( 'Image.php' );
12 require_once( 'MacBinary.php' );
13
14 /**
15 * Entry point
16 */
17 function wfSpecialUpload() {
18 global $wgRequest;
19 $form = new UploadForm( $wgRequest );
20 $form->execute();
21 }
22
23 /**
24 *
25 * @package MediaWiki
26 * @subpackage SpecialPage
27 */
28 class UploadForm {
29 /**#@+
30 * @access private
31 */
32 var $mUploadFile, $mUploadDescription, $mIgnoreWarning;
33 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
34 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
35 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile;
36 /**#@-*/
37
38 /**
39 * Constructor : initialise object
40 * Get data POSTed through the form and assign them to the object
41 * @param $request Data posted.
42 */
43 function UploadForm( &$request ) {
44 $this->mDestFile = $request->getText( 'wpDestFile' );
45
46 if( !$request->wasPosted() ) {
47 # GET requests just give the main form; no data except wpDestfile.
48 return;
49 }
50
51 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning');
52 $this->mReUpload = $request->getCheck( 'wpReUpload' );
53 $this->mUpload = $request->getCheck( 'wpUpload' );
54
55 $this->mUploadDescription = $request->getText( 'wpUploadDescription' );
56 $this->mUploadCopyStatus = $request->getText( 'wpUploadCopyStatus' );
57 $this->mUploadSource = $request->getText( 'wpUploadSource');
58
59 $this->mAction = $request->getVal( 'action' );
60
61 $this->mSessionKey = $request->getInt( 'wpSessionKey' );
62 if( !empty( $this->mSessionKey ) &&
63 isset( $_SESSION['wsUploadData'][$this->mSessionKey] ) ) {
64 /**
65 * Confirming a temporarily stashed upload.
66 * We don't want path names to be forged, so we keep
67 * them in the session on the server and just give
68 * an opaque key to the user agent.
69 */
70 $data = $_SESSION['wsUploadData'][$this->mSessionKey];
71 $this->mUploadTempName = $data['mUploadTempName'];
72 $this->mUploadSize = $data['mUploadSize'];
73 $this->mOname = $data['mOname'];
74 $this->mStashed = true;
75 $this->mRemoveTempFile = false;
76 } else {
77 /**
78 *Check for a newly uploaded file.
79 */
80 $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
81 $this->mUploadSize = $request->getFileSize( 'wpUploadFile' );
82 $this->mOname = $request->getFileName( 'wpUploadFile' );
83 $this->mSessionKey = false;
84 $this->mStashed = false;
85 $this->mRemoveTempFile = false; // PHP will handle this
86 }
87 }
88
89 /**
90 * Start doing stuff
91 * @access public
92 */
93 function execute() {
94 global $wgUser, $wgOut;
95 global $wgEnableUploads, $wgUploadDirectory;
96
97 /** Show an error message if file upload is disabled */
98 if( ! $wgEnableUploads ) {
99 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
100 return;
101 }
102
103 /** Various rights checks */
104 if( !$wgUser->isAllowed( 'upload' ) || $wgUser->isBlocked() ) {
105 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
106 return;
107 }
108 if( wfReadOnly() ) {
109 $wgOut->readOnlyPage();
110 return;
111 }
112
113 /** Check if the image directory is writeable, this is a common mistake */
114 if ( !is_writeable( $wgUploadDirectory ) ) {
115 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
116 return;
117 }
118
119 if( $this->mReUpload ) {
120 $this->unsaveUploadedFile();
121 $this->mainUploadForm();
122 } else if ( 'submit' == $this->mAction || $this->mUpload ) {
123 $this->processUpload();
124 } else {
125 $this->mainUploadForm();
126 }
127
128 $this->cleanupTempFile();
129 }
130
131 /* -------------------------------------------------------------- */
132
133 /**
134 * Really do the upload
135 * Checks are made in SpecialUpload::execute()
136 * @access private
137 */
138 function processUpload() {
139 global $wgUser, $wgOut, $wgLang, $wgContLang;
140 global $wgUploadDirectory;
141 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
142
143 /**
144 * If there was no filename or a zero size given, give up quick.
145 */
146 if( trim( $this->mOname ) == '' || empty( $this->mUploadSize ) ) {
147 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
148 return;
149 }
150
151 # Chop off any directories in the given filename
152 if ( $this->mDestFile ) {
153 $basename = basename( $this->mDestFile );
154 } else {
155 $basename = basename( $this->mOname );
156 }
157
158 /**
159 * We'll want to blacklist against *any* 'extension', and use
160 * only the final one for the whitelist.
161 */
162 list( $partname, $ext ) = $this->splitExtensions( $basename );
163 if( count( $ext ) ) {
164 $finalExt = $ext[count( $ext ) - 1];
165 } else {
166 $finalExt = '';
167 }
168 $fullExt = implode( '.', $ext );
169
170 if ( strlen( $partname ) < 3 ) {
171 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
172 return;
173 }
174
175 /**
176 * Filter out illegal characters, and try to make a legible name
177 * out of it. We'll strip some silently that Title would die on.
178 */
179 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
180 $nt = Title::newFromText( $filtered );
181 if( is_null( $nt ) ) {
182 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
183 return;
184 }
185 $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() );
186 $this->mUploadSaveName = $nt->getDBkey();
187
188 /**
189 * If the image is protected, non-sysop users won't be able
190 * to modify it by uploading a new revision.
191 */
192 if( !$nt->userCanEdit() ) {
193 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
194 }
195
196 /* Don't allow users to override the blacklist (check file extension) */
197 global $wgStrictFileExtensions;
198 global $wgFileExtensions, $wgFileBlacklist;
199 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
200 ($wgStrictFileExtensions &&
201 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
202 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
203 }
204
205 /**
206 * Look at the contents of the file; if we can recognize the
207 * type but it's corrupt or data of the wrong type, we should
208 * probably not accept it.
209 */
210 if( !$this->mStashed ) {
211 $this->checkMacBinary();
212 $veri = $this->verify( $this->mUploadTempName, $finalExt );
213
214 if( $veri !== true ) { //it's a wiki error...
215 return $this->uploadError( $veri->toString() );
216 }
217 }
218
219 /**
220 * Check for non-fatal conditions
221 */
222 if ( ! $this->mIgnoreWarning ) {
223 $warning = '';
224 if( $this->mUploadSaveName != ucfirst( $filtered ) ) {
225 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
226 }
227
228 global $wgCheckFileExtensions;
229 if ( $wgCheckFileExtensions ) {
230 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
231 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
232 }
233 }
234
235 global $wgUploadSizeWarning;
236 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
237 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
238 # value, perhaps add GB,MB and KB suffixes?
239 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize ).'</li>';
240 }
241 if ( $this->mUploadSize == 0 ) {
242 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
243 }
244
245 if( $nt->getArticleID() ) {
246 global $wgUser;
247 $sk = $wgUser->getSkin();
248 $dlink = $sk->makeKnownLinkObj( $nt );
249 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
250 }
251
252 if( $warning != '' ) {
253 /**
254 * Stash the file in a temporary location; the user can choose
255 * to let it through and we'll complete the upload then.
256 */
257 return $this->uploadWarning( $warning );
258 }
259 }
260
261 /**
262 * Try actually saving the thing...
263 * It will show an error form on failure.
264 */
265 $hasBeenMunged = !empty( $this->mSessionKey ) || $this->mRemoveTempFile;
266 if( $this->saveUploadedFile( $this->mUploadSaveName,
267 $this->mUploadTempName,
268 $hasBeenMunged ) ) {
269 /**
270 * Update the upload log and create the description page
271 * if it's a new file.
272 */
273 $img = Image::newFromName( $this->mUploadSaveName );
274 $success = $img->recordUpload( $this->mUploadOldVersion,
275 $this->mUploadDescription,
276 $this->mUploadCopyStatus,
277 $this->mUploadSource );
278
279 if ( $success ) {
280 $this->showSuccess();
281 } else {
282 // Image::recordUpload() fails if the image went missing, which is
283 // unlikely, hence the lack of a specialised message
284 $wgOut->fileNotFoundError( $this->mUploadSaveName );
285 }
286 }
287 }
288
289 /**
290 * Move the uploaded file from its temporary location to the final
291 * destination. If a previous version of the file exists, move
292 * it into the archive subdirectory.
293 *
294 * @todo If the later save fails, we may have disappeared the original file.
295 *
296 * @param string $saveName
297 * @param string $tempName full path to the temporary file
298 * @param bool $useRename if true, doesn't check that the source file
299 * is a PHP-managed upload temporary
300 */
301 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
302 global $wgUploadDirectory, $wgOut;
303
304 $fname= "SpecialUpload::saveUploadedFile";
305
306 $dest = wfImageDir( $saveName );
307 $archive = wfImageArchiveDir( $saveName );
308 $this->mSavedFile = "{$dest}/{$saveName}";
309
310 if( is_file( $this->mSavedFile ) ) {
311 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
312 wfSuppressWarnings();
313 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
314 wfRestoreWarnings();
315
316 if( ! $success ) {
317 $wgOut->fileRenameError( $this->mSavedFile,
318 "${archive}/{$this->mUploadOldVersion}" );
319 return false;
320 }
321 else wfDebug("$fname: moved file ".$this->mSavedFile." to ${archive}/{$this->mUploadOldVersion}\n");
322 }
323 else {
324 $this->mUploadOldVersion = '';
325 }
326
327 wfSuppressWarnings();
328 $success = $useRename
329 ? rename( $tempName, $this->mSavedFile )
330 : move_uploaded_file( $tempName, $this->mSavedFile );
331 wfRestoreWarnings();
332
333 if( ! $success ) {
334 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
335 return false;
336 } else {
337 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
338 }
339
340 chmod( $this->mSavedFile, 0644 );
341 return true;
342 }
343
344 /**
345 * Stash a file in a temporary directory for later processing
346 * after the user has confirmed it.
347 *
348 * If the user doesn't explicitly cancel or accept, these files
349 * can accumulate in the temp directory.
350 *
351 * @param string $saveName - the destination filename
352 * @param string $tempName - the source temporary file to save
353 * @return string - full path the stashed file, or false on failure
354 * @access private
355 */
356 function saveTempUploadedFile( $saveName, $tempName ) {
357 global $wgOut;
358 $archive = wfImageArchiveDir( $saveName, 'temp' );
359 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
360
361 $success = $this->mRemoveTempFile
362 ? rename( $tempName, $stash )
363 : move_uploaded_file( $tempName, $stash );
364 if ( !$success ) {
365 $wgOut->fileCopyError( $tempName, $stash );
366 return false;
367 }
368
369 return $stash;
370 }
371
372 /**
373 * Stash a file in a temporary directory for later processing,
374 * and save the necessary descriptive info into the session.
375 * Returns a key value which will be passed through a form
376 * to pick up the path info on a later invocation.
377 *
378 * @return int
379 * @access private
380 */
381 function stashSession() {
382 $stash = $this->saveTempUploadedFile(
383 $this->mUploadSaveName, $this->mUploadTempName );
384
385 if( !$stash ) {
386 # Couldn't save the file.
387 return false;
388 }
389
390 $key = mt_rand( 0, 0x7fffffff );
391 $_SESSION['wsUploadData'][$key] = array(
392 'mUploadTempName' => $stash,
393 'mUploadSize' => $this->mUploadSize,
394 'mOname' => $this->mOname );
395 return $key;
396 }
397
398 /**
399 * Remove a temporarily kept file stashed by saveTempUploadedFile().
400 * @access private
401 */
402 function unsaveUploadedFile() {
403 global $wgOut;
404 wfSuppressWarnings();
405 $success = unlink( $this->mUploadTempName );
406 wfRestoreWarnings();
407 if ( ! $success ) {
408 $wgOut->fileDeleteError( $this->mUploadTempName );
409 }
410 }
411
412 /* -------------------------------------------------------------- */
413
414 /**
415 * Show some text and linkage on successful upload.
416 * @access private
417 */
418 function showSuccess() {
419 global $wgUser, $wgOut, $wgContLang;
420
421 $sk = $wgUser->getSkin();
422 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
423 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
424 $dlink = $sk->makeKnownLink( $dname, $dname );
425
426 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
427 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
428 $wgOut->addHTML( $text );
429 $wgOut->returnToMain( false );
430 }
431
432 /**
433 * @param string $error as HTML
434 * @access private
435 */
436 function uploadError( $error ) {
437 global $wgOut;
438 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
439 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
440 }
441
442 /**
443 * There's something wrong with this file, not enough to reject it
444 * totally but we require manual intervention to save it for real.
445 * Stash it away, then present a form asking to confirm or cancel.
446 *
447 * @param string $warning as HTML
448 * @access private
449 */
450 function uploadWarning( $warning ) {
451 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
452 global $wgUseCopyrightUpload;
453
454 $this->mSessionKey = $this->stashSession();
455 if( !$this->mSessionKey ) {
456 # Couldn't save file; an error has been displayed so let's go.
457 return;
458 }
459
460 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
461 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
462
463 $save = wfMsgHtml( 'savefile' );
464 $reupload = wfMsgHtml( 'reupload' );
465 $iw = wfMsgWikiHtml( 'ignorewarning' );
466 $reup = wfMsgWikiHtml( 'reuploaddesc' );
467 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
468 $action = $titleObj->escapeLocalURL( 'action=submit' );
469
470 if ( $wgUseCopyrightUpload )
471 {
472 $copyright = "
473 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
474 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
475 ";
476 } else {
477 $copyright = "";
478 }
479
480 $wgOut->addHTML( "
481 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
482 <input type='hidden' name='wpIgnoreWarning' value='1' />
483 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
484 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
485 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile ) . "\" />
486 {$copyright}
487 <table border='0'>
488 <tr>
489 <tr>
490 <td align='right'>
491 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
492 </td>
493 <td align='left'>$iw</td>
494 </tr>
495 <tr>
496 <td align='right'>
497 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
498 </td>
499 <td align='left'>$reup</td>
500 </tr>
501 </tr>
502 </table></form>\n" );
503 }
504
505 /**
506 * Displays the main upload form, optionally with a highlighted
507 * error message up at the top.
508 *
509 * @param string $msg as HTML
510 * @access private
511 */
512 function mainUploadForm( $msg='' ) {
513 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
514 global $wgUseCopyrightUpload;
515
516 $cols = intval($wgUser->getOption( 'cols' ));
517 $ew = $wgUser->getOption( 'editwidth' );
518 if ( $ew ) $ew = " style=\"width:100%\"";
519 else $ew = '';
520
521 if ( '' != $msg ) {
522 $sub = wfMsgHtml( 'uploaderror' );
523 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
524 "<span class='error'>{$msg}</span>\n" );
525 }
526 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
527 $sk = $wgUser->getSkin();
528
529
530 $sourcefilename = wfMsgHtml( 'sourcefilename' );
531 $destfilename = wfMsgHtml( 'destfilename' );
532
533 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
534 $ulb = wfMsgHtml( 'uploadbtn' );
535
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'>{$summary}</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 of 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 * Check if the temporary file is MacBinary-encoded, as some uploads
889 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
890 * If so, the data fork will be extracted to a second temporary file,
891 * which will then be checked for validity and either kept or discarded.
892 *
893 * @access private
894 */
895 function checkMacBinary() {
896 $macbin = new MacBinary( $this->mUploadTempName );
897 if( $macbin->isValid() ) {
898 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
899 $dataHandle = fopen( $dataFile, 'wb' );
900
901 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
902 $macbin->extractData( $dataHandle );
903
904 $this->mUploadTempName = $dataFile;
905 $this->mUploadSize = $macbin->dataForkLength();
906
907 // We'll have to manually remove the new file if it's not kept.
908 $this->mRemoveTempFile = true;
909 }
910 $macbin->close();
911 }
912
913 /**
914 * If we've modified the upload file we need to manually remove it
915 * on exit to clean up.
916 * @access private
917 */
918 function cleanupTempFile() {
919 if( $this->mRemoveTempFile && file_exists( $this->mUploadTempName ) ) {
920 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
921 unlink( $this->mUploadTempName );
922 }
923 }
924
925 }
926 ?>