b76d997f609285ed867188f220407692d66f2ae9
[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     $ctype = $_SERVER['CONTENT_TYPE'];
169     if ($ctype == 'application/x-www-form-urlencoded') {
170         if (!isset($_POST['action'])) {
171             $_POST['action'] = 'create';
172         }
173         if ($_POST['action'] != 'create') {
174             header('HTTP/1.1 501 Not Implemented');
175             header('Content-Type: text/plain');
176             echo "Creation of posts supported only\n";
177             exit();
178         }
179
180         $data = $_POST;
181         $base = (object) [
182             'type' => ['h-entry'],
183         ];
184         if (isset($data['h'])) {
185             $base->type = ['h-' . $data['h']];
186             unset($data['h']);
187         }
188         if (isset($data['access_token'])) {
189             $token = $data['access_token'];
190             unset($data['access_token']);
191         } else {
192             $token = getTokenFromHeader();
193         }
194         //reserved properties
195         foreach (['q', 'url', 'action'] as $key) {
196             if (isset($data[$key])) {
197                 $base->$key = $data[$key];
198                 unset($data[$key]);
199             }
200         }
201         //"mp-" reserved for future use
202         foreach ($data as $key => $value) {
203             if (substr($key, 0, 3) == 'mp-') {
204                 $base->$key = $value;
205                 unset($data[$key]);
206             } else if (!is_array($value)) {
207                 //convert to array
208                 $data[$key] = [$value];
209             }
210         }
211         $json = $base;
212         $json->properties = (object) $data;
213         handleCreate($json, $token);
214     } else if ($ctype == 'application/json') {
215         $input = file_get_contents('php://input');
216         $json  = json_decode($input);
217         if ($json === null) {
218             mpError(
219                 'HTTP/1.1 400 Bad Request',
220                 'invalid_request',
221                 'Invalid JSON'
222             );
223         }
224         $token = getTokenFromHeader();
225         handleCreate($json, $token);
226     } else {
227         mpError(
228             'HTTP/1.1 400 Bad Request',
229             'invalid_request',
230             'Unsupported POST content type'
231         );
232     }
233 } else {
234     mpError(
235         'HTTP/1.0 400 Bad Request',
236         'invalid_request',
237         'Unsupported HTTP request method'
238     );
239 }
240 ?>