MediaWiki  master
router.php
Go to the documentation of this file.
1 <?php
24 if ( PHP_SAPI != 'cli-server' ) {
25  die( "This script can only be run by php's cli-server sapi." );
26 }
27 
28 if ( !isset( $_SERVER['SCRIPT_FILENAME'] ) ) {
29  // Let built-in server handle error.
30  return false;
31 }
32 
33 // The SCRIPT_FILENAME can be one of three things:
34 // 1. Absolute path to a file in the docroot associated with the
35 // path of the current request URL. PHP does this for any file path
36 // where it finds a matching file on disk. For both PHP files, and for
37 // static files.
38 // 2. Relative path to router.php (this file), for any unknown URL path
39 // that ends in ".php" or another extension that PHP would execute.
40 // 3. Absolute path to {docroot}/index.php, for any other unknown path.
41 // Effectively treating it as a 404 handler.
42 $file = $_SERVER['SCRIPT_FILENAME'];
43 if ( !is_readable( $file ) ) {
44  // Let built-in server handle error.
45  return false;
46 }
47 
48 $ext = pathinfo( $file, PATHINFO_EXTENSION );
49 if ( $ext == 'php' ) {
50  // Let built-in server handle script inclusion.
51  return false;
52 } else {
53  // Serve static file with appropiate Content-Type headers.
54  // The built-in server for PHP 7.0+ supports most files already
55  // (contrary to PHP 5.2, which was supported when router.php was created).
56  // But it still doesn't support as many MIME types as MediaWiki (e.g. ".json")
57 
58  // Fallback
59  $mime = 'text/plain';
60  // Borrow from MimeAnalyzer
61  $lines = explode( "\n", file_get_contents( "includes/libs/mime/mime.types" ) );
62  foreach ( $lines as $line ) {
63  $exts = explode( ' ', $line );
64  $type = array_shift( $exts );
65  if ( in_array( $ext, $exts ) ) {
66  $mime = $type;
67  break;
68  }
69  }
70 
71  if ( preg_match( '#^text/#', $mime ) ) {
72  // Text should have a charset=UTF-8 (PHP's webserver does this too)
73  header( "Content-Type: $mime; charset=UTF-8" );
74  } else {
75  header( "Content-Type: $mime" );
76  }
77 
78  $content = file_get_contents( $file );
79 
80  header( 'Vary: Accept-Encoding' );
81  $acceptGzip = preg_match( '/\bgzip\b/', $_SERVER['HTTP_ACCEPT_ENCODING'] ?? '' );
82  if ( $acceptGzip &&
83  // Don't compress binary static files (e.g. png)
84  preg_match( '/text|javascript|json|css|xml|svg/', $mime ) &&
85  // Tiny files tend to grow instead of shrink. – <https://gerrit.wikimedia.org/r/537974>
86  strlen( $content ) > 150
87  ) {
88  $content = gzencode( $content, 9 );
89  header( 'Content-Encoding: gzip' );
90  }
91  header( "Content-Length: " . strlen( $content ) );
92  echo $content;
93 
94  return true;
95 }
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
$acceptGzip
Definition: router.php:81
$lines
Definition: router.php:61
if(!is_readable( $file)) $ext
Definition: router.php:48
$content
Definition: router.php:78