* Yummie ? : syntax.
[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 wfRecordUpload( $this->mUploadSaveName,
270 $this->mUploadOldVersion,
271 $this->mUploadSize,
272 $this->mUploadDescription,
273 $this->mUploadCopyStatus,
274 $this->mUploadSource );
275
276 /* refresh image metadata cache */
277 new Image( $this->mUploadSaveName, true );
278
279 $this->showSuccess();
280 }
281 }
282
283 /**
284 * Move the uploaded file from its temporary location to the final
285 * destination. If a previous version of the file exists, move
286 * it into the archive subdirectory.
287 *
288 * @todo If the later save fails, we may have disappeared the original file.
289 *
290 * @param string $saveName
291 * @param string $tempName full path to the temporary file
292 * @param bool $useRename if true, doesn't check that the source file
293 * is a PHP-managed upload temporary
294 */
295 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
296 global $wgUploadDirectory, $wgOut;
297
298 $dest = wfImageDir( $saveName );
299 $archive = wfImageArchiveDir( $saveName );
300 $this->mSavedFile = "{$dest}/{$saveName}";
301
302 if( is_file( $this->mSavedFile ) ) {
303 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
304 wfSuppressWarnings();
305 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
306 wfRestoreWarnings();
307
308 if( ! $success ) {
309 $wgOut->fileRenameError( $this->mSavedFile,
310 "${archive}/{$this->mUploadOldVersion}" );
311 return false;
312 }
313 } else {
314 $this->mUploadOldVersion = '';
315 }
316
317 if( $useRename ) {
318 wfSuppressWarnings();
319 $success = rename( $tempName, $this->mSavedFile );
320 wfRestoreWarnings();
321
322 if( ! $success ) {
323 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
324 return false;
325 }
326 } else {
327 wfSuppressWarnings();
328 $success = move_uploaded_file( $tempName, $this->mSavedFile );
329 wfRestoreWarnings();
330
331 if( ! $success ) {
332 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
333 return false;
334 }
335 }
336 chmod( $this->mSavedFile, 0644 );
337 return true;
338 }
339
340 /**
341 * Stash a file in a temporary directory for later processing
342 * after the user has confirmed it.
343 *
344 * If the user doesn't explicitly cancel or accept, these files
345 * can accumulate in the temp directory.
346 *
347 * @param string $saveName - the destination filename
348 * @param string $tempName - the source temporary file to save
349 * @return string - full path the stashed file, or false on failure
350 * @access private
351 */
352 function saveTempUploadedFile( $saveName, $tempName ) {
353 global $wgOut;
354 $archive = wfImageArchiveDir( $saveName, 'temp' );
355 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
356
357 if ( !move_uploaded_file( $tempName, $stash ) ) {
358 $wgOut->fileCopyError( $tempName, $stash );
359 return false;
360 }
361
362 return $stash;
363 }
364
365 /**
366 * Stash a file in a temporary directory for later processing,
367 * and save the necessary descriptive info into the session.
368 * Returns a key value which will be passed through a form
369 * to pick up the path info on a later invocation.
370 *
371 * @return int
372 * @access private
373 */
374 function stashSession() {
375 $stash = $this->saveTempUploadedFile(
376 $this->mUploadSaveName, $this->mUploadTempName );
377
378 if( !$stash ) {
379 # Couldn't save the file.
380 return false;
381 }
382
383 $key = mt_rand( 0, 0x7fffffff );
384 $_SESSION['wsUploadData'][$key] = array(
385 'mUploadTempName' => $stash,
386 'mUploadSize' => $this->mUploadSize,
387 'mOname' => $this->mOname );
388 return $key;
389 }
390
391 /**
392 * Remove a temporarily kept file stashed by saveTempUploadedFile().
393 * @access private
394 */
395 function unsaveUploadedFile() {
396 wfSuppressWarnings();
397 $success = unlink( $this->mUploadTempName );
398 wfRestoreWarnings();
399 if ( ! $success ) {
400 $wgOut->fileDeleteError( $this->mUploadTempName );
401 }
402 }
403
404 /* -------------------------------------------------------------- */
405
406 /**
407 * Show some text and linkage on successful upload.
408 * @access private
409 */
410 function showSuccess() {
411 global $wgUser, $wgOut, $wgContLang;
412
413 $sk = $wgUser->getSkin();
414 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::wfImageUrl( $this->mUploadSaveName ) );
415 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
416 $dlink = $sk->makeKnownLink( $dname, $dname );
417
418 $wgOut->addHTML( '<h2>' . wfMsg( 'successfulupload' ) . "</h2>\n" );
419 $text = wfMsg( 'fileuploaded', $ilink, $dlink );
420 $wgOut->addHTML( '<p>'.$text."\n" );
421 $wgOut->returnToMain( false );
422 }
423
424 /**
425 * @param string $error as HTML
426 * @access private
427 */
428 function uploadError( $error ) {
429 global $wgOut;
430 $sub = wfMsg( 'uploadwarning' );
431 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
432 $wgOut->addHTML( "<h4 class='error'>{$error}</h4>\n" );
433 }
434
435 /**
436 * There's something wrong with this file, not enough to reject it
437 * totally but we require manual intervention to save it for real.
438 * Stash it away, then present a form asking to confirm or cancel.
439 *
440 * @param string $warning as HTML
441 * @access private
442 */
443 function uploadWarning( $warning ) {
444 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
445 global $wgUseCopyrightUpload;
446
447 $this->mSessionKey = $this->stashSession();
448 if( !$this->mSessionKey ) {
449 # Couldn't save file; an error has been displayed so let's go.
450 return;
451 }
452
453 $sub = wfMsg( 'uploadwarning' );
454 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
455 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
456
457 $save = wfMsg( 'savefile' );
458 $reupload = wfMsg( 'reupload' );
459 $iw = wfMsg( 'ignorewarning' );
460 $reup = wfMsg( 'reuploaddesc' );
461 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
462 $action = $titleObj->escapeLocalURL( 'action=submit' );
463
464 if ( $wgUseCopyrightUpload )
465 {
466 $copyright = "
467 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
468 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
469 ";
470 } else {
471 $copyright = "";
472 }
473
474 $wgOut->addHTML( "
475 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
476 <input type='hidden' name='wpUploadAffirm' value='1' />
477 <input type='hidden' name='wpIgnoreWarning' value='1' />
478 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
479 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
480 {$copyright}
481 <table border='0'>
482 <tr>
483 <tr>
484 <td align='right'>
485 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
486 </td>
487 <td align='left'>$iw</td>
488 </tr>
489 <tr>
490 <td align='right'>
491 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
492 </td>
493 <td align='left'>$reup</td>
494 </tr>
495 </tr>
496 </table></form>\n" );
497 }
498
499 /**
500 * Displays the main upload form, optionally with a highlighted
501 * error message up at the top.
502 *
503 * @param string $msg as HTML
504 * @access private
505 */
506 function mainUploadForm( $msg='' ) {
507 global $wgOut, $wgUser, $wgLang, $wgUploadDirectory, $wgRequest;
508 global $wgUseCopyrightUpload;
509
510 $cols = intval($wgUser->getOption( 'cols' ));
511 $ew = $wgUser->getOption( 'editwidth' );
512 if ( $ew ) $ew = " style=\"width:100%\"";
513 else $ew = '';
514
515 if ( '' != $msg ) {
516 $sub = wfMsg( 'uploaderror' );
517 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
518 "<h4 class='error'>{$msg}</h4>\n" );
519 } else {
520 $sub = wfMsg( 'uploadfile' );
521 $wgOut->addHTML( "<h2>{$sub}</h2>\n" );
522 }
523 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
524 $sk = $wgUser->getSkin();
525
526 $fn = wfMsg( 'filename' );
527 $fd = wfMsg( 'filedesc' );
528 $ulb = wfMsg( 'uploadbtn' );
529
530 $clink = $sk->makeKnownLink( wfMsgForContent( 'copyrightpage' ),
531 wfMsg( 'copyrightpagename' ) );
532 $ca = wfMsg( 'affirmation', $clink );
533 $iw = wfMsg( 'ignorewarning' );
534
535 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
536 $action = $titleObj->escapeLocalURL();
537
538 $source = "
539 <td align='right'>
540 <input tabindex='3' type='checkbox' name='wpUploadAffirm' value='1' id='wpUploadAffirm' />
541 </td><td align='left'><label for='wpUploadAffirm'>{$ca}</label></td>
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 <td align='right'>{$fn}:</td><td align='left'>
560 <input tabindex='1' type='file' name='wpUploadFile' size='40' />
561 </td></tr><tr>
562 <td align='right'>{$fd}:</td><td align='left'>
563 <textarea tabindex='2' name='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>"
564 . htmlspecialchars( $this->mUploadDescription ) .
565 "</textarea>
566 </td></tr><tr>
567 {$source}
568 </tr>
569 <tr><td></td><td align='left'>
570 <input tabindex='5' type='submit' name='wpUpload' value=\"{$ulb}\" />
571 </td></tr></table></form>\n" );
572 }
573
574 /* -------------------------------------------------------------- */
575
576 /**
577 * Split a file into a base name and all dot-delimited 'extensions'
578 * on the end. Some web server configurations will fall back to
579 * earlier pseudo-'extensions' to determine type and execute
580 * scripts, so the blacklist needs to check them all.
581 *
582 * @return array
583 */
584 function splitExtensions( $filename ) {
585 $bits = explode( '.', $filename );
586 $basename = array_shift( $bits );
587 return array( $basename, $bits );
588 }
589
590 /**
591 * Perform case-insensitive match against a list of file extensions.
592 * Returns true if the extension is in the list.
593 *
594 * @param string $ext
595 * @param array $list
596 * @return bool
597 */
598 function checkFileExtension( $ext, $list ) {
599 return in_array( strtolower( $ext ), $list );
600 }
601
602 /**
603 * Perform case-insensitive match against a list of file extensions.
604 * Returns true if any of the extensions are in the list.
605 *
606 * @param array $ext
607 * @param array $list
608 * @return bool
609 */
610 function checkFileExtensionList( $ext, $list ) {
611 foreach( $ext as $e ) {
612 if( in_array( strtolower( $e ), $list ) ) {
613 return true;
614 }
615 }
616 return false;
617 }
618
619 /**
620 * Returns false if the file is of a known type but can't be recognized,
621 * indicating a corrupt file.
622 * Returns true otherwise; unknown file types are not checked if given
623 * with an unrecognized extension.
624 *
625 * @param string $tmpfile Pathname to the temporary upload file
626 * @param string $extension The filename extension that the file is to be served with
627 * @return bool
628 */
629 function verify( $tmpfile, $extension ) {
630 if( $this->triggersIEbug( $tmpfile ) ||
631 $this->triggersSafariBug( $tmpfile ) ) {
632 return false;
633 }
634
635 $fname = 'SpecialUpload::verify';
636 $mergeExtensions = array(
637 'jpg' => 'jpeg',
638 'tif' => 'tiff' );
639 $extensionTypes = array(
640 # See http://www.php.net/getimagesize
641 1 => 'gif',
642 2 => 'jpeg',
643 3 => 'png',
644 4 => 'swf',
645 5 => 'psd',
646 6 => 'bmp',
647 7 => 'tiff',
648 8 => 'tiff',
649 9 => 'jpc',
650 10 => 'jp2',
651 11 => 'jpx',
652 12 => 'jb2',
653 13 => 'swc',
654 14 => 'iff',
655 15 => 'wbmp',
656 16 => 'xbm' );
657
658 $extension = strtolower( $extension );
659 if( isset( $mergeExtensions[$extension] ) ) {
660 $extension = $mergeExtensions[$extension];
661 }
662 wfDebug( "$fname: Testing file '$tmpfile' with given extension '$extension'\n" );
663
664 if( !in_array( $extension, $extensionTypes ) ) {
665 # Not a recognized image type. We don't know how to verify these.
666 # They're allowed by policy or they wouldn't get this far, so we'll
667 # let them slide for now.
668 wfDebug( "$fname: Unknown extension; passing.\n" );
669 return true;
670 }
671
672 wfSuppressWarnings();
673 $data = getimagesize( $tmpfile );
674 wfRestoreWarnings();
675 if( false === $data ) {
676 # Didn't recognize the image type.
677 # Either the image is corrupt or someone's slipping us some
678 # bogus data such as HTML+JavaScript trying to take advantage
679 # of an Internet Explorer security flaw.
680 wfDebug( "$fname: getimagesize() doesn't recognize the file; rejecting.\n" );
681 return false;
682 }
683
684 $imageType = $data[2];
685 if( !isset( $extensionTypes[$imageType] ) ) {
686 # Now we're kind of confused. Perhaps new image types added
687 # to PHP's support that we don't know about.
688 # We'll let these slide for now.
689 wfDebug( "$fname: getimagesize() knows the file, but we don't recognize the type; passing.\n" );
690 return true;
691 }
692
693 $ext = strtolower( $extension );
694 if( $extension != $extensionTypes[$imageType] ) {
695 # The given filename extension doesn't match the
696 # file type. Probably just a mistake, but it's a stupid
697 # one and we shouldn't let it pass. KILL THEM!
698 wfDebug( "$fname: file extension does not match recognized type; rejecting.\n" );
699 return false;
700 }
701
702 wfDebug( "$fname: all clear; passing.\n" );
703 return true;
704 }
705
706 /**
707 * Internet Explorer for Windows performs some really stupid file type
708 * autodetection which can cause it to interpret valid image files as HTML
709 * and potentially execute JavaScript, creating a cross-site scripting
710 * attack vectors.
711 *
712 * Returns true if IE is likely to mistake the given file for HTML.
713 *
714 * @param string $filename
715 * @return bool
716 */
717 function triggersIEbug( $filename ) {
718 $file = fopen( $filename, 'rb' );
719 $chunk = strtolower( fread( $file, 256 ) );
720 fclose( $file );
721
722 $tags = array(
723 '<body',
724 '<head',
725 '<html',
726 '<img',
727 '<pre',
728 '<script',
729 '<table',
730 '<title' );
731 foreach( $tags as $tag ) {
732 if( false !== strpos( $chunk, $tag ) ) {
733 return true;
734 }
735 }
736 return false;
737 }
738
739 /**
740 * Apple's Safari browser performs some unsafe file type autodetection
741 * which can cause legitimate files to be interpreted as HTML if the
742 * web server is not correctly configured to send the right content-type
743 * (or if you're really uploading plain text and octet streams!)
744 *
745 * Returns true if Safari would mistake the given file for HTML
746 * when served with a generic content-type.
747 *
748 * @param string $filename
749 * @return bool
750 */
751 function triggersSafariBug( $filename ) {
752 $file = fopen( $filename, 'rb' );
753 $chunk = strtolower( fread( $file, 1024 ) );
754 fclose( $file );
755
756 $tags = array(
757 '<html',
758 '<script',
759 '<title' );
760 foreach( $tags as $tag ) {
761 if( false !== strpos( $chunk, $tag ) ) {
762 return true;
763 }
764 }
765 return false;
766 }
767
768 }
769 ?>