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