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