fetch token verification error response
[anoweco.git] / www / micropub.php
1 <?php
2 namespace anoweco;
3 /**
4  * Micropub endpoint that stores comments in the database
5  *
6  * @author Christian Weiske <cweiske@cweiske.de>
7  */
8 header('HTTP/1.0 500 Internal Server Error');
9 require 'www-header.php';
10
11 /**
12  * Send out a micropub error
13  *
14  * @param string $status      HTTP status code line
15  * @param string $code        One of the allowed status types:
16  *                            - forbidden
17  *                            - insufficient_scope
18  *                            - invalid_request
19  *                            - not_found
20  * @param string $description
21  */
22 function mpError($status, $code, $description)
23 {
24     header($status);
25     header('Content-Type: application/json');
26     echo json_encode(
27         ['error' => $code, 'error_description' => $description]
28     ) . "\n";
29     exit(1);
30 }
31
32 function validateToken($token)
33 {
34     $ctx = stream_context_create(
35         array(
36             'http' => array(
37                 'header' => array(
38                     'Authorization: Bearer ' . $token
39                 ),
40                 'ignore_errors' => true,
41             ),
42         )
43     );
44     //FIXME: make hard-coded token server URL configurable
45     $res = @file_get_contents(Urls::full('/token.php'), false, $ctx);
46     list($dummy, $code, $msg) = explode(' ', $http_response_header[0]);
47     if ($code != 200) {
48         mpError(
49             'HTTP/1.0 403 Forbidden',
50             'forbidden',
51             'Error verifying bearer token: ' . trim($res)
52         );
53     }
54
55     parse_str($res, $data);
56     //FIXME: they spit out non-micropub json error responess
57     verifyUrlParameter($data, 'me');
58     verifyUrlParameter($data, 'client_id');
59     verifyParameter($data, 'scope');
60
61     return [$data['me'], $data['client_id'], $data['scope']];
62 }
63
64 function handleCreate($json, $token)
65 {
66     list($me, $client_id, $scope) = validateToken($token);
67     $userId = Urls::userId($me);
68     if ($userId === null) {
69         mpError(
70             'HTTP/1.0 403 Forbidden',
71             'forbidden',
72             'Invalid user URL'
73         );
74     }
75     $storage = new Storage();
76     $rowUser = $storage->getUser($userId);
77     if ($rowUser === null) {
78         mpError(
79             'HTTP/1.0 403 Forbidden',
80             'forbidden',
81             'User not found: ' . $userId
82         );
83     }
84
85     if (!isset($json->properties->{'in-reply-to'})) {
86         mpError(
87             'HTTP/1.0 400 Bad Request',
88             'invalid_request',
89             'Only replies accepted'
90         );
91     }
92
93     $storage = new Storage();
94     try {
95         $id = $storage->addComment($json, $userId);
96
97         header('HTTP/1.0 201 Created');
98         header('Location: ' . Urls::full(Urls::comment($id)));
99         exit();
100     } catch (\Exception $e) {
101         //FIXME: return correct status code
102         header('HTTP/1.0 500 Internal Server Error');
103         exit();
104     }
105 }
106
107 function getTokenFromHeader()
108 {
109     if (!isset($_SERVER['HTTP_AUTHORIZATION'])) {
110         mpError(
111             'HTTP/1.0 403 Forbidden', 'forbidden',
112             'Authorization HTTP header missing'
113         );
114     }
115     list($bearer, $token) = explode(' ', $_SERVER['HTTP_AUTHORIZATION'], 2);
116     if ($bearer !== 'Bearer') {
117         mpError(
118             'HTTP/1.0 403 Forbidden', 'forbidden',
119             'Authorization header must start with "Bearer"'
120         );
121     }
122     return trim($token);
123 }
124
125
126 if ($_SERVER['REQUEST_METHOD'] == 'GET') {
127     if (!isset($_GET['q'])) {
128         mpError(
129             'HTTP/1.1 400 Bad Request',
130             'invalid_request',
131             'Parameter "q" missing.'
132         );
133     } else if ($_GET['q'] === 'config') {
134         header('HTTP/1.0 200 OK');
135         header('Content-Type: application/json');
136         echo '{}';
137         exit();
138     } else if ($_GET['q'] === 'syndicate-to') {
139         header('HTTP/1.0 200 OK');
140         header('Content-Type: application/json');
141         echo '{}';
142         exit();
143     } else {
144         //FIXME: maybe implement $q=source
145         header('HTTP/1.1 501 Not Implemented');
146         header('Content-Type: text/plain');
147         echo 'Unsupported "q" value: ' . $_GET['q'] . "\n";
148         exit();
149     }
150 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
151     if (!isset($_SERVER['CONTENT_TYPE'])) {
152         mpError(
153             'HTTP/1.1 400 Bad Request',
154             'invalid_request',
155             'Content-Type header missing.'
156         );
157     }
158     $ctype = $_SERVER['CONTENT_TYPE'];
159     if ($ctype == 'application/x-www-form-urlencoded') {
160         if (!isset($_POST['action'])) {
161             $_POST['action'] = 'create';
162         }
163         if ($_POST['action'] != 'create') {
164             header('HTTP/1.1 501 Not Implemented');
165             header('Content-Type: text/plain');
166             echo "Creation of posts supported only\n";
167             exit();
168         }
169
170         $data = $_POST;
171         $base = (object) [
172             'type' => ['h-entry'],
173         ];
174         if (isset($data['h'])) {
175             $base->type = ['h-' . $data['h']];
176             unset($data['h']);
177         }
178         if (isset($data['access_token'])) {
179             $token = $data['access_token'];
180             unset($data['access_token']);
181         } else {
182             $token = getTokenFromHeader();
183         }
184         //reserved properties
185         foreach (['q', 'url', 'action'] as $key) {
186             if (isset($data[$key])) {
187                 $base->$key = $data[$key];
188                 unset($data[$key]);
189             }
190         }
191         //"mp-" reserved for future use
192         foreach ($data as $key => $value) {
193             if (substr($key, 0, 3) == 'mp-') {
194                 $base->$key = $value;
195                 unset($data[$key]);
196             } else if (!is_array($value)) {
197                 //convert to array
198                 $data[$key] = [$value];
199             }
200         }
201         $json = $base;
202         $json->properties = (object) $data;
203         handleCreate($json, $token);
204     } else if ($ctype == 'application/javascript') {
205         $input = file_get_contents('php://stdin');
206         $json  = json_decode($input);
207         if ($json === null) {
208             mpError(
209                 'HTTP/1.1 400 Bad Request',
210                 'invalid_request',
211                 'Invalid JSON'
212             );
213         }
214         $token = getTokenFromHeader();
215         handleCreate($json, $token);
216     } else {
217         mpError(
218             'HTTP/1.1 400 Bad Request',
219             'invalid_request',
220             'Unsupported POST content type'
221         );
222     }
223 } else {
224     mpError(
225         'HTTP/1.0 400 Bad Request',
226         'invalid_request',
227         'Unsupported HTTP request method'
228     );
229 }
230 ?>