Skip to content

Commit

Permalink
Switch to mime-db as source of extension => MIME map
Browse files Browse the repository at this point in the history
The Apache MIME type map is not actively maintained anymore, so
this switches to jshttp/mime-db, which seems to be the de-facto
standard in this area now. This avoid the need to patch in our
own MIME types over time.

The preference algorithm is based on:
https://github.com/jshttp/mime-types/blob/47b62ac45e9b176a2af35532d0eea4968bb9eb6d/index.js#L154

Closes GH-5764.
  • Loading branch information
nikic committed Aug 13, 2020
1 parent cdc4e49 commit e17ff61
Show file tree
Hide file tree
Showing 2 changed files with 210 additions and 28 deletions.
38 changes: 24 additions & 14 deletions sapi/cli/generate_mime_type_map.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,42 @@

// Check if we are being given a mime.types file or if we should use the
// default URL.
$source = count($_SERVER['argv']) > 1 ? $_SERVER['argv'][1] : 'https://raw.githubusercontent.com/apache/httpd/trunk/docs/conf/mime.types';
$source = count($argv) > 1 ? $argv[1] : 'https://cdn.jsdelivr.net/gh/jshttp/mime-db@v1.44.0/db.json';

// See if we can actually load it.
$types = @file($source);
if ($types === false) {
$data = @file_get_contents($source);
if ($data === false) {
fprintf(STDERR, "Error: unable to read $source\n");
exit(1);
}

// Remove comments and flip into an extensions array.
// Source preference from lowest to highest
$prefs = ['nginx' => 1, 'apache' => 2, 'custom' => 3, 'iana' => 4];

$extensions = [];
array_walk($types, function ($line) use (&$extensions) {
$line = trim($line);
if ($line && $line[0] != '#') {
$fields = preg_split('/\s+/', $line);
if (count($fields) > 1) {
$mime = array_shift($fields);
foreach ($fields as $extension) {
$extensions[$extension] = $mime;
$types = json_decode($data, true);
foreach ($types as $mime => $info) {
$source = $info['source'] ?? 'custom';
$pref = $prefs[$source];
foreach ($info['extensions'] ?? [] as $extension) {
if (isset($extensions[$extension])) {
// Use same preference rules as jshttp/mime-types
[$oldMime, $oldPref] = $extensions[$extension];
if ($oldMime !== 'application/octet-stream'
&& ($oldPref > $pref
|| ($oldPref === $pref && substr($oldMime, 0, 12) === 'application/'))) {
continue;
}
}

$extensions[$extension] = [$mime, $pref];
}
});
}

// Only keep the MIME type.
$extensions = array_map(function($x) { return $x[0]; }, $extensions);

$additional_mime_maps = [
"map" => "application/json", // from commit: a0d62f08ae8cbebc88e5c92e08fca8d0cdc7309d
"jsm" => "application/javascript",
];

Expand Down

0 comments on commit e17ff61

Please sign in to comment.