From ed7763c37928f76ca68a9151e808ebcb28597880 Mon Sep 17 00:00:00 2001 From: Johannes Meyer Date: Thu, 12 Nov 2020 09:31:58 +0100 Subject: [PATCH] Introduce class `Icinga\Web\Controller\StaticController` --- .../Web/Controller/StaticController.php | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 library/Icinga/Web/Controller/StaticController.php diff --git a/library/Icinga/Web/Controller/StaticController.php b/library/Icinga/Web/Controller/StaticController.php new file mode 100644 index 000000000..7c06dfedb --- /dev/null +++ b/library/Icinga/Web/Controller/StaticController.php @@ -0,0 +1,77 @@ +getRequestUri(), strlen($request->getBaseUrl()) + 4), '/'); + + $library = null; + foreach ($app->getLibraries() as $candidate) { + if (substr($assetPath, 0, strlen($candidate->getName())) === $candidate->getName()) { + $library = $candidate; + $assetPath = ltrim(substr($assetPath, strlen($candidate->getName())), '/'); + break; + } + } + + if ($library === null) { + $app->getResponse() + ->setHttpResponseCode(404); + + return; + } + + $assetRoot = $library->getStaticAssetPath(); + $filePath = $assetRoot . DIRECTORY_SEPARATOR . $assetPath; + + // Doesn't use realpath as it isn't supposed to access files outside asset/static + if (! is_readable($filePath) || ! is_file($filePath)) { + $app->getResponse() + ->setHttpResponseCode(404); + + return; + } + + $fileStat = stat($filePath); + $eTag = sprintf( + '%x-%x-%x', + $fileStat['ino'], + $fileStat['size'], + (float) str_pad($fileStat['mtime'], 16, '0') + ); + + $app->getResponse()->setHeader( + 'Cache-Control', + 'public, max-age=1814400, stale-while-revalidate=604800', + true + ); + + if ($request->getServer('HTTP_IF_NONE_MATCH') === $eTag) { + $app->getResponse() + ->setHttpResponseCode(304); + } else { + $app->getResponse() + ->setHeader('ETag', $eTag) + ->setHeader('Content-Type', mime_content_type($filePath), true) + ->setHeader('Last-Modified', gmdate('D, d M Y H:i:s', $fileStat['mtime']) . ' GMT') + ->setBody(file_get_contents($filePath)); + } + } +}