de2199acf2a1a48f438fae8c17f14f12411fc4e6
[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;
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 if( !$request->wasPosted() ) {
44 # GET requests just give the main form; no data.
45 return;
46 }
47
48 $this->mUploadAffirm = $request->getCheck( 'wpUploadAffirm' );
49 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning');
50 $this->mReUpload = $request->getCheck( 'wpReUpload' );
51 $this->mUpload = $request->getCheck( 'wpUpload' );
52
53 $this->mUploadDescription = $request->getText( 'wpUploadDescription' );
54 $this->mUploadCopyStatus = $request->getText( 'wpUploadCopyStatus' );
55 $this->mUploadSource = $request->getText( 'wpUploadSource');
56
57 $this->mAction = $request->getVal( 'action' );
58
59 $this->mSessionKey = $request->getInt( 'wpSessionKey' );
60 if( !empty( $this->mSessionKey ) &&
61 isset( $_SESSION['wsUploadData'][$this->mSessionKey] ) ) {
62 /**
63 * Confirming a temporarily stashed upload.
64 * We don't want path names to be forged, so we keep
65 * them in the session on the server and just give
66 * an opaque key to the user agent.
67 */
68 $data = $_SESSION['wsUploadData'][$this->mSessionKey];
69 $this->mUploadTempName = $data['mUploadTempName'];
70 $this->mUploadSize = $data['mUploadSize'];
71 $this->mOname = $data['mOname'];
72 $this->mStashed = true;
73 } else {
74 /**
75 *Check for a newly uploaded file.
76 */
77 $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
78 $this->mUploadSize = $request->getFileSize( 'wpUploadFile' );
79 $this->mOname = $request->getFileName( 'wpUploadFile' );
80 $this->mSessionKey = false;
81 $this->mStashed = false;
82 }
83 }
84
85 /**
86 * Start doing stuff
87 * @access public
88 */
89 function execute() {
90 global $wgUser, $wgOut;
91 global $wgEnableUploads;
92
93 /** Show an error message if file upload is disabled */
94 if( ! $wgEnableUploads ) {
95 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
96 return;
97 }
98
99 /** Various rights checks */
100 if( ( $wgUser->isAnon() )
101 OR $wgUser->isBlocked() ) {
102 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
103 return;
104 }
105 if( wfReadOnly() ) {
106 $wgOut->readOnlyPage();
107 return;
108 }
109
110 if( $this->mReUpload ) {
111 $this->unsaveUploadedFile();
112 $this->mainUploadForm();
113 } else if ( 'submit' == $this->mAction || $this->mUpload ) {
114 $this->processUpload();
115 } else {
116 $this->mainUploadForm();
117 }
118 }
119
120 /* -------------------------------------------------------------- */
121
122 /**
123 * Really do the upload
124 * Checks are made in SpecialUpload::execute()
125 * @access private
126 */
127 function processUpload() {
128 global $wgUser, $wgOut, $wgLang, $wgContLang;
129 global $wgUploadDirectory;
130 global $wgUseCopyrightUpload, $wgCheckCopyrightUpload;
131
132 /**
133 * If there was no filename or a zero size given, give up quick.
134 */
135 if( ( trim( $this->mOname ) == '' ) || empty( $this->mUploadSize ) ) {
136 return $this->mainUploadForm('<li>'.wfMsg( 'emptyfile' ).'</li>');
137 }
138
139 /**
140 * When using detailed copyright, if user filled field, assume he
141 * confirmed the upload
142 */
143 if ( $wgUseCopyrightUpload ) {
144 $this->mUploadAffirm = true;
145 if( $wgCheckCopyrightUpload &&
146 ( trim( $this->mUploadCopyStatus ) == '' ||
147 trim( $this->mUploadSource ) == '' ) ) {
148 $this->mUploadAffirm = false;
149 }
150 }
151
152 /** User need to confirm his upload */
153 if( !$this->mUploadAffirm ) {
154 $this->mainUploadForm( wfMsg( 'noaffirmation' ) );
155 return;
156 }
157
158 # Chop off any directories in the given filename
159 $basename = basename( $this->mOname );
160
161 /**
162 * We'll want to blacklist against *any* 'extension', and use
163 * only the final one for the whitelist.
164 */
165 list( $partname, $ext ) = $this->splitExtensions( $basename );
166 if( count( $ext ) ) {
167 $finalExt = $ext[count( $ext ) - 1];
168 } else {
169 $finalExt = '';
170 }
171 $fullExt = implode( '.', $ext );
172
173 if ( strlen( $partname ) < 3 ) {
174 $this->mainUploadForm( wfMsg( 'minlength' ) );
175 return;
176 }
177
178 /**
179 * Filter out illegal characters, and try to make a legible name
180 * out of it. We'll strip some silently that Title would die on.
181 */
182 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
183 $nt = Title::newFromText( $filtered );
184 if( is_null( $nt ) ) {
185 return $this->uploadError( wfMsg( 'illegalfilename', htmlspecialchars( $filtered ) ) );
186 }
187 $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() );
188 $this->mUploadSaveName = $nt->getDBkey();
189
190 /**
191 * If the image is protected, non-sysop users won't be able
192 * to modify it by uploading a new revision.
193 */
194 if( !$nt->userCanEdit() ) {
195 return $this->uploadError( wfMsg( 'protectedpage' ) );
196 }
197
198 /* Don't allow users to override the blacklist */
199 global $wgStrictFileExtensions;
200 global $wgFileExtensions, $wgFileBlacklist;
201 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
202 ($wgStrictFileExtensions &&
203 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
204 return $this->uploadError( wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ) );
205 }
206
207 /**
208 * Look at the contents of the file; if we can recognize the
209 * type but it's corrupt or data of the wrong type, we should
210 * probably not accept it.
211 */
212 if( !$this->mStashed && !$this->verify( $this->mUploadTempName, $finalExt ) ) {
213 return $this->uploadError( wfMsg( 'uploadcorrupt' ) );
214 }
215
216 /**
217 * Check for non-fatal conditions
218 */
219 if ( ! $this->mIgnoreWarning ) {
220 $warning = '';
221 if( $this->mUploadSaveName != ucfirst( $filtered ) ) {
222 $warning .= '<li>'.wfMsg( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
223 }
224
225 global $wgCheckFileExtensions;
226 if ( $wgCheckFileExtensions ) {
227 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
228 $warning .= '<li>'.wfMsg( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
229 }
230 }
231
232 global $wgUploadSizeWarning;
233 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
234 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
235 # value, perhaps add GB,MB and KB suffixes?
236 $warning .= '<li>'.wfMsg( 'largefile', $wgUploadSizeWarning, $this->mUploadSize ).'</li>';
237 }
238 if ( $this->mUploadSize == 0 ) {
239 $warning .= '<li>'.wfMsg( 'emptyfile' ).'</li>';
240 }
241
242 if( $nt->getArticleID() ) {
243 global $wgUser;
244 $sk = $wgUser->getSkin();
245 $dlink = $sk->makeKnownLinkObj( $nt );
246 $warning .= '<li>'.wfMsg( 'fileexists', $dlink ).'</li>';
247 }
248
249 if( $warning != '' ) {
250 /**
251 * Stash the file in a temporary location; the user can choose
252 * to let it through and we'll complete the upload then.
253 */
254 return $this->uploadWarning($warning);
255 }
256 }
257
258 /**
259 * Try actually saving the thing...
260 * It will show an error form on failure.
261 */
262 if( $this->saveUploadedFile( $this->mUploadSaveName,
263 $this->mUploadTempName,
264 !empty( $this->mSessionKey ) ) ) {
265 /**
266 * Update the upload log and create the description page
267 * if it's a new file.
268 */
269 $img = Image::newFromName( $this->mUploadSaveName );
270 $success = $img->recordUpload( $this->mUploadOldVersion,
271 $this->mUploadDescription,
272 $this->mUploadCopyStatus,
273 $this->mUploadSource );
274
275 if ( $success ) {
276 $this->showSuccess();
277 } else {
278 // Image::recordUpload() fails if the image went missing, which is
279 // unlikely, hence the lack of a specialised message
280 $wgOut->fileNotFoundError( $this->mUploadSaveName );
281 }
282 }
283 }
284
285 /**
286 * Move the uploaded file from its temporary location to the final
287 * destination. If a previous version of the file exists, move
288 * it into the archive subdirectory.
289 *
290 * @todo If the later save fails, we may have disappeared the original file.
291 *
292 * @param string $saveName
293 * @param string $tempName full path to the temporary file
294 * @param bool $useRename if true, doesn't check that the source file
295 * is a PHP-managed upload temporary
296 */
297 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
298 global $wgUploadDirectory, $wgOut;
299
300 $dest = wfImageDir( $saveName );
301 $archive = wfImageArchiveDir( $saveName );
302 $this->mSavedFile = "{$dest}/{$saveName}";
303
304 if( is_file( $this->mSavedFile ) ) {
305 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
306 wfSuppressWarnings();
307 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
308 wfRestoreWarnings();
309
310 if( ! $success ) {
311 $wgOut->fileRenameError( $this->mSavedFile,
312 "${archive}/{$this->mUploadOldVersion}" );
313 return false;
314 }
315 } else {
316 $this->mUploadOldVersion = '';
317 }
318
319 if( $useRename ) {
320 wfSuppressWarnings();
321 $success = rename( $tempName, $this->mSavedFile );
322 wfRestoreWarnings();
323
324 if( ! $success ) {
325 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
326 return false;
327 }
328 } else {
329 wfSuppressWarnings();
330 $success = move_uploaded_file( $tempName, $this->mSavedFile );
331 wfRestoreWarnings();
332
333 if( ! $success ) {
334 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
335 return false;
336 }
337 }
338 chmod( $this->mSavedFile, 0644 );
339 return true;
340 }
341
342 /**
343 * Stash a file in a temporary directory for later processing
344 * after the user has confirmed it.
345 *
346 * If the user doesn't explicitly cancel or accept, these files
347 * can accumulate in the temp directory.
348 *
349 * @param string $saveName - the destination filename
350 * @param string $tempName - the source temporary file to save
351 * @return string - full path the stashed file, or false on failure
352 * @access private
353 */
354 function saveTempUploadedFile( $saveName, $tempName ) {
355 global $wgOut;
356 $archive = wfImageArchiveDir( $saveName, 'temp' );
357 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
358
359 if ( !move_uploaded_file( $tempName, $stash ) ) {
360 $wgOut->fileCopyError( $tempName, $stash );
361 return false;
362 }
363
364 return $stash;
365 }
366
367 /**
368 * Stash a file in a temporary directory for later processing,
369 * and save the necessary descriptive info into the session.
370 * Returns a key value which will be passed through a form
371 * to pick up the path info on a later invocation.
372 *
373 * @return int
374 * @access private
375 */
376 function stashSession() {
377 $stash = $this->saveTempUploadedFile(
378 $this->mUploadSaveName, $this->mUploadTempName );
379
380 if( !$stash ) {
381 # Couldn't save the file.
382 return false;
383 }
384
385 $key = mt_rand( 0, 0x7fffffff );
386 $_SESSION['wsUploadData'][$key] = array(
387 'mUploadTempName' => $stash,
388 'mUploadSize' => $this->mUploadSize,
389 'mOname' => $this->mOname );
390 return $key;
391 }
392
393 /**
394 * Remove a temporarily kept file stashed by saveTempUploadedFile().
395 * @access private
396 */
397 function unsaveUploadedFile() {
398 wfSuppressWarnings();
399 $success = unlink( $this->mUploadTempName );
400 wfRestoreWarnings();
401 if ( ! $success ) {
402 $wgOut->fileDeleteError( $this->mUploadTempName );
403 }
404 }
405
406 /* -------------------------------------------------------------- */
407
408 /**
409 * Show some text and linkage on successful upload.
410 * @access private
411 */
412 function showSuccess() {
413 global $wgUser, $wgOut, $wgContLang;
414
415 $sk = $wgUser->getSkin();
416 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
417 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
418 $dlink = $sk->makeKnownLink( $dname, $dname );
419
420 $wgOut->addHTML( '<h2>' . wfMsg( 'successfulupload' ) . "</h2>\n" );
421 $text = wfMsg( 'fileuploaded', $ilink, $dlink );
422 $wgOut->addHTML( '<p>'.$text."\n" );
423 $wgOut->returnToMain( false );
424 }
425
426 /**
427 * @param string $error as HTML
428 * @access private
429 */
430 function uploadError( $error ) {
431 global $wgOut;
432 $sub = wfMsg( 'uploadwarning' );
433 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
434 $wgOut->addHTML( "<h4 class='error'>{$error}</h4>\n" );
435 }
436
437 /**
438 * There's something wrong with this file, not enough to reject it
439 * totally but we require manual intervention to save it for real.
440 * Stash it away, then present a form asking to confirm or cancel.
441 *
442 * @param string $warning as HTML
443 * @access private
444 */
445 function uploadWarning( $warning ) {
446 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
447 global $wgUseCopyrightUpload;
448
449 $this->mSessionKey = $this->stashSession();
450 if( !$this->mSessionKey ) {
451 # Couldn't save file; an error has been displayed so let's go.
452 return;
453 }
454
455 $sub = wfMsg( 'uploadwarning' );
456 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
457 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
458
459 $save = wfMsg( 'savefile' );
460 $reupload = wfMsg( 'reupload' );
461 $iw = wfMsg( 'ignorewarning' );
462 $reup = wfMsg( 'reuploaddesc' );
463 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
464 $action = $titleObj->escapeLocalURL( 'action=submit' );
465
466 if ( $wgUseCopyrightUpload )
467 {
468 $copyright = "
469 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
470 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
471 ";
472 } else {
473 $copyright = "";
474 }
475
476 $wgOut->addHTML( "
477 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
478 <input type='hidden' name='wpUploadAffirm' value='1' />
479 <input type='hidden' name='wpIgnoreWarning' value='1' />
480 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
481 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
482 {$copyright}
483 <table border='0'>
484 <tr>
485 <tr>
486 <td align='right'>
487 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
488 </td>
489 <td align='left'>$iw</td>
490 </tr>
491 <tr>
492 <td align='right'>
493 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
494 </td>
495 <td align='left'>$reup</td>
496 </tr>
497 </tr>
498 </table></form>\n" );
499 }
500
501 /**
502 * Displays the main upload form, optionally with a highlighted
503 * error message up at the top.
504 *
505 * @param string $msg as HTML
506 * @access private
507 */
508 function mainUploadForm( $msg='' ) {
509 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
510 global $wgUseCopyrightUpload;
511
512 $cols = intval($wgUser->getOption( 'cols' ));
513 $ew = $wgUser->getOption( 'editwidth' );
514 if ( $ew ) $ew = " style=\"width:100%\"";
515 else $ew = '';
516
517 if ( '' != $msg ) {
518 $sub = wfMsg( 'uploaderror' );
519 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
520 "<h4 class='error'>{$msg}</h4>\n" );
521 } else {
522 $sub = wfMsg( 'uploadfile' );
523 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
524 }
525 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
526 $sk = $wgUser->getSkin();
527
528 $fn = wfMsg( 'filename' );
529 $fd = wfMsg( 'filedesc' );
530 $ulb = wfMsg( 'uploadbtn' );
531
532 $clink = $sk->makeKnownLink( wfMsgForContent( 'copyrightpage' ),
533 wfMsg( 'copyrightpagename' ) );
534 $ca = wfMsg( 'affirmation', $clink );
535 $iw = wfMsg( 'ignorewarning' );
536
537 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
538 $action = $titleObj->escapeLocalURL();
539
540 $source = "
541 <td align='right'>
542 <input tabindex='3' type='checkbox' name='wpUploadAffirm' value='1' id='wpUploadAffirm' />
543 </td><td align='left'><label for='wpUploadAffirm'>{$ca}</label></td>
544 " ;
545 if ( $wgUseCopyrightUpload )
546 {
547 $source = "
548 <td align='right' nowrap='nowrap'>" . wfMsg ( 'filestatus' ) . ":</td>
549 <td><input tabindex='3' type='text' name=\"wpUploadCopyStatus\" value=\"" .
550 htmlspecialchars($this->mUploadCopyStatus). "\" size='40' /></td>
551 </tr><tr>
552 <td align='right'>". wfMsg ( 'filesource' ) . ":</td>
553 <td><input tabindex='4' type='text' name='wpUploadSource' value=\"" .
554 htmlspecialchars($this->mUploadSource). "\" size='40' /></td>
555 " ;
556 }
557
558 $wgOut->addHTML( "
559 <form id='upload' method='post' enctype='multipart/form-data' action='$action'>
560 <table border='0'><tr>
561 <td align='right'>{$fn}:</td><td align='left'>
562 <input tabindex='1' type='file' name='wpUploadFile' size='40' />
563 </td></tr><tr>
564 <td align='right'>{$fd}:</td><td align='left'>
565 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
566 . htmlspecialchars( $this->mUploadDescription ) .
567 "</textarea>
568 </td></tr><tr>
569 {$source}
570 </tr>
571 <tr><td></td><td align='left'>
572 <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
573 </td></tr></table></form>\n" );
574 }
575
576 /* -------------------------------------------------------------- */
577
578 /**
579 * Split a file into a base name and all dot-delimited 'extensions'
580 * on the end. Some web server configurations will fall back to
581 * earlier pseudo-'extensions' to determine type and execute
582 * scripts, so the blacklist needs to check them all.
583 *
584 * @return array
585 */
586 function splitExtensions( $filename ) {
587 $bits = explode( '.', $filename );
588 $basename = array_shift( $bits );
589 return array( $basename, $bits );
590 }
591
592 /**
593 * Perform case-insensitive match against a list of file extensions.
594 * Returns true if the extension is in the list.
595 *
596 * @param string $ext
597 * @param array $list
598 * @return bool
599 */
600 function checkFileExtension( $ext, $list ) {
601 return in_array( strtolower( $ext ), $list );
602 }
603
604 /**
605 * Perform case-insensitive match against a list of file extensions.
606 * Returns true if any of the extensions are in the list.
607 *
608 * @param array $ext
609 * @param array $list
610 * @return bool
611 */
612 function checkFileExtensionList( $ext, $list ) {
613 foreach( $ext as $e ) {
614 if( in_array( strtolower( $e ), $list ) ) {
615 return true;
616 }
617 }
618 return false;
619 }
620
621 /**
622 * Returns false if the file is of a known type but can't be recognized,
623 * indicating a corrupt file.
624 * Returns true otherwise; unknown file types are not checked if given
625 * with an unrecognized extension.
626 *
627 * @param string $tmpfile Pathname to the temporary upload file
628 * @param string $extension The filename extension that the file is to be served with
629 * @return bool
630 */
631 function verify( $tmpfile, $extension ) {
632 if( $this->triggersIEbug( $tmpfile ) ||
633 $this->triggersSafariBug( $tmpfile ) ) {
634 return false;
635 }
636
637 $fname = 'SpecialUpload::verify';
638 $mergeExtensions = array(
639 'jpg' => 'jpeg',
640 'tif' => 'tiff' );
641 $extensionTypes = array(
642 # See http://www.php.net/getimagesize
643 1 => 'gif',
644 2 => 'jpeg',
645 3 => 'png',
646 4 => 'swf',
647 5 => 'psd',
648 6 => 'bmp',
649 7 => 'tiff',
650 8 => 'tiff',
651 9 => 'jpc',
652 10 => 'jp2',
653 11 => 'jpx',
654 12 => 'jb2',
655 13 => 'swc',
656 14 => 'iff',
657 15 => 'wbmp',
658 16 => 'xbm' );
659
660 $extension = strtolower( $extension );
661 if( isset( $mergeExtensions[$extension] ) ) {
662 $extension = $mergeExtensions[$extension];
663 }
664 wfDebug( "$fname: Testing file '$tmpfile' with given extension '$extension'\n" );
665
666 if( !in_array( $extension, $extensionTypes ) ) {
667 # Not a recognized image type. We don't know how to verify these.
668 # They're allowed by policy or they wouldn't get this far, so we'll
669 # let them slide for now.
670 wfDebug( "$fname: Unknown extension; passing.\n" );
671 return true;
672 }
673
674 wfSuppressWarnings();
675 $data = getimagesize( $tmpfile );
676 wfRestoreWarnings();
677 if( false === $data ) {
678 # Didn't recognize the image type.
679 # Either the image is corrupt or someone's slipping us some
680 # bogus data such as HTML+JavaScript trying to take advantage
681 # of an Internet Explorer security flaw.
682 wfDebug( "$fname: getimagesize() doesn't recognize the file; rejecting.\n" );
683 return false;
684 }
685
686 $imageType = $data[2];
687 if( !isset( $extensionTypes[$imageType] ) ) {
688 # Now we're kind of confused. Perhaps new image types added
689 # to PHP's support that we don't know about.
690 # We'll let these slide for now.
691 wfDebug( "$fname: getimagesize() knows the file, but we don't recognize the type; passing.\n" );
692 return true;
693 }
694
695 $ext = strtolower( $extension );
696 if( $extension != $extensionTypes[$imageType] ) {
697 # The given filename extension doesn't match the
698 # file type. Probably just a mistake, but it's a stupid
699 # one and we shouldn't let it pass. KILL THEM!
700 wfDebug( "$fname: file extension does not match recognized type; rejecting.\n" );
701 return false;
702 }
703
704 wfDebug( "$fname: all clear; passing.\n" );
705 return true;
706 }
707
708 /**
709 * Internet Explorer for Windows performs some really stupid file type
710 * autodetection which can cause it to interpret valid image files as HTML
711 * and potentially execute JavaScript, creating a cross-site scripting
712 * attack vectors.
713 *
714 * Returns true if IE is likely to mistake the given file for HTML.
715 *
716 * @param string $filename
717 * @return bool
718 */
719 function triggersIEbug( $filename ) {
720 $file = fopen( $filename, 'rb' );
721 $chunk = strtolower( fread( $file, 256 ) );
722 fclose( $file );
723
724 $tags = array(
725 '<body',
726 '<head',
727 '<html',
728 '<img',
729 '<pre',
730 '<script',
731 '<table',
732 '<title' );
733 foreach( $tags as $tag ) {
734 if( false !== strpos( $chunk, $tag ) ) {
735 return true;
736 }
737 }
738 return false;
739 }
740
741 /**
742 * Apple's Safari browser performs some unsafe file type autodetection
743 * which can cause legitimate files to be interpreted as HTML if the
744 * web server is not correctly configured to send the right content-type
745 * (or if you're really uploading plain text and octet streams!)
746 *
747 * Returns true if Safari would mistake the given file for HTML
748 * when served with a generic content-type.
749 *
750 * @param string $filename
751 * @return bool
752 */
753 function triggersSafariBug( $filename ) {
754 $file = fopen( $filename, 'rb' );
755 $chunk = strtolower( fread( $file, 1024 ) );
756 fclose( $file );
757
758 $tags = array(
759 '<html',
760 '<script',
761 '<title' );
762 foreach( $tags as $tag ) {
763 if( false !== strpos( $chunk, $tag ) ) {
764 return true;
765 }
766 }
767 return false;
768 }
769
770 }
771 ?>