Correctly inspect POST content type
[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     $storage = new Storage();
86     $lb      = new Linkback();
87     try {
88         $id = $storage->addComment($json, $userId);
89         $lb->ping($id);
90
91         header('HTTP/1.0 201 Created');
92         header('Location: ' . Urls::full(Urls::comment($id)));
93         exit();
94     } catch (\Exception $e) {
95         if ($e->getCode() == 400) {
96             mpError(
97                 'HTTP/1.0 400 Bad Request',
98                 'invalid_request',
99                 $e->getMessage()
100             );
101         }
102
103         mpError(
104             'HTTP/1.0 500 Internal Server Error',
105             'this_violates_the_spec',
106             $e->getMessage()
107         );
108         exit();
109     }
110 }
111
112 function getTokenFromHeader()
113 {
114     if (isset($_SERVER['HTTP_AUTHORIZATION'])) {
115         $auth = $_SERVER['HTTP_AUTHORIZATION'];
116     } else if (isset($_SERVER['REDIRECT_HTTP_AUTHORIZATION'])) {
117         //php-cgi has it there
118         $auth = $_SERVER['REDIRECT_HTTP_AUTHORIZATION'];
119     } else {
120         mpError(
121             'HTTP/1.0 403 Forbidden', 'forbidden',
122             'Authorization HTTP header missing'
123         );
124     }
125     list($bearer, $token) = explode(' ', $auth, 2);
126     if ($bearer !== 'Bearer') {
127         mpError(
128             'HTTP/1.0 403 Forbidden', 'forbidden',
129             'Authorization header must start with "Bearer"'
130         );
131     }
132     return trim($token);
133 }
134
135
136 if ($_SERVER['REQUEST_METHOD'] == 'GET') {
137     if (!isset($_GET['q'])) {
138         mpError(
139             'HTTP/1.1 400 Bad Request',
140             'invalid_request',
141             'Parameter "q" missing.'
142         );
143     } else if ($_GET['q'] === 'config') {
144         header('HTTP/1.0 200 OK');
145         header('Content-Type: application/json');
146         echo '{}';
147         exit();
148     } else if ($_GET['q'] === 'syndicate-to') {
149         header('HTTP/1.0 200 OK');
150         header('Content-Type: application/json');
151         echo '{}';
152         exit();
153     } else {
154         //FIXME: maybe implement $q=source
155         header('HTTP/1.1 501 Not Implemented');
156         header('Content-Type: text/plain');
157         echo 'Unsupported "q" value: ' . $_GET['q'] . "\n";
158         exit();
159     }
160 } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
161     if (!isset($_SERVER['CONTENT_TYPE'])) {
162         mpError(
163             'HTTP/1.1 400 Bad Request',
164             'invalid_request',
165             'Content-Type header missing.'
166         );
167     }
168     list($ctype) = explode(';', $_SERVER['CONTENT_TYPE'], 2);
169     $ctype = trim($ctype);
170     if ($ctype == 'application/x-www-form-urlencoded') {
171         if (!isset($_POST['action'])) {
172             $_POST['action'] = 'create';
173         }
174         if ($_POST['action'] != 'create') {
175             header('HTTP/1.1 501 Not Implemented');
176             header('Content-Type: text/plain');
177             echo "Creation of posts supported only\n";
178             exit();
179         }
180
181         $data = $_POST;
182         $base = (object) [
183             'type' => ['h-entry'],
184         ];
185         if (isset($data['h'])) {
186             $base->type = ['h-' . $data['h']];
187             unset($data['h']);
188         }
189         if (isset($data['access_token'])) {
190             $token = $data['access_token'];
191             unset($data['access_token']);
192         } else {
193             $token = getTokenFromHeader();
194         }
195         //reserved properties
196         foreach (['q', 'url', 'action'] as $key) {
197             if (isset($data[$key])) {
198                 $base->$key = $data[$key];
199                 unset($data[$key]);
200             }
201         }
202         //"mp-" reserved for future use
203         foreach ($data as $key => $value) {
204             if (substr($key, 0, 3) == 'mp-') {
205                 $base->$key = $value;
206                 unset($data[$key]);
207             } else if (!is_array($value)) {
208                 //convert to array
209                 $data[$key] = [$value];
210             }
211         }
212         $json = $base;
213         $json->properties = (object) $data;
214         handleCreate($json, $token);
215     } else if ($ctype == 'application/json') {
216         $input = file_get_contents('php://input');
217         $json  = json_decode($input);
218         if ($json === null) {
219             mpError(
220                 'HTTP/1.1 400 Bad Request',
221                 'invalid_request',
222                 'Invalid JSON'
223             );
224         }
225         $token = getTokenFromHeader();
226         handleCreate($json, $token);
227     } else {
228         mpError(
229             'HTTP/1.1 400 Bad Request',
230             'invalid_request',
231             'Unsupported POST content type'
232         );
233     }
234 } else {
235     mpError(
236         'HTTP/1.0 400 Bad Request',
237         'invalid_request',
238         'Unsupported HTTP request method'
239     );
240 }
241 ?>