summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDavid T. Sadler <davidtsadler@googlemail.com>2021-07-01 21:32:48 +0100
committerDavid T. Sadler <davidtsadler@googlemail.com>2021-07-01 21:32:48 +0100
commit576160b4d38d28fc5aa70fa5c03d38712dc8ac17 (patch)
treea5bce82d34f9523f869a1d454092e386bfb3d0d0
parent69b8f357a07bbb312111202e28e3e7a990f78e77 (diff)
Implement simple add bookmark API
-rw-r--r--.gitignore1
-rw-r--r--public/bookmarks/index.php47
2 files changed, 48 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..4f4773f
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1 @@
+config.php
diff --git a/public/bookmarks/index.php b/public/bookmarks/index.php
new file mode 100644
index 0000000..8ecfe24
--- /dev/null
+++ b/public/bookmarks/index.php
@@ -0,0 +1,47 @@
+<?php declare(strict_types=1);
+
+error_reporting(E_ALL);
+
+$config = require_once('../../config.php');
+
+if ('POST' !== ($_SERVER['REQUEST_METHOD'] ?? null)) {
+ respondAndExit([405 => 'Method Not Allowed']);
+}
+
+if ('Bearer '.$config['bearer_token'] !== ($_SERVER['HTTP_AUTHORIZATION'] ?? null)) {
+ respondAndExit([
+ 401 => 'Unauthorized',
+ 0 => 'WWW-Authenticate: Bearer realm="Bookmarks"',
+ ]);
+}
+
+if ('application/x-www-form-urlencoded' !== ($_SERVER['CONTENT_TYPE'] ?? null)) {
+ respondAndExit([415 => 'Unsupported Media Type']);
+}
+
+$url = filter_input(INPUT_POST, 'url', FILTER_VALIDATE_URL);
+
+if (!$url || !strlen($url) === 0 || strlen($url) > $config['max_url_length']) {
+ respondAndExit([400 => 'Bad Request']);
+}
+
+if (!file_put_contents($config['path_to_file'], "$url\n", FILE_APPEND)) {
+ respondAndExit([500 => 'Internal Server Error']);
+}
+
+respondAndExit([201 => 'Created']);
+
+function respondAndExit(array $headers): void
+{
+ foreach ($headers as $responseCode => $header) {
+ if ($responseCode) {
+ header($header, false, $responseCode);
+ } else {
+ header($header);
+ }
+ }
+
+ header('Content-type: text/plain; charset=UTF-8');
+
+ exit();
+}