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)) {
91 include __DIR__ . '/commentform.phtml';
92 $html = ob_get_clean();
93 $article['content'] .= $html;
99 * Render our configuration page.
100 * Directly echo it out.
102 * @param string $args Preferences tab that is currently open
106 public function hook_prefs_tab($args)
108 if ($args != "prefPrefs") {
112 $accounts = PluginHost::getInstance()->get($this, 'accounts', []);
114 //FIXME: default identity
115 include __DIR__ . '/settings.phtml';
121 public function micropub($args)
123 //we do not get all arguments passed here, to we work around
124 $args = $GLOBALS['argv'];
125 array_shift($args);//update.php
126 array_shift($args);//--micropub
127 $mode = array_shift($args);
128 return $this->action($mode, $args);
133 * Also used by micropub() cli command method.
135 * /backend.php?op=pluginhandler&plugin=micropub&method=action
137 public function action($mode = null, $args = [])
139 if (isset($_POST['mode'])) {
140 $mode = $_POST['mode'];
141 } else if (isset($_GET['mode'])) {
142 $mode = $_GET['mode'];
145 if ($mode == 'authorize') {
146 return $this->authorizeAction($args);
147 } else if ($mode == 'authreturn') {
148 return $this->authreturnAction();
149 } else if ($mode == 'post') {
150 return $this->postAction();
152 return $this->errorOut('Unsupported mode');
156 protected function postAction()
158 if (!isset($_POST['me'])) {
159 return $this->errorOut('"me" parameter missing');
163 if (!isset($_POST['replyTo'])) {
164 return $this->errorOut('"replyTo" parameter missing');
166 $replyTo = $_POST['replyTo'];
168 if (!isset($_POST['content'])) {
169 return $this->errorOut('"content" parameter missing');
171 $content = $_POST['content'];
173 $accounts = PluginHost::getInstance()->get($this, 'accounts', []);
174 if (!isset($accounts[$me])) {
175 return $this->errorOut('"me" parameter invalid');
177 $account = $accounts[$me];
179 $links = $this->getLinks($me);
180 if (!count($links)) {
181 return $this->errorOut('No links found');
183 if (!isset($links['micropub'])) {
184 return $this->errorOut('No micropub endpoint found');
187 /* unfortunately fetch_file_contents() does not return headers
188 so we have to bring our own way to POST data */
192 'header' => 'Content-type: application/x-www-form-urlencoded',
193 'content' => http_build_query(
195 'access_token' => $account['access_token'],
197 'in-reply-to' => $replyTo,
198 'content' => $content,
201 'ignore_errors' => true,
205 $links['micropub'], 'r', false,
206 stream_context_create($opts)
208 $meta = stream_get_meta_data($stream);
209 $headers = $meta['wrapper_data'];
210 $content = stream_get_contents($stream);
212 //we hope there were no redirects and this is actually the only
213 // HTTP line in the headers
214 $status = array_shift($headers);
215 list($httpver, $code, $text) = explode(' ', $status, 3);
216 if ($code != 201 && $code != 202) {
217 return $this->errorOut(
219 . $code . ' ' . $text
224 foreach ($headers as $header) {
225 $parts = explode(':', $header, 2);
226 if (count($parts) == 2 && strtolower($parts[0]) == 'location') {
227 $location = trim($parts[1]);
230 if ($location === null) {
231 return $this->errorOut(
232 'Location header missing in successful creation response.'
236 header('Content-type: application/json');
239 'code' => intval($code),
240 'location' => $location,
241 'message' => 'Post created',
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') {