From 00bc7a00a00df2bb82407180d95cf4e3d628093c Mon Sep 17 00:00:00 2001 From: "J. King" Date: Fri, 29 Sep 2017 17:40:07 -0400 Subject: [PATCH] Transparently handle HEAD requests; fixes #114 --- lib/REST.php | 8 +++++++- lib/REST/Request.php | 5 +++++ lib/REST/Response.php | 26 +++++++++++++++++--------- 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/lib/REST.php b/lib/REST.php index 68f5e0ba..e1023761 100644 --- a/lib/REST.php +++ b/lib/REST.php @@ -39,7 +39,13 @@ class REST { $req->refreshURL(); $class = $this->apis[$api]['class']; $drv = new $class(); - return $drv->dispatch($req); + if ($req->head) { + $res = $drv->dispatch($req); + $res->head = true; + return $res; + } else { + return $drv->dispatch($req); + } } public function apiMatch(string $url, array $map): string { diff --git a/lib/REST/Request.php b/lib/REST/Request.php index bdd3a39f..2eda0477 100644 --- a/lib/REST/Request.php +++ b/lib/REST/Request.php @@ -4,6 +4,7 @@ namespace JKingWeb\Arsse\REST; class Request { public $method = "GET"; + public $head = false; public $url = ""; public $path =""; public $paths = []; @@ -26,6 +27,10 @@ class Request { $this->url = $url; $this->body = $body; $this->type = $contentType; + if($this->method=="HEAD") { + $this->head = true; + $this->method = "GET"; + } $this->refreshURL(); } diff --git a/lib/REST/Response.php b/lib/REST/Response.php index fc18723d..5323695c 100644 --- a/lib/REST/Response.php +++ b/lib/REST/Response.php @@ -9,6 +9,7 @@ class Response { const T_XML = "application/xml"; const T_TEXT = "text/plain"; + public $head = false; public $code; public $payload; public $type; @@ -24,15 +25,11 @@ class Response { public function output() { if (!headers_sent()) { - try { - $statusText = Arsse::$lang->msg("HTTP.Status.".$this->code); - } catch (\JKingWeb\Arsse\Lang\Exception $e) { - $statusText = ""; + foreach ($this->fields as $field) { + header($field); } - header("Status: ".$this->code." ".$statusText); $body = ""; if (!is_null($this->payload)) { - header("Content-Type: ".$this->type); switch ($this->type) { case self::T_JSON: $body = (string) json_encode($this->payload, \JSON_PRETTY_PRINT); @@ -42,10 +39,21 @@ class Response { break; } } - foreach ($this->fields as $field) { - header($field); + if (strlen($body)) { + header("Content-Type: ".$this->type); + header("Content-Length: ".strlen($body)); + } elseif ($this->code==200) { + $this->code = 204; + } + try { + $statusText = Arsse::$lang->msg("HTTP.Status.".$this->code); + } catch (\JKingWeb\Arsse\Lang\Exception $e) { + $statusText = ""; + } + header("Status: ".$this->code." ".$statusText); + if (!$this->head) { + echo $body; } - echo $body; } else { throw new REST\Exception("headersSent"); }