MimeAnalyzer.php 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233
  1. <?php
  2. /**
  3. * Module defining helper functions for detecting and dealing with MIME types.
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use Psr\Log\LoggerAwareInterface;
  23. use Psr\Log\LoggerInterface;
  24. use Psr\Log\NullLogger;
  25. /**
  26. * Implements functions related to MIME types such as detection and mapping to file extension
  27. *
  28. * @since 1.28
  29. */
  30. class MimeAnalyzer implements LoggerAwareInterface {
  31. /** @var string */
  32. protected $typeFile;
  33. /** @var string */
  34. protected $infoFile;
  35. /** @var string */
  36. protected $xmlTypes;
  37. /** @var callable */
  38. protected $initCallback;
  39. /** @var callable */
  40. protected $detectCallback;
  41. /** @var callable */
  42. protected $guessCallback;
  43. /** @var callable */
  44. protected $extCallback;
  45. /** @var array Mapping of media types to arrays of MIME types */
  46. protected $mediaTypes = null;
  47. /** @var array Map of MIME type aliases */
  48. protected $mimeTypeAliases = null;
  49. /** @var array Map of MIME types to file extensions (as a space separated list) */
  50. protected $mimetoExt = null;
  51. /** @var array Map of file extensions types to MIME types (as a space separated list) */
  52. public $mExtToMime = null; // legacy name; field accessed by hooks
  53. /** @var IEContentAnalyzer */
  54. protected $IEAnalyzer;
  55. /** @var string Extra MIME types, set for example by media handling extensions */
  56. private $extraTypes = '';
  57. /** @var string Extra MIME info, set for example by media handling extensions */
  58. private $extraInfo = '';
  59. /** @var LoggerInterface */
  60. private $logger;
  61. /**
  62. * Defines a set of well known MIME types
  63. * This is used as a fallback to mime.types files.
  64. * An extensive list of well known MIME types is provided by
  65. * the file mime.types in the includes directory.
  66. *
  67. * This list concatenated with mime.types is used to create a MIME <-> ext
  68. * map. Each line contains a MIME type followed by a space separated list of
  69. * extensions. If multiple extensions for a single MIME type exist or if
  70. * multiple MIME types exist for a single extension then in most cases
  71. * MediaWiki assumes that the first extension following the MIME type is the
  72. * canonical extension, and the first time a MIME type appears for a certain
  73. * extension is considered the canonical MIME type.
  74. *
  75. * (Note that appending the type file list to the end of self::$wellKnownTypes
  76. * sucks because you can't redefine canonical types. This could be fixed by
  77. * appending self::$wellKnownTypes behind type file list, but who knows
  78. * what will break? In practice this probably isn't a problem anyway -- Bryan)
  79. */
  80. protected static $wellKnownTypes = <<<EOT
  81. application/ogg ogx ogg ogm ogv oga spx opus
  82. application/pdf pdf
  83. application/vnd.oasis.opendocument.chart odc
  84. application/vnd.oasis.opendocument.chart-template otc
  85. application/vnd.oasis.opendocument.database odb
  86. application/vnd.oasis.opendocument.formula odf
  87. application/vnd.oasis.opendocument.formula-template otf
  88. application/vnd.oasis.opendocument.graphics odg
  89. application/vnd.oasis.opendocument.graphics-template otg
  90. application/vnd.oasis.opendocument.image odi
  91. application/vnd.oasis.opendocument.image-template oti
  92. application/vnd.oasis.opendocument.presentation odp
  93. application/vnd.oasis.opendocument.presentation-template otp
  94. application/vnd.oasis.opendocument.spreadsheet ods
  95. application/vnd.oasis.opendocument.spreadsheet-template ots
  96. application/vnd.oasis.opendocument.text odt
  97. application/vnd.oasis.opendocument.text-master otm
  98. application/vnd.oasis.opendocument.text-template ott
  99. application/vnd.oasis.opendocument.text-web oth
  100. application/javascript js
  101. application/x-shockwave-flash swf
  102. audio/midi mid midi kar
  103. audio/mpeg mpga mpa mp2 mp3
  104. audio/x-aiff aif aiff aifc
  105. audio/x-wav wav
  106. audio/ogg oga spx ogg opus
  107. audio/opus opus ogg oga ogg spx
  108. image/x-bmp bmp
  109. image/gif gif
  110. image/jpeg jpeg jpg jpe
  111. image/png png
  112. image/svg+xml svg
  113. image/svg svg
  114. image/tiff tiff tif
  115. image/vnd.djvu djvu
  116. image/x.djvu djvu
  117. image/x-djvu djvu
  118. image/x-portable-pixmap ppm
  119. image/x-xcf xcf
  120. text/plain txt
  121. text/html html htm
  122. video/ogg ogv ogm ogg
  123. video/mpeg mpg mpeg
  124. EOT;
  125. /**
  126. * Defines a set of well known MIME info entries
  127. * This is used as a fallback to mime.info files.
  128. * An extensive list of well known MIME types is provided by
  129. * the file mime.info in the includes directory.
  130. */
  131. protected static $wellKnownInfo = <<<EOT
  132. application/pdf [OFFICE]
  133. application/vnd.oasis.opendocument.chart [OFFICE]
  134. application/vnd.oasis.opendocument.chart-template [OFFICE]
  135. application/vnd.oasis.opendocument.database [OFFICE]
  136. application/vnd.oasis.opendocument.formula [OFFICE]
  137. application/vnd.oasis.opendocument.formula-template [OFFICE]
  138. application/vnd.oasis.opendocument.graphics [OFFICE]
  139. application/vnd.oasis.opendocument.graphics-template [OFFICE]
  140. application/vnd.oasis.opendocument.image [OFFICE]
  141. application/vnd.oasis.opendocument.image-template [OFFICE]
  142. application/vnd.oasis.opendocument.presentation [OFFICE]
  143. application/vnd.oasis.opendocument.presentation-template [OFFICE]
  144. application/vnd.oasis.opendocument.spreadsheet [OFFICE]
  145. application/vnd.oasis.opendocument.spreadsheet-template [OFFICE]
  146. application/vnd.oasis.opendocument.text [OFFICE]
  147. application/vnd.oasis.opendocument.text-template [OFFICE]
  148. application/vnd.oasis.opendocument.text-master [OFFICE]
  149. application/vnd.oasis.opendocument.text-web [OFFICE]
  150. application/javascript text/javascript application/x-javascript [EXECUTABLE]
  151. application/x-shockwave-flash [MULTIMEDIA]
  152. audio/midi [AUDIO]
  153. audio/x-aiff [AUDIO]
  154. audio/x-wav [AUDIO]
  155. audio/mp3 audio/mpeg [AUDIO]
  156. application/ogg audio/ogg video/ogg [MULTIMEDIA]
  157. image/x-bmp image/x-ms-bmp image/bmp [BITMAP]
  158. image/gif [BITMAP]
  159. image/jpeg [BITMAP]
  160. image/png [BITMAP]
  161. image/svg+xml [DRAWING]
  162. image/tiff [BITMAP]
  163. image/vnd.djvu [BITMAP]
  164. image/x-xcf [BITMAP]
  165. image/x-portable-pixmap [BITMAP]
  166. text/plain [TEXT]
  167. text/html [TEXT]
  168. video/ogg [VIDEO]
  169. video/mpeg [VIDEO]
  170. unknown/unknown application/octet-stream application/x-empty [UNKNOWN]
  171. EOT;
  172. /**
  173. * @param array $params Configuration map, includes:
  174. * - typeFile: path to file with the list of known MIME types
  175. * - infoFile: path to file with the MIME type info
  176. * - xmlTypes: map of root element names to XML MIME types
  177. * - initCallback: initialization callback that is passed this object [optional]
  178. * - detectCallback: alternative to finfo that returns the mime type for a file.
  179. * For example, the callback can return the output of "file -bi". [optional]
  180. * - guessCallback: callback to improve the guessed MIME type using the file data.
  181. * This is intended for fixing mistakes in fileinfo or "detectCallback". [optional]
  182. * - extCallback: callback to improve the guessed MIME type using the extension. [optional]
  183. * - logger: PSR-3 logger [optional]
  184. * @note Constructing these instances is expensive due to file reads.
  185. * A service or singleton pattern should be used to avoid creating instances again and again.
  186. */
  187. public function __construct( array $params ) {
  188. $this->typeFile = $params['typeFile'];
  189. $this->infoFile = $params['infoFile'];
  190. $this->xmlTypes = $params['xmlTypes'];
  191. $this->initCallback = $params['initCallback'] ?? null;
  192. $this->detectCallback = $params['detectCallback'] ?? null;
  193. $this->guessCallback = $params['guessCallback'] ?? null;
  194. $this->extCallback = $params['extCallback'] ?? null;
  195. $this->logger = $params['logger'] ?? new NullLogger();
  196. $this->loadFiles();
  197. }
  198. protected function loadFiles() {
  199. /**
  200. * --- load mime.types ---
  201. */
  202. # Allow media handling extensions adding MIME-types and MIME-info
  203. if ( $this->initCallback ) {
  204. call_user_func( $this->initCallback, $this );
  205. }
  206. $types = self::$wellKnownTypes;
  207. $mimeTypeFile = $this->typeFile;
  208. if ( $mimeTypeFile ) {
  209. if ( is_file( $mimeTypeFile ) && is_readable( $mimeTypeFile ) ) {
  210. $this->logger->info( __METHOD__ . ": loading mime types from $mimeTypeFile\n" );
  211. $types .= "\n";
  212. $types .= file_get_contents( $mimeTypeFile );
  213. } else {
  214. $this->logger->info( __METHOD__ . ": can't load mime types from $mimeTypeFile\n" );
  215. }
  216. } else {
  217. $this->logger->info( __METHOD__ .
  218. ": no mime types file defined, using built-ins only.\n" );
  219. }
  220. $types .= "\n" . $this->extraTypes;
  221. $types = str_replace( [ "\r\n", "\n\r", "\n\n", "\r\r", "\r" ], "\n", $types );
  222. $types = str_replace( "\t", " ", $types );
  223. $this->mimetoExt = [];
  224. $this->mExtToMime = [];
  225. $lines = explode( "\n", $types );
  226. foreach ( $lines as $s ) {
  227. $s = trim( $s );
  228. if ( empty( $s ) ) {
  229. continue;
  230. }
  231. if ( strpos( $s, '#' ) === 0 ) {
  232. continue;
  233. }
  234. $s = strtolower( $s );
  235. $i = strpos( $s, ' ' );
  236. if ( $i === false ) {
  237. continue;
  238. }
  239. $mime = substr( $s, 0, $i );
  240. $ext = trim( substr( $s, $i + 1 ) );
  241. if ( empty( $ext ) ) {
  242. continue;
  243. }
  244. if ( !empty( $this->mimetoExt[$mime] ) ) {
  245. $this->mimetoExt[$mime] .= ' ' . $ext;
  246. } else {
  247. $this->mimetoExt[$mime] = $ext;
  248. }
  249. $extensions = explode( ' ', $ext );
  250. foreach ( $extensions as $e ) {
  251. $e = trim( $e );
  252. if ( empty( $e ) ) {
  253. continue;
  254. }
  255. if ( !empty( $this->mExtToMime[$e] ) ) {
  256. $this->mExtToMime[$e] .= ' ' . $mime;
  257. } else {
  258. $this->mExtToMime[$e] = $mime;
  259. }
  260. }
  261. }
  262. /**
  263. * --- load mime.info ---
  264. */
  265. $mimeInfoFile = $this->infoFile;
  266. $info = self::$wellKnownInfo;
  267. if ( $mimeInfoFile ) {
  268. if ( is_file( $mimeInfoFile ) && is_readable( $mimeInfoFile ) ) {
  269. $this->logger->info( __METHOD__ . ": loading mime info from $mimeInfoFile\n" );
  270. $info .= "\n";
  271. $info .= file_get_contents( $mimeInfoFile );
  272. } else {
  273. $this->logger->info( __METHOD__ . ": can't load mime info from $mimeInfoFile\n" );
  274. }
  275. } else {
  276. $this->logger->info( __METHOD__ .
  277. ": no mime info file defined, using built-ins only.\n" );
  278. }
  279. $info .= "\n" . $this->extraInfo;
  280. $info = str_replace( [ "\r\n", "\n\r", "\n\n", "\r\r", "\r" ], "\n", $info );
  281. $info = str_replace( "\t", " ", $info );
  282. $this->mimeTypeAliases = [];
  283. $this->mediaTypes = [];
  284. $lines = explode( "\n", $info );
  285. foreach ( $lines as $s ) {
  286. $s = trim( $s );
  287. if ( empty( $s ) ) {
  288. continue;
  289. }
  290. if ( strpos( $s, '#' ) === 0 ) {
  291. continue;
  292. }
  293. $s = strtolower( $s );
  294. $i = strpos( $s, ' ' );
  295. if ( $i === false ) {
  296. continue;
  297. }
  298. # print "processing MIME INFO line $s<br>";
  299. $match = [];
  300. if ( preg_match( '!\[\s*(\w+)\s*\]!', $s, $match ) ) {
  301. $s = preg_replace( '!\[\s*(\w+)\s*\]!', '', $s );
  302. $mtype = trim( strtoupper( $match[1] ) );
  303. } else {
  304. $mtype = MEDIATYPE_UNKNOWN;
  305. }
  306. $m = explode( ' ', $s );
  307. if ( !isset( $this->mediaTypes[$mtype] ) ) {
  308. $this->mediaTypes[$mtype] = [];
  309. }
  310. foreach ( $m as $mime ) {
  311. $mime = trim( $mime );
  312. if ( empty( $mime ) ) {
  313. continue;
  314. }
  315. $this->mediaTypes[$mtype][] = $mime;
  316. }
  317. if ( count( $m ) > 1 ) {
  318. $main = $m[0];
  319. $mCount = count( $m );
  320. for ( $i = 1; $i < $mCount; $i += 1 ) {
  321. $mime = $m[$i];
  322. $this->mimeTypeAliases[$mime] = $main;
  323. }
  324. }
  325. }
  326. }
  327. public function setLogger( LoggerInterface $logger ) {
  328. $this->logger = $logger;
  329. }
  330. /**
  331. * Adds to the list mapping MIME to file extensions.
  332. * As an extension author, you are encouraged to submit patches to
  333. * MediaWiki's core to add new MIME types to mime.types.
  334. * @param string $types
  335. */
  336. public function addExtraTypes( $types ) {
  337. $this->extraTypes .= "\n" . $types;
  338. }
  339. /**
  340. * Adds to the list mapping MIME to media type.
  341. * As an extension author, you are encouraged to submit patches to
  342. * MediaWiki's core to add new MIME info to mime.info.
  343. * @param string $info
  344. */
  345. public function addExtraInfo( $info ) {
  346. $this->extraInfo .= "\n" . $info;
  347. }
  348. /**
  349. * Returns a list of file extensions for a given MIME type as a space
  350. * separated string or null if the MIME type was unrecognized. Resolves
  351. * MIME type aliases.
  352. *
  353. * @param string $mime
  354. * @return string|null
  355. */
  356. public function getExtensionsForType( $mime ) {
  357. $mime = strtolower( $mime );
  358. // Check the mime-to-ext map
  359. if ( isset( $this->mimetoExt[$mime] ) ) {
  360. return $this->mimetoExt[$mime];
  361. }
  362. // Resolve the MIME type to the canonical type
  363. if ( isset( $this->mimeTypeAliases[$mime] ) ) {
  364. $mime = $this->mimeTypeAliases[$mime];
  365. if ( isset( $this->mimetoExt[$mime] ) ) {
  366. return $this->mimetoExt[$mime];
  367. }
  368. }
  369. return null;
  370. }
  371. /**
  372. * Returns a list of MIME types for a given file extension as a space
  373. * separated string or null if the extension was unrecognized.
  374. *
  375. * @param string $ext
  376. * @return string|null
  377. */
  378. public function getTypesForExtension( $ext ) {
  379. $ext = strtolower( $ext );
  380. $r = $this->mExtToMime[$ext] ?? null;
  381. return $r;
  382. }
  383. /**
  384. * Returns a single MIME type for a given file extension or null if unknown.
  385. * This is always the first type from the list returned by getTypesForExtension($ext).
  386. *
  387. * @param string $ext
  388. * @return string|null
  389. */
  390. public function guessTypesForExtension( $ext ) {
  391. $m = $this->getTypesForExtension( $ext );
  392. if ( is_null( $m ) ) {
  393. return null;
  394. }
  395. // TODO: Check if this is needed; strtok( $m, ' ' ) should be sufficient
  396. $m = trim( $m );
  397. $m = preg_replace( '/\s.*$/', '', $m );
  398. return $m;
  399. }
  400. /**
  401. * Tests if the extension matches the given MIME type. Returns true if a
  402. * match was found, null if the MIME type is unknown, and false if the
  403. * MIME type is known but no matches where found.
  404. *
  405. * @param string $extension
  406. * @param string $mime
  407. * @return bool|null
  408. */
  409. public function isMatchingExtension( $extension, $mime ) {
  410. $ext = $this->getExtensionsForType( $mime );
  411. if ( !$ext ) {
  412. return null; // Unknown MIME type
  413. }
  414. $ext = explode( ' ', $ext );
  415. $extension = strtolower( $extension );
  416. return in_array( $extension, $ext );
  417. }
  418. /**
  419. * Returns true if the MIME type is known to represent an image format
  420. * supported by the PHP GD library.
  421. *
  422. * @param string $mime
  423. *
  424. * @return bool
  425. */
  426. public function isPHPImageType( $mime ) {
  427. // As defined by imagegetsize and image_type_to_mime
  428. static $types = [
  429. 'image/gif', 'image/jpeg', 'image/png',
  430. 'image/x-bmp', 'image/xbm', 'image/tiff',
  431. 'image/jp2', 'image/jpeg2000', 'image/iff',
  432. 'image/xbm', 'image/x-xbitmap',
  433. 'image/vnd.wap.wbmp', 'image/vnd.xiff',
  434. 'image/x-photoshop',
  435. 'application/x-shockwave-flash',
  436. ];
  437. return in_array( $mime, $types );
  438. }
  439. /**
  440. * Returns true if the extension represents a type which can
  441. * be reliably detected from its content. Use this to determine
  442. * whether strict content checks should be applied to reject
  443. * invalid uploads; if we can't identify the type we won't
  444. * be able to say if it's invalid.
  445. *
  446. * @todo Be more accurate when using fancy MIME detector plugins;
  447. * right now this is the bare minimum getimagesize() list.
  448. * @param string $extension
  449. * @return bool
  450. */
  451. function isRecognizableExtension( $extension ) {
  452. static $types = [
  453. // Types recognized by getimagesize()
  454. 'gif', 'jpeg', 'jpg', 'png', 'swf', 'psd',
  455. 'bmp', 'tiff', 'tif', 'jpc', 'jp2',
  456. 'jpx', 'jb2', 'swc', 'iff', 'wbmp',
  457. 'xbm',
  458. // Formats we recognize magic numbers for
  459. 'djvu', 'ogx', 'ogg', 'ogv', 'oga', 'spx', 'opus',
  460. 'mid', 'pdf', 'wmf', 'xcf', 'webm', 'mkv', 'mka',
  461. 'webp', 'mp3',
  462. // XML formats we sure hope we recognize reliably
  463. 'svg',
  464. // 3D formats
  465. 'stl',
  466. ];
  467. return in_array( strtolower( $extension ), $types );
  468. }
  469. /**
  470. * Improves a MIME type using the file extension. Some file formats are very generic,
  471. * so their MIME type is not very meaningful. A more useful MIME type can be derived
  472. * by looking at the file extension. Typically, this method would be called on the
  473. * result of guessMimeType().
  474. *
  475. * @param string $mime The MIME type, typically guessed from a file's content.
  476. * @param string $ext The file extension, as taken from the file name
  477. *
  478. * @return string The MIME type
  479. */
  480. public function improveTypeFromExtension( $mime, $ext ) {
  481. if ( $mime === 'unknown/unknown' ) {
  482. if ( $this->isRecognizableExtension( $ext ) ) {
  483. $this->logger->info( __METHOD__ . ': refusing to guess mime type for .' .
  484. "$ext file, we should have recognized it\n" );
  485. } else {
  486. // Not something we can detect, so simply
  487. // trust the file extension
  488. $mime = $this->guessTypesForExtension( $ext );
  489. }
  490. } elseif ( $mime === 'application/x-opc+zip' ) {
  491. if ( $this->isMatchingExtension( $ext, $mime ) ) {
  492. // A known file extension for an OPC file,
  493. // find the proper MIME type for that file extension
  494. $mime = $this->guessTypesForExtension( $ext );
  495. } else {
  496. $this->logger->info( __METHOD__ .
  497. ": refusing to guess better type for $mime file, " .
  498. ".$ext is not a known OPC extension.\n" );
  499. $mime = 'application/zip';
  500. }
  501. } elseif ( $mime === 'text/plain' && $this->findMediaType( ".$ext" ) === MEDIATYPE_TEXT ) {
  502. // Textual types are sometimes not recognized properly.
  503. // If detected as text/plain, and has an extension which is textual
  504. // improve to the extension's type. For example, csv and json are often
  505. // misdetected as text/plain.
  506. $mime = $this->guessTypesForExtension( $ext );
  507. }
  508. # Media handling extensions can improve the MIME detected
  509. $callback = $this->extCallback;
  510. if ( $callback ) {
  511. $callback( $this, $ext, $mime /* by reference */ );
  512. }
  513. if ( isset( $this->mimeTypeAliases[$mime] ) ) {
  514. $mime = $this->mimeTypeAliases[$mime];
  515. }
  516. $this->logger->info( __METHOD__ . ": improved mime type for .$ext: $mime\n" );
  517. return $mime;
  518. }
  519. /**
  520. * MIME type detection. This uses detectMimeType to detect the MIME type
  521. * of the file, but applies additional checks to determine some well known
  522. * file formats that may be missed or misinterpreted by the default MIME
  523. * detection (namely XML based formats like XHTML or SVG, as well as ZIP
  524. * based formats like OPC/ODF files).
  525. *
  526. * @param string $file The file to check
  527. * @param string|bool $ext The file extension, or true (default) to extract
  528. * it from the filename. Set it to false to ignore the extension. DEPRECATED!
  529. * Set to false, use improveTypeFromExtension($mime, $ext) later to improve MIME type.
  530. *
  531. * @return string The MIME type of $file
  532. */
  533. public function guessMimeType( $file, $ext = true ) {
  534. if ( $ext ) { // TODO: make $ext default to false. Or better, remove it.
  535. $this->logger->info( __METHOD__ .
  536. ": WARNING: use of the \$ext parameter is deprecated. " .
  537. "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
  538. }
  539. $mime = $this->doGuessMimeType( $file, $ext );
  540. if ( !$mime ) {
  541. $this->logger->info( __METHOD__ .
  542. ": internal type detection failed for $file (.$ext)...\n" );
  543. $mime = $this->detectMimeType( $file, $ext );
  544. }
  545. if ( isset( $this->mimeTypeAliases[$mime] ) ) {
  546. $mime = $this->mimeTypeAliases[$mime];
  547. }
  548. $this->logger->info( __METHOD__ . ": guessed mime type of $file: $mime\n" );
  549. return $mime;
  550. }
  551. /**
  552. * Guess the MIME type from the file contents.
  553. *
  554. * @todo Remove $ext param
  555. *
  556. * @param string $file
  557. * @param mixed $ext
  558. * @return bool|string
  559. * @throws UnexpectedValueException
  560. */
  561. private function doGuessMimeType( $file, $ext ) {
  562. // Read a chunk of the file
  563. Wikimedia\suppressWarnings();
  564. $f = fopen( $file, 'rb' );
  565. Wikimedia\restoreWarnings();
  566. if ( !$f ) {
  567. return 'unknown/unknown';
  568. }
  569. $fsize = filesize( $file );
  570. if ( $fsize === false ) {
  571. return 'unknown/unknown';
  572. }
  573. $head = fread( $f, 1024 );
  574. $tailLength = min( 65558, $fsize ); // 65558 = maximum size of a zip EOCDR
  575. if ( fseek( $f, -1 * $tailLength, SEEK_END ) === -1 ) {
  576. throw new UnexpectedValueException(
  577. "Seeking $tailLength bytes from EOF failed in " . __METHOD__ );
  578. }
  579. $tail = $tailLength ? fread( $f, $tailLength ) : '';
  580. $this->logger->info( __METHOD__ .
  581. ": analyzing head and tail of $file for magic numbers.\n" );
  582. // Hardcode a few magic number checks...
  583. $headers = [
  584. // Multimedia...
  585. 'MThd' => 'audio/midi',
  586. 'OggS' => 'application/ogg',
  587. 'ID3' => 'audio/mpeg',
  588. "\xff\xfb" => 'audio/mpeg', // MPEG-1 layer 3
  589. "\xff\xf3" => 'audio/mpeg', // MPEG-2 layer 3 (lower sample rates)
  590. "\xff\xe3" => 'audio/mpeg', // MPEG-2.5 layer 3 (very low sample rates)
  591. // Image formats...
  592. // Note that WMF may have a bare header, no magic number.
  593. "\x01\x00\x09\x00" => 'application/x-msmetafile', // Possibly prone to false positives?
  594. "\xd7\xcd\xc6\x9a" => 'application/x-msmetafile',
  595. '%PDF' => 'application/pdf',
  596. 'gimp xcf' => 'image/x-xcf',
  597. // Some forbidden fruit...
  598. 'MZ' => 'application/octet-stream', // DOS/Windows executable
  599. "\xca\xfe\xba\xbe" => 'application/octet-stream', // Mach-O binary
  600. "\x7fELF" => 'application/octet-stream', // ELF binary
  601. ];
  602. foreach ( $headers as $magic => $candidate ) {
  603. if ( strncmp( $head, $magic, strlen( $magic ) ) == 0 ) {
  604. $this->logger->info( __METHOD__ .
  605. ": magic header in $file recognized as $candidate\n" );
  606. return $candidate;
  607. }
  608. }
  609. /* Look for WebM and Matroska files */
  610. if ( strncmp( $head, pack( "C4", 0x1a, 0x45, 0xdf, 0xa3 ), 4 ) == 0 ) {
  611. $doctype = strpos( $head, "\x42\x82" );
  612. if ( $doctype ) {
  613. // Next byte is datasize, then data (sizes larger than 1 byte are stupid muxers)
  614. $data = substr( $head, $doctype + 3, 8 );
  615. if ( strncmp( $data, "matroska", 8 ) == 0 ) {
  616. $this->logger->info( __METHOD__ . ": recognized file as video/x-matroska\n" );
  617. return "video/x-matroska";
  618. } elseif ( strncmp( $data, "webm", 4 ) == 0 ) {
  619. // XXX HACK look for a video track, if we don't find it, this is an audio file
  620. $videotrack = strpos( $head, "\x86\x85V_VP" );
  621. if ( $videotrack ) {
  622. // There is a video track, so this is a video file.
  623. $this->logger->info( __METHOD__ . ": recognized file as video/webm\n" );
  624. return "video/webm";
  625. }
  626. $this->logger->info( __METHOD__ . ": recognized file as audio/webm\n" );
  627. return "audio/webm";
  628. }
  629. }
  630. $this->logger->info( __METHOD__ . ": unknown EBML file\n" );
  631. return "unknown/unknown";
  632. }
  633. /* Look for WebP */
  634. if ( strncmp( $head, "RIFF", 4 ) == 0 &&
  635. strncmp( substr( $head, 8, 7 ), "WEBPVP8", 7 ) == 0
  636. ) {
  637. $this->logger->info( __METHOD__ . ": recognized file as image/webp\n" );
  638. return "image/webp";
  639. }
  640. /* Look for MS Compound Binary (OLE) files */
  641. if ( strncmp( $head, "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1", 8 ) == 0 ) {
  642. $this->logger->info( __METHOD__ . ': recognized MS CFB (OLE) file' );
  643. return $this->detectMicrosoftBinaryType( $f );
  644. }
  645. /**
  646. * Look for PHP. Check for this before HTML/XML... Warning: this is a
  647. * heuristic, and won't match a file with a lot of non-PHP before. It
  648. * will also match text files which could be PHP. :)
  649. *
  650. * @todo FIXME: For this reason, the check is probably useless -- an attacker
  651. * could almost certainly just pad the file with a lot of nonsense to
  652. * circumvent the check in any case where it would be a security
  653. * problem. On the other hand, it causes harmful false positives (bug
  654. * 16583). The heuristic has been cut down to exclude three-character
  655. * strings like "<? ", but should it be axed completely?
  656. */
  657. if ( ( strpos( $head, '<?php' ) !== false ) ||
  658. ( strpos( $head, "<\x00?\x00p\x00h\x00p" ) !== false ) ||
  659. ( strpos( $head, "<\x00?\x00 " ) !== false ) ||
  660. ( strpos( $head, "<\x00?\x00\n" ) !== false ) ||
  661. ( strpos( $head, "<\x00?\x00\t" ) !== false ) ||
  662. ( strpos( $head, "<\x00?\x00=" ) !== false )
  663. ) {
  664. $this->logger->info( __METHOD__ . ": recognized $file as application/x-php\n" );
  665. return 'application/x-php';
  666. }
  667. /**
  668. * look for XML formats (XHTML and SVG)
  669. */
  670. Wikimedia\suppressWarnings();
  671. $xml = new XmlTypeCheck( $file );
  672. Wikimedia\restoreWarnings();
  673. if ( $xml->wellFormed ) {
  674. $xmlTypes = $this->xmlTypes;
  675. return $xmlTypes[$xml->getRootElement()] ?? 'application/xml';
  676. }
  677. /**
  678. * look for shell scripts
  679. */
  680. $script_type = null;
  681. # detect by shebang
  682. if ( substr( $head, 0, 2 ) == "#!" ) {
  683. $script_type = "ASCII";
  684. } elseif ( substr( $head, 0, 5 ) == "\xef\xbb\xbf#!" ) {
  685. $script_type = "UTF-8";
  686. } elseif ( substr( $head, 0, 7 ) == "\xfe\xff\x00#\x00!" ) {
  687. $script_type = "UTF-16BE";
  688. } elseif ( substr( $head, 0, 7 ) == "\xff\xfe#\x00!" ) {
  689. $script_type = "UTF-16LE";
  690. }
  691. if ( $script_type ) {
  692. if ( $script_type !== "UTF-8" && $script_type !== "ASCII" ) {
  693. // Quick and dirty fold down to ASCII!
  694. $pack = [ 'UTF-16BE' => 'n*', 'UTF-16LE' => 'v*' ];
  695. $chars = unpack( $pack[$script_type], substr( $head, 2 ) );
  696. $head = '';
  697. foreach ( $chars as $codepoint ) {
  698. if ( $codepoint < 128 ) {
  699. $head .= chr( $codepoint );
  700. } else {
  701. $head .= '?';
  702. }
  703. }
  704. }
  705. $match = [];
  706. if ( preg_match( '%/?([^\s]+/)(\w+)%', $head, $match ) ) {
  707. $mime = "application/x-{$match[2]}";
  708. $this->logger->info( __METHOD__ . ": shell script recognized as $mime\n" );
  709. return $mime;
  710. }
  711. }
  712. // Check for ZIP variants (before getimagesize)
  713. $eocdrPos = strpos( $tail, "PK\x05\x06" );
  714. if ( $eocdrPos !== false && $eocdrPos <= strlen( $tail ) - 22 ) {
  715. $this->logger->info( __METHOD__ . ": ZIP signature present in $file\n" );
  716. // Check if it really is a ZIP file, make sure the EOCDR is at the end (T40432)
  717. $commentLength = unpack( "n", substr( $tail, $eocdrPos + 20 ) )[1];
  718. if ( $eocdrPos + 22 + $commentLength !== strlen( $tail ) ) {
  719. $this->logger->info( __METHOD__ . ": ZIP EOCDR not at end. Not a ZIP file." );
  720. } else {
  721. return $this->detectZipType( $head, $tail, $ext );
  722. }
  723. }
  724. // Check for STL (3D) files
  725. // @see https://en.wikipedia.org/wiki/STL_(file_format)
  726. if ( $fsize >= 15 &&
  727. stripos( $head, 'SOLID ' ) === 0 &&
  728. preg_match( '/\RENDSOLID .*$/i', $tail ) ) {
  729. // ASCII STL file
  730. return 'application/sla';
  731. } elseif ( $fsize > 84 ) {
  732. // binary STL file
  733. $triangles = substr( $head, 80, 4 );
  734. $triangles = unpack( 'V', $triangles );
  735. $triangles = reset( $triangles );
  736. if ( $triangles !== false && $fsize === 84 + ( $triangles * 50 ) ) {
  737. return 'application/sla';
  738. }
  739. }
  740. Wikimedia\suppressWarnings();
  741. $gis = getimagesize( $file );
  742. Wikimedia\restoreWarnings();
  743. if ( $gis && isset( $gis['mime'] ) ) {
  744. $mime = $gis['mime'];
  745. $this->logger->info( __METHOD__ . ": getimagesize detected $file as $mime\n" );
  746. return $mime;
  747. }
  748. # Media handling extensions can guess the MIME by content
  749. # It's intentionally here so that if core is wrong about a type (false positive),
  750. # people will hopefully nag and submit patches :)
  751. $mime = false;
  752. # Some strings by reference for performance - assuming well-behaved hooks
  753. $callback = $this->guessCallback;
  754. if ( $callback ) {
  755. $callback( $this, $head, $tail, $file, $mime /* by reference */ );
  756. }
  757. return $mime;
  758. }
  759. /**
  760. * Detect application-specific file type of a given ZIP file from its
  761. * header data. Currently works for OpenDocument and OpenXML types...
  762. * If can't tell, returns 'application/zip'.
  763. *
  764. * @param string $header Some reasonably-sized chunk of file header
  765. * @param string|null $tail The tail of the file
  766. * @param string|bool $ext The file extension, or true to extract it from the filename.
  767. * Set it to false (default) to ignore the extension. DEPRECATED! Set to false,
  768. * use improveTypeFromExtension($mime, $ext) later to improve MIME type.
  769. *
  770. * @return string
  771. */
  772. function detectZipType( $header, $tail = null, $ext = false ) {
  773. if ( $ext ) { # TODO: remove $ext param
  774. $this->logger->info( __METHOD__ .
  775. ": WARNING: use of the \$ext parameter is deprecated. " .
  776. "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
  777. }
  778. $mime = 'application/zip';
  779. $opendocTypes = [
  780. # In OASIS Open Document Format v1.2, Database front end document
  781. # has a recommended MIME type of:
  782. # application/vnd.oasis.opendocument.base
  783. # Despite the type registered at the IANA being 'database' which is
  784. # supposed to be normative.
  785. # T35515
  786. 'base',
  787. 'chart-template',
  788. 'chart',
  789. 'formula-template',
  790. 'formula',
  791. 'graphics-template',
  792. 'graphics',
  793. 'image-template',
  794. 'image',
  795. 'presentation-template',
  796. 'presentation',
  797. 'spreadsheet-template',
  798. 'spreadsheet',
  799. 'text-template',
  800. 'text-master',
  801. 'text-web',
  802. 'text' ];
  803. // The list of document types is available in OASIS Open Document
  804. // Format version 1.2 under Appendix C. It is not normative though,
  805. // supposedly types registered at the IANA should be.
  806. // http://docs.oasis-open.org/office/v1.2/os/OpenDocument-v1.2-os-part1.html
  807. $types = '(?:' . implode( '|', $opendocTypes ) . ')';
  808. $opendocRegex = "/^mimetype(application\/vnd\.oasis\.opendocument\.$types)/";
  809. $openxmlRegex = "/^\[Content_Types\].xml/";
  810. if ( preg_match( $opendocRegex, substr( $header, 30 ), $matches ) ) {
  811. $mime = $matches[1];
  812. $this->logger->info( __METHOD__ . ": detected $mime from ZIP archive\n" );
  813. } elseif ( preg_match( $openxmlRegex, substr( $header, 30 ) ) ) {
  814. $mime = "application/x-opc+zip";
  815. # TODO: remove the block below, as soon as improveTypeFromExtension is used everywhere
  816. if ( $ext !== true && $ext !== false ) {
  817. /** This is the mode used by getPropsFromPath
  818. * These MIME's are stored in the database, where we don't really want
  819. * x-opc+zip, because we use it only for internal purposes
  820. */
  821. if ( $this->isMatchingExtension( $ext, $mime ) ) {
  822. /* A known file extension for an OPC file,
  823. * find the proper mime type for that file extension
  824. */
  825. $mime = $this->guessTypesForExtension( $ext );
  826. } else {
  827. $mime = "application/zip";
  828. }
  829. }
  830. $this->logger->info( __METHOD__ .
  831. ": detected an Open Packaging Conventions archive: $mime\n" );
  832. } elseif ( substr( $header, 0, 8 ) == "\xd0\xcf\x11\xe0\xa1\xb1\x1a\xe1" &&
  833. ( $headerpos = strpos( $tail, "PK\x03\x04" ) ) !== false &&
  834. preg_match( $openxmlRegex, substr( $tail, $headerpos + 30 ) ) ) {
  835. if ( substr( $header, 512, 4 ) == "\xEC\xA5\xC1\x00" ) {
  836. $mime = "application/msword";
  837. }
  838. switch ( substr( $header, 512, 6 ) ) {
  839. case "\xEC\xA5\xC1\x00\x0E\x00":
  840. case "\xEC\xA5\xC1\x00\x1C\x00":
  841. case "\xEC\xA5\xC1\x00\x43\x00":
  842. $mime = "application/vnd.ms-powerpoint";
  843. break;
  844. case "\xFD\xFF\xFF\xFF\x10\x00":
  845. case "\xFD\xFF\xFF\xFF\x1F\x00":
  846. case "\xFD\xFF\xFF\xFF\x22\x00":
  847. case "\xFD\xFF\xFF\xFF\x23\x00":
  848. case "\xFD\xFF\xFF\xFF\x28\x00":
  849. case "\xFD\xFF\xFF\xFF\x29\x00":
  850. case "\xFD\xFF\xFF\xFF\x10\x02":
  851. case "\xFD\xFF\xFF\xFF\x1F\x02":
  852. case "\xFD\xFF\xFF\xFF\x22\x02":
  853. case "\xFD\xFF\xFF\xFF\x23\x02":
  854. case "\xFD\xFF\xFF\xFF\x28\x02":
  855. case "\xFD\xFF\xFF\xFF\x29\x02":
  856. $mime = "application/vnd.msexcel";
  857. break;
  858. }
  859. $this->logger->info( __METHOD__ .
  860. ": detected a MS Office document with OPC trailer\n" );
  861. } else {
  862. $this->logger->info( __METHOD__ . ": unable to identify type of ZIP archive\n" );
  863. }
  864. return $mime;
  865. }
  866. /**
  867. * Detect the type of a Microsoft Compound Binary a.k.a. OLE file.
  868. * These are old style pre-ODF files such as .doc and .xls
  869. *
  870. * @param resource $handle An opened seekable file handle
  871. * @return string The detected MIME type
  872. */
  873. function detectMicrosoftBinaryType( $handle ) {
  874. $info = MSCompoundFileReader::readHandle( $handle );
  875. if ( !$info['valid'] ) {
  876. $this->logger->info( __METHOD__ . ': invalid file format' );
  877. return 'unknown/unknown';
  878. }
  879. if ( !$info['mime'] ) {
  880. $this->logger->info( __METHOD__ . ": unrecognised document subtype" );
  881. return 'unknown/unknown';
  882. }
  883. return $info['mime'];
  884. }
  885. /**
  886. * Internal MIME type detection. Detection is done using the fileinfo
  887. * extension if it is available. It can be overriden by callback, which could
  888. * use an external program, for example. If detection fails and $ext is not false,
  889. * the MIME type is guessed from the file extension, using guessTypesForExtension.
  890. *
  891. * If the MIME type is still unknown, getimagesize is used to detect the
  892. * MIME type if the file is an image. If no MIME type can be determined,
  893. * this function returns 'unknown/unknown'.
  894. *
  895. * @param string $file The file to check
  896. * @param string|bool $ext The file extension, or true (default) to extract it from the filename.
  897. * Set it to false to ignore the extension. DEPRECATED! Set to false, use
  898. * improveTypeFromExtension($mime, $ext) later to improve MIME type.
  899. *
  900. * @return string The MIME type of $file
  901. */
  902. private function detectMimeType( $file, $ext = true ) {
  903. /** @todo Make $ext default to false. Or better, remove it. */
  904. if ( $ext ) {
  905. $this->logger->info( __METHOD__ .
  906. ": WARNING: use of the \$ext parameter is deprecated. "
  907. . "Use improveTypeFromExtension(\$mime, \$ext) instead.\n" );
  908. }
  909. $callback = $this->detectCallback;
  910. $m = null;
  911. if ( $callback ) {
  912. $m = $callback( $file );
  913. } else {
  914. $m = mime_content_type( $file );
  915. }
  916. if ( $m ) {
  917. # normalize
  918. $m = preg_replace( '![;, ].*$!', '', $m ); # strip charset, etc
  919. $m = trim( $m );
  920. $m = strtolower( $m );
  921. if ( strpos( $m, 'unknown' ) !== false ) {
  922. $m = null;
  923. } else {
  924. $this->logger->info( __METHOD__ . ": magic mime type of $file: $m\n" );
  925. return $m;
  926. }
  927. }
  928. // If desired, look at extension as a fallback.
  929. if ( $ext === true ) {
  930. $i = strrpos( $file, '.' );
  931. $ext = strtolower( $i ? substr( $file, $i + 1 ) : '' );
  932. }
  933. if ( $ext ) {
  934. if ( $this->isRecognizableExtension( $ext ) ) {
  935. $this->logger->info( __METHOD__ . ": refusing to guess mime type for .$ext file, "
  936. . "we should have recognized it\n" );
  937. } else {
  938. $m = $this->guessTypesForExtension( $ext );
  939. if ( $m ) {
  940. $this->logger->info( __METHOD__ . ": extension mime type of $file: $m\n" );
  941. return $m;
  942. }
  943. }
  944. }
  945. // Unknown type
  946. $this->logger->info( __METHOD__ . ": failed to guess mime type for $file!\n" );
  947. return 'unknown/unknown';
  948. }
  949. /**
  950. * Determine the media type code for a file, using its MIME type, name and
  951. * possibly its contents.
  952. *
  953. * This function relies on the findMediaType(), mapping extensions and MIME
  954. * types to media types.
  955. *
  956. * @todo analyse file if need be
  957. * @todo look at multiple extension, separately and together.
  958. *
  959. * @param string|null $path Full path to the image file, in case we have to look at the contents
  960. * (if null, only the MIME type is used to determine the media type code).
  961. * @param string|null $mime MIME type. If null it will be guessed using guessMimeType.
  962. *
  963. * @return string A value to be used with the MEDIATYPE_xxx constants.
  964. */
  965. function getMediaType( $path = null, $mime = null ) {
  966. if ( !$mime && !$path ) {
  967. return MEDIATYPE_UNKNOWN;
  968. }
  969. // If MIME type is unknown, guess it
  970. if ( !$mime ) {
  971. $mime = $this->guessMimeType( $path, false );
  972. }
  973. // Special code for ogg - detect if it's video (theora),
  974. // else label it as sound.
  975. if ( $mime == 'application/ogg' && is_string( $path ) && file_exists( $path ) ) {
  976. // Read a chunk of the file
  977. $f = fopen( $path, "rt" );
  978. if ( !$f ) {
  979. return MEDIATYPE_UNKNOWN;
  980. }
  981. $head = fread( $f, 256 );
  982. fclose( $f );
  983. $head = str_replace( 'ffmpeg2theora', '', strtolower( $head ) );
  984. // This is an UGLY HACK, file should be parsed correctly
  985. if ( strpos( $head, 'theora' ) !== false ) {
  986. return MEDIATYPE_VIDEO;
  987. } elseif ( strpos( $head, 'vorbis' ) !== false ) {
  988. return MEDIATYPE_AUDIO;
  989. } elseif ( strpos( $head, 'flac' ) !== false ) {
  990. return MEDIATYPE_AUDIO;
  991. } elseif ( strpos( $head, 'speex' ) !== false ) {
  992. return MEDIATYPE_AUDIO;
  993. } elseif ( strpos( $head, 'opus' ) !== false ) {
  994. return MEDIATYPE_AUDIO;
  995. } else {
  996. return MEDIATYPE_MULTIMEDIA;
  997. }
  998. }
  999. $type = null;
  1000. // Check for entry for full MIME type
  1001. if ( $mime ) {
  1002. $type = $this->findMediaType( $mime );
  1003. if ( $type !== MEDIATYPE_UNKNOWN ) {
  1004. return $type;
  1005. }
  1006. }
  1007. // Check for entry for file extension
  1008. if ( $path ) {
  1009. $i = strrpos( $path, '.' );
  1010. $e = strtolower( $i ? substr( $path, $i + 1 ) : '' );
  1011. // TODO: look at multi-extension if this fails, parse from full path
  1012. $type = $this->findMediaType( '.' . $e );
  1013. if ( $type !== MEDIATYPE_UNKNOWN ) {
  1014. return $type;
  1015. }
  1016. }
  1017. // Check major MIME type
  1018. if ( $mime ) {
  1019. $i = strpos( $mime, '/' );
  1020. if ( $i !== false ) {
  1021. $major = substr( $mime, 0, $i );
  1022. $type = $this->findMediaType( $major );
  1023. if ( $type !== MEDIATYPE_UNKNOWN ) {
  1024. return $type;
  1025. }
  1026. }
  1027. }
  1028. if ( !$type ) {
  1029. $type = MEDIATYPE_UNKNOWN;
  1030. }
  1031. return $type;
  1032. }
  1033. /**
  1034. * Returns a media code matching the given MIME type or file extension.
  1035. * File extensions are represented by a string starting with a dot (.) to
  1036. * distinguish them from MIME types.
  1037. *
  1038. * This function relies on the mapping defined by $this->mMediaTypes
  1039. * @private
  1040. * @param string $extMime
  1041. * @return int|string
  1042. */
  1043. function findMediaType( $extMime ) {
  1044. if ( strpos( $extMime, '.' ) === 0 ) {
  1045. // If it's an extension, look up the MIME types
  1046. $m = $this->getTypesForExtension( substr( $extMime, 1 ) );
  1047. if ( !$m ) {
  1048. return MEDIATYPE_UNKNOWN;
  1049. }
  1050. $m = explode( ' ', $m );
  1051. } else {
  1052. // Normalize MIME type
  1053. if ( isset( $this->mimeTypeAliases[$extMime] ) ) {
  1054. $extMime = $this->mimeTypeAliases[$extMime];
  1055. }
  1056. $m = [ $extMime ];
  1057. }
  1058. foreach ( $m as $mime ) {
  1059. foreach ( $this->mediaTypes as $type => $codes ) {
  1060. if ( in_array( $mime, $codes, true ) ) {
  1061. return $type;
  1062. }
  1063. }
  1064. }
  1065. return MEDIATYPE_UNKNOWN;
  1066. }
  1067. /**
  1068. * Returns an array of media types (MEDIATYPE_xxx constants)
  1069. *
  1070. * @return array
  1071. */
  1072. public function getMediaTypes() {
  1073. return array_keys( $this->mediaTypes );
  1074. }
  1075. /**
  1076. * Get the MIME types that various versions of Internet Explorer would
  1077. * detect from a chunk of the content.
  1078. *
  1079. * @param string $fileName The file name (unused at present)
  1080. * @param string $chunk The first 256 bytes of the file
  1081. * @param string $proposed The MIME type proposed by the server
  1082. * @return array
  1083. */
  1084. public function getIEMimeTypes( $fileName, $chunk, $proposed ) {
  1085. $ca = $this->getIEContentAnalyzer();
  1086. return $ca->getRealMimesFromData( $fileName, $chunk, $proposed );
  1087. }
  1088. /**
  1089. * Get a cached instance of IEContentAnalyzer
  1090. *
  1091. * @return IEContentAnalyzer
  1092. */
  1093. protected function getIEContentAnalyzer() {
  1094. if ( is_null( $this->IEAnalyzer ) ) {
  1095. $this->IEAnalyzer = new IEContentAnalyzer;
  1096. }
  1097. return $this->IEAnalyzer;
  1098. }
  1099. }