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