From 36d314e032757fc8d86f8f0daddc596e0e95ca8e Mon Sep 17 00:00:00 2001 From: Marc Alexander Date: Wed, 23 Oct 2013 18:34:35 +0200 Subject: [PATCH] [ticket/11912] Add phpbb mimetype guesser Mimetype guesser will be used as front-end file for mimetype guessing. PHPBB3-11912 --- phpBB/phpbb/mimetype/guesser.php | 105 +++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 phpBB/phpbb/mimetype/guesser.php diff --git a/phpBB/phpbb/mimetype/guesser.php b/phpBB/phpbb/mimetype/guesser.php new file mode 100644 index 0000000000..5ae094cd63 --- /dev/null +++ b/phpBB/phpbb/mimetype/guesser.php @@ -0,0 +1,105 @@ +register_guessers($mimetype_guessers); + } + + /** + * Register MimeTypeGuessers + * + * @param array $mimetype_guessers Mimetype guesser service collection + * + * @throws \LogicException If incorrect or not mimetype guessers have + * been supplied to class + */ + protected function register_guessers($mimetype_guessers) + { + foreach ($mimetype_guessers as $guesser) + { + $is_supported = (method_exists($guesser, 'is_supported')) ? 'is_supported' : ''; + $is_supported = (method_exists($guesser, 'isSupported')) ? 'isSupported' : $is_supported; + + if (empty($is_supported)) + { + throw new \LogicException('Incorrect mimetype guesser supplied.'); + } + + if ($guesser->$is_supported()) + { + $this->guessers[] = $guesser; + } + } + + if (empty($this->guessers)) + { + throw new \LogicException('No mimetype guesser supplied.'); + } + } + + /** + * Guess mimetype of supplied file + * + * @param string $file Path to file + * + * @return string Guess for mimetype of file + */ + public function guess($file) + { + if (!is_file($file)) + { + return false; + } + + if (!is_readable($file)) + { + return false; + } + + foreach ($this->guessers as $guesser) + { + $mimetype = $guesser->guess($file); + + // Try to guess something that is not the fallback application/octet-stream + if ($mimetype !== null && $mimetype !== 'application/octet-stream') + { + return $mimetype; + } + } + // Return any mimetype if we got a result or the fallback value + return (!empty($mimetype)) ? $mimetype : 'application/octet-stream'; + } +}