Add FixAcceptHeader middleware
authorTim Düsterhus <duesterhus@woltlab.com>
Thu, 13 Apr 2023 10:46:04 +0000 (12:46 +0200)
committerTim Düsterhus <duesterhus@woltlab.com>
Fri, 14 Apr 2023 11:54:48 +0000 (13:54 +0200)
wcfsetup/install/files/lib/http/middleware/FixAcceptHeader.class.php [new file with mode: 0644]
wcfsetup/install/files/lib/system/request/RequestHandler.class.php

diff --git a/wcfsetup/install/files/lib/http/middleware/FixAcceptHeader.class.php b/wcfsetup/install/files/lib/http/middleware/FixAcceptHeader.class.php
new file mode 100644 (file)
index 0000000..9fecb6e
--- /dev/null
@@ -0,0 +1,34 @@
+<?php
+
+namespace wcf\http\middleware;
+
+use Psr\Http\Message\ResponseInterface;
+use Psr\Http\Message\ServerRequestInterface;
+use Psr\Http\Server\MiddlewareInterface;
+use Psr\Http\Server\RequestHandlerInterface;
+use wcf\http\Helper;
+
+/**
+ * Adds a preference for application/json responses for AJAX requests that accept everything.
+ *
+ * @author  Tim Duesterhus
+ * @copyright   2001-2022 WoltLab GmbH
+ * @license GNU Lesser General Public License <http://opensource.org/licenses/lgpl-license.php>
+ * @since   6.0
+ */
+final class FixAcceptHeader implements MiddlewareInterface
+{
+    /**
+     * @inheritDoc
+     */
+    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
+    {
+        if (Helper::isAjaxRequest($request)) {
+            if (!$request->hasHeader('accept') || $request->getHeaderLine('accept') === '*/*') {
+                $request = $request->withHeader('accept', 'application/json, */*; q=0.9');
+            }
+        }
+
+        return $handler->handle($request);
+    }
+}
index d16a9ff4a4478d99a08d691058b8482249cc4bb9..0bcd31a915737fdda7c9bd50004abd6de6b278ad 100644 (file)
@@ -21,6 +21,7 @@ use wcf\http\middleware\EnforceAcpAuthentication;
 use wcf\http\middleware\EnforceCacheControlPrivate;
 use wcf\http\middleware\EnforceFrameOptions;
 use wcf\http\middleware\EnforceNoCacheForTemporaryRedirects;
+use wcf\http\middleware\FixAcceptHeader;
 use wcf\http\middleware\HandleExceptions;
 use wcf\http\middleware\HandleStartupErrors;
 use wcf\http\middleware\HandleValinorMappingErrors;
@@ -114,6 +115,7 @@ final class RequestHandler extends SingletonFactory
 
                 $pipeline = new Pipeline([
                     new HandleStartupErrors(),
+                    new FixAcceptHeader(),
                     new PreventMimeSniffing(),
                     new AddAcpSecurityHeaders(),
                     new EnforceCacheControlPrivate(),