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()
47 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 = PluginHost::getInstance()->get($this, 'accounts', []);
87 if (!count($accounts)) {
91 $accountUrls = array_keys($accounts);
92 $defaultAccount = null;
93 foreach ($accounts as $url => $account) {
94 if ($account['default']) {
95 $defaultAccount = $url;
100 include __DIR__ . '/commentform.phtml';
101 $html = ob_get_clean();
102 $article['content'] .= $html;
108 * Render our configuration page.
109 * Directly echo it out.
111 * @param string $args Preferences tab that is currently open
115 public function hook_prefs_tab($args)
117 if ($args != "prefPrefs") {
121 $accounts = PluginHost::getInstance()->get($this, 'accounts', []);
122 if (isset($_REQUEST['accordion'])
123 && $_REQUEST['accordion'] == 'micropub'
125 $accordionActive = 'selected="true"';
127 $accordionActive = '';
130 foreach ($accounts as $url => $account) {
131 $accounts[$url]['checked'] = '';
132 if ($account['default']) {
133 $accounts[$url]['checked'] = 'checked="checked"';
137 //FIXME: default identity
138 include __DIR__ . '/settings.phtml';
141 public function get_prefs_js()
143 return file_get_contents(__DIR__ . '/settings.js');
149 public function micropub($args)
151 //we do not get all arguments passed here, to we work around
152 $args = $GLOBALS['argv'];
153 array_shift($args);//update.php
154 array_shift($args);//--micropub
155 $mode = array_shift($args);
156 return $this->action($mode, $args);
161 * Also used by micropub() cli command method.
163 * /backend.php?op=pluginhandler&plugin=micropub&method=action
165 public function action($mode = null, $args = [])
167 if (isset($_POST['mode'])) {
168 $mode = $_POST['mode'];
169 } else if (isset($_GET['mode'])) {
170 $mode = $_GET['mode'];
173 if ($mode == 'authorize') {
174 return $this->authorizeAction($args);
175 } else if ($mode == 'authreturn') {
176 return $this->authreturnAction();
177 } else if ($mode == 'post') {
178 return $this->postAction();
179 } else if ($mode == 'deleteIdentity') {
180 return $this->deleteIdentityAction();
181 } else if ($mode == 'setDefaultIdentity') {
182 return $this->setDefaultIdentityAction();
184 return $this->errorOut('Unsupported mode');
188 protected function postAction()
190 if (!isset($_POST['me'])) {
191 return $this->errorOut('"me" parameter missing');
193 $me = trim($_POST['me']);
195 if (!isset($_POST['replyTo'])) {
196 return $this->errorOut('"replyTo" parameter missing');
198 $replyTo = trim($_POST['replyTo']);
200 if (!isset($_POST['content'])) {
201 return $this->errorOut('"content" parameter missing');
203 $content = trim($_POST['content']);
205 $accounts = PluginHost::getInstance()->get($this, 'accounts', []);
206 if (!isset($accounts[$me])) {
207 return $this->errorOut('"me" parameter invalid');
209 $account = $accounts[$me];
211 $links = $this->getLinks($me);
212 if (!count($links)) {
213 return $this->errorOut('No links found');
215 if (!isset($links['micropub'])) {
216 return $this->errorOut('No micropub endpoint found');
219 /* unfortunately fetch_file_contents() does not return headers
220 so we have to bring our own way to POST data */
224 'header' => 'Content-type: application/x-www-form-urlencoded',
225 'content' => http_build_query(
227 'access_token' => $account['access_token'],
229 'in-reply-to' => $replyTo,
230 'content' => $content,
233 'ignore_errors' => true,
237 $links['micropub'], 'r', false,
238 stream_context_create($opts)
240 $meta = stream_get_meta_data($stream);
241 $headers = $meta['wrapper_data'];
242 $content = stream_get_contents($stream);
244 //we hope there were no redirects and this is actually the only
245 // HTTP line in the headers
246 $status = array_shift($headers);
247 list($httpver, $code, $text) = explode(' ', $status, 3);
248 if ($code != 201 && $code != 202) {
249 return $this->errorOut(
251 . $code . ' ' . $text
256 foreach ($headers as $header) {
257 $parts = explode(':', $header, 2);
258 if (count($parts) == 2 && strtolower($parts[0]) == 'location') {
259 $location = trim($parts[1]);
262 if ($location === null) {
263 return $this->errorOut(
264 'Location header missing in successful creation response.'
268 header('Content-type: application/json');
271 'code' => intval($code),
272 'location' => $location,
273 'message' => 'Post created',
279 protected function authorizeAction($args = [])
282 $url = array_shift($args);
283 } else if (isset($_POST['url'])) {
284 $url = $_POST['url'];
286 if (!filter_var($url, FILTER_VALIDATE_URL)) {
287 return $this->errorOut('Invalid URL');
290 //step 1: micropub discovery
291 $links = $this->getLinks($url);
293 if (!count($links)) {
294 return $this->errorOut('No links found');
296 if (!isset($links['micropub'])) {
297 return $this->errorOut('No micropub endpoint found');
299 if (!isset($links['token_endpoint'])) {
300 return $this->errorOut('No token endpoint found');
302 if (!isset($links['authorization_endpoint'])) {
303 return $this->errorOut('No authorization endpoint found');
306 $redirUrl = get_self_url_prefix() . '/backend.php'
307 . '?op=micropub&method=action&mode=authreturn';
308 $authUrl = $links['authorization_endpoint']
310 . '&redirect_uri=' . urlencode($redirUrl)
311 . '&client_id=' . urlencode(get_self_url_prefix())//FIXME: app info
312 //. '&state=' . 'FIXME'
314 . '&response_type=code';
315 header('Location: ' . $authUrl);
316 echo $authUrl . "\n";
321 * Return from authorization
323 public function authreturnAction()
325 if (!isset($_GET['me'])) {
326 return $this->errorOut('"me" parameter missing');
328 if (!isset($_GET['code'])) {
329 return $this->errorOut('"code" parameter missing');
332 $links = $this->getLinks($_GET['me']);
333 if (!isset($links['token_endpoint'])) {
334 return $this->errorOut('No token endpoint found');
337 //obtain access token from the code
338 $redirUrl = get_self_url_prefix() . '/backend.php'
339 . '?op=micropub&method=action&mode=authreturn';
340 $res = fetch_file_contents(
342 //FIXME: add accept header once this is fixed:
343 // https://discourse.tt-rss.org/t//207
344 'url' => $links['token_endpoint'],
346 'grant_type' => 'authorization_code',
348 'code' => $_GET['code'],
349 'redirect_uri' => $redirUrl,
350 'client_id' => get_self_url_prefix()
355 //we have no way to get the content type :/
356 if ($res{0} == '{') {
358 $data = json_decode($res);
360 parse_str($res, $data);
362 if (!isset($data['access_token'])) {
363 return $this->errorOut('access token missing');
365 if (!isset($data['me'])) {
366 return $this->errorOut('access token missing');
368 if (!isset($data['scope'])) {
369 return $this->errorOut('scope token missing');
372 $host = PluginHost::getInstance();
373 $accounts = $host->get($this, 'accounts', []);
374 $accounts[$data['me']] = [
375 'access_token' => $data['access_token'],
376 'scope' => $data['scope'],
378 $host->set($this, 'accounts', $accounts);
381 //the accordion parameter will never work
382 // because fox has serious mental problems
383 // https://discourse.tt-rss.org/t/open-a-certain-accordion-in-preferences-by-url-parameter/234
384 header('Location: prefs.php?accordion=micropub');
388 * Backend preferences action: Remove a given account
390 protected function deleteIdentityAction()
392 if (!isset($_POST['me'])) {
393 return $this->errorOut('"me" parameter missing');
395 $me = trim($_POST['me']);
397 $host = PluginHost::getInstance();
398 $accounts = $host->get($this, 'accounts', []);
399 if (!isset($accounts[$me])) {
400 return $this->errorOut('Unknown identity');
403 unset($accounts[$me]);
404 $host->set($this, 'accounts', $accounts);
405 header('Content-type: application/json');
410 'message' => 'Identity removed',
417 * Backend preferences action: Make a given account the default
419 protected function setDefaultIdentityAction()
421 if (!isset($_POST['me'])) {
422 return $this->errorOut('"me" parameter missing');
424 $me = trim($_POST['me']);
426 $host = PluginHost::getInstance();
427 $accounts = $host->get($this, 'accounts', []);
428 if (!isset($accounts[$me])) {
429 return $this->errorOut('Unknown identity');
432 foreach ($accounts as $url => $data) {
433 $accounts[$url]['default'] = ($url == $me);
435 $host->set($this, 'accounts', $accounts);
436 header('Content-type: application/json');
441 'message' => 'Default account set',
448 * Send an error message.
449 * Automatically in the correct format (plain text or json)
451 * @param string $msg Error message
455 protected function errorOut($msg)
457 header('HTTP/1.0 400 Bad Request');
459 //this does not take "q"uality values into account, I know.
460 if (isset($_SERVER['HTTP_ACCEPT'])
461 && strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false
464 header('Content-type: application/json');
471 header('Content-type: text/plain');
478 * Extract link relations from a given URL
480 protected function getLinks($url)
482 //FIXME: HTTP Link header support with HTTP2
483 $html = fetch_file_contents(
488 //Loading invalid HTML is tedious.
489 // quick hack with regex. yay!
490 preg_match_all('#<link[^>]+?>#', $html, $matches);
492 foreach ($matches[0] as $match) {
493 if (substr($match, -2) != '/>') {
494 //make it valid xml...
495 $match = substr($match, 0, -1) . '/>';
497 $sx = simplexml_load_string($match);
498 if (isset($sx['rel']) && isset($sx['href'])
499 && !isset($links[(string) $sx['rel']])
501 $links[(string) $sx['rel']] = (string) $sx['href'];
507 function csrf_ignore($method)
513 * Check which method is allowed via HTTP
515 function before($method)
517 if ($method == 'action') {