3 * Simple Micropub client to post reponses
7 * @author Christian Weiske <cweiske@cweiske.de>
8 * @license AGPLv3 or later
9 * @link https://www.w3.org/TR/micropub/
11 class Micropub extends Plugin implements IHandler
14 * Dumb workaround for "private $host" in Plugin class
15 * + the re-creation of the plugin instance without calling init().
18 * @see https://discourse.tt-rss.org/t//208
19 * @see https://discourse.tt-rss.org/t//209
21 protected static $myhost;
23 public function __construct()
25 //do nothing. only here to not have micropub() called as constructor
28 public function about()
38 public function api_version()
46 public function init(/*PluginHost*/ $host)
49 static::$myhost = $host;
50 $host->add_hook($host::HOOK_PREFS_TAB, $this);
51 $host->add_hook($host::HOOK_RENDER_ARTICLE, $this);
52 //command line option --micropub
54 'micropub', 'Add Micropub identity', $this, ':', 'MODE'
59 * @param array $article Article data. Keys:
72 * - always_display_enclosures
80 public function hook_render_article($article)
82 $quillUrl = 'https://quill.p3k.io/new'
83 . '?reply=' . urlencode($article['link']);
84 // did I tell you I hate dojo/dijit?
86 $accounts = array_keys(PluginHost::getInstance()->get($this, 'accounts', []));
87 if (!count($accounts)) {
90 array_shift($accounts);
92 include __DIR__ . '/commentform.phtml';
93 $html = ob_get_clean();
94 $article['content'] .= $html;
100 * Render our configuration page.
101 * Directly echo it out.
103 * @param string $args Preferences tab that is currently open
107 public function hook_prefs_tab($args)
109 if ($args != "prefPrefs") {
113 $accounts = PluginHost::getInstance()->get($this, 'accounts', []);
115 //FIXME: default identity
116 include __DIR__ . '/settings.phtml';
122 public function micropub($args)
124 //we do not get all arguments passed here, to we work around
125 $args = $GLOBALS['argv'];
126 array_shift($args);//update.php
127 array_shift($args);//--micropub
128 $mode = array_shift($args);
129 return $this->action($mode, $args);
134 * Also used by micropub() cli command method.
136 * /backend.php?op=pluginhandler&plugin=micropub&method=action
138 public function action($mode = null, $args = [])
140 if (isset($_POST['mode'])) {
141 $mode = $_POST['mode'];
142 } else if (isset($_GET['mode'])) {
143 $mode = $_GET['mode'];
146 if ($mode == 'authorize') {
147 return $this->authorizeAction($args);
148 } else if ($mode == 'authreturn') {
149 return $this->authreturnAction();
150 } else if ($mode == 'post') {
151 return $this->postAction();
153 return $this->errorOut('Unsupported mode');
157 protected function postAction()
159 if (!isset($_POST['me'])) {
160 return $this->errorOut('"me" parameter missing');
164 if (!isset($_POST['replyTo'])) {
165 return $this->errorOut('"replyTo" parameter missing');
167 $replyTo = $_POST['replyTo'];
169 if (!isset($_POST['content'])) {
170 return $this->errorOut('"content" parameter missing');
172 $content = $_POST['content'];
174 $accounts = PluginHost::getInstance()->get($this, 'accounts', []);
175 if (!isset($accounts[$me])) {
176 return $this->errorOut('"me" parameter invalid');
178 $account = $accounts[$me];
180 $links = $this->getLinks($me);
181 if (!count($links)) {
182 return $this->errorOut('No links found');
184 if (!isset($links['micropub'])) {
185 return $this->errorOut('No micropub endpoint found');
188 /* unfortunately fetch_file_contents() does not return headers
189 so we have to bring our own way to POST data */
193 'header' => 'Content-type: application/x-www-form-urlencoded',
194 'content' => http_build_query(
196 'access_token' => $account['access_token'],
198 'in-reply-to' => $replyTo,
199 'content' => $content,
202 'ignore_errors' => true,
206 $links['micropub'], 'r', false,
207 stream_context_create($opts)
209 $meta = stream_get_meta_data($stream);
210 $headers = $meta['wrapper_data'];
211 $content = stream_get_contents($stream);
213 //we hope there were no redirects and this is actually the only
214 // HTTP line in the headers
215 $status = array_shift($headers);
216 list($httpver, $code, $text) = explode(' ', $status, 3);
217 if ($code != 201 && $code != 202) {
218 return $this->errorOut(
220 . $code . ' ' . $text
225 foreach ($headers as $header) {
226 $parts = explode(':', $header, 2);
227 if (count($parts) == 2 && strtolower($parts[0]) == 'location') {
228 $location = trim($parts[1]);
231 if ($location === null) {
232 return $this->errorOut(
233 'Location header missing in successful creation response.'
237 header('Content-type: application/json');
240 'code' => intval($code),
241 'location' => $location,
247 protected function authorizeAction($args = [])
250 $url = array_shift($args);
251 } else if (isset($_POST['url'])) {
252 $url = $_POST['url'];
254 if (!filter_var($url, FILTER_VALIDATE_URL)) {
255 return $this->errorOut('Invalid URL');
258 //step 1: micropub discovery
259 $links = $this->getLinks($url);
261 if (!count($links)) {
262 return $this->errorOut('No links found');
264 if (!isset($links['micropub'])) {
265 return $this->errorOut('No micropub endpoint found');
267 if (!isset($links['token_endpoint'])) {
268 return $this->errorOut('No token endpoint found');
270 if (!isset($links['authorization_endpoint'])) {
271 return $this->errorOut('No authorization endpoint found');
274 $redirUrl = get_self_url_prefix() . '/backend.php'
275 . '?op=micropub&method=action&mode=authreturn';
276 $authUrl = $links['authorization_endpoint']
278 . '&redirect_uri=' . urlencode($redirUrl)
279 . '&client_id=' . urlencode(get_self_url_prefix())//FIXME: app info
280 //. '&state=' . 'FIXME'
282 . '&response_type=code';
283 header('Location: ' . $authUrl);
284 echo $authUrl . "\n";
289 * Return from authorization
291 public function authreturnAction()
293 if (!isset($_GET['me'])) {
294 return $this->errorOut('"me" parameter missing');
296 if (!isset($_GET['code'])) {
297 return $this->errorOut('"code" parameter missing');
300 $links = $this->getLinks($_GET['me']);
301 if (!isset($links['token_endpoint'])) {
302 return $this->errorOut('No token endpoint found');
305 //obtain access token from the code
306 $redirUrl = get_self_url_prefix() . '/backend.php'
307 . '?op=micropub&method=action&mode=authreturn';
308 $res = fetch_file_contents(
310 //FIXME: add accept header once this is fixed:
311 // https://discourse.tt-rss.org/t//207
312 'url' => $links['token_endpoint'],
314 'grant_type' => 'authorization_code',
316 'code' => $_GET['code'],
317 'redirect_uri' => $redirUrl,
318 'client_id' => get_self_url_prefix()
323 //we have no way to get the content type :/
324 if ($res{0} == '{') {
326 $data = json_decode($res);
328 parse_str($res, $data);
330 if (!isset($data['access_token'])) {
331 return $this->errorOut('access token missing');
333 if (!isset($data['me'])) {
334 return $this->errorOut('access token missing');
336 if (!isset($data['scope'])) {
337 return $this->errorOut('scope token missing');
340 $host = PluginHost::getInstance();
341 $accounts = $host->get($this, 'accounts', []);
342 $accounts[$data['me']] = [
343 'access_token' => $data['access_token'],
344 'scope' => $data['scope'],
346 $host->set($this, 'accounts', $accounts);
349 header('Location: prefs.php');
353 * Send an error message.
354 * Automatically in the correct format (plain text or json)
356 * @param string $msg Error message
360 protected function errorOut($msg)
362 header('HTTP/1.0 400 Bad Request');
364 //this does not take "q"uality values into account, I know.
365 if (isset($_SERVER['HTTP_ACCEPT'])
366 && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false
369 header('Content-type: application/json');
376 header('Content-type: text/plain');
383 * Extract link relations from a given URL
385 protected function getLinks($url)
387 //FIXME: HTTP Link header support with HTTP2
388 $html = fetch_file_contents(
393 //Loading invalid HTML is tedious.
394 // quick hack with regex. yay!
395 preg_match_all('#<link[^>]+?>#', $html, $matches);
397 foreach ($matches[0] as $match) {
398 if (substr($match, -2) != '/>') {
399 //make it valid xml...
400 $match = substr($match, 0, -1) . '/>';
402 $sx = simplexml_load_string($match);
403 if (isset($sx['rel']) && isset($sx['href'])
404 && !isset($links[(string) $sx['rel']])
406 $links[(string) $sx['rel']] = (string) $sx['href'];
412 function csrf_ignore($method)
418 * Check which method is allowed via HTTP
420 function before($method)
422 if ($method == 'action') {