Show micropub error descriptions
[tt-rss-micropub.git] / init.php
index 4c0f598aae9b061ba1bf9a48d3b1a19b821645ac..d561aa5421b561d2fe81269786625afdfb2bcf24 100644 (file)
--- a/init.php
+++ b/init.php
@@ -83,10 +83,19 @@ class Micropub extends Plugin implements IHandler
             . '?reply=' . urlencode($article['link']);
         // did I tell you I hate dojo/dijit?
 
             . '?reply=' . urlencode($article['link']);
         // did I tell you I hate dojo/dijit?
 
-        $accounts = array_keys(PluginHost::getInstance()->get($this, 'accounts', []));
+        $accounts = PluginHost::getInstance()->get($this, 'accounts', []);
         if (!count($accounts)) {
             return $article;
         }
         if (!count($accounts)) {
             return $article;
         }
+
+        $accountUrls = array_keys($accounts);
+        $defaultAccount = null;
+        foreach ($accounts as $url => $account) {
+            if ($account['default']) {
+                $defaultAccount = $url;
+            }
+        }
+
         ob_start();
         include __DIR__ . '/commentform.phtml';
         $html = ob_get_clean();
         ob_start();
         include __DIR__ . '/commentform.phtml';
         $html = ob_get_clean();
@@ -118,6 +127,13 @@ class Micropub extends Plugin implements IHandler
             $accordionActive = '';
         }
 
             $accordionActive = '';
         }
 
+        foreach ($accounts as $url => $account) {
+            $accounts[$url]['checked'] = '';
+            if ($account['default']) {
+                $accounts[$url]['checked'] = 'checked="checked"';
+            }
+        }
+
         //FIXME: default identity
         include __DIR__ . '/settings.phtml';
     }
         //FIXME: default identity
         include __DIR__ . '/settings.phtml';
     }
@@ -162,34 +178,52 @@ class Micropub extends Plugin implements IHandler
             return $this->postAction();
         } else if ($mode == 'deleteIdentity') {
             return $this->deleteIdentityAction();
             return $this->postAction();
         } else if ($mode == 'deleteIdentity') {
             return $this->deleteIdentityAction();
+        } else if ($mode == 'setDefaultIdentity') {
+            return $this->setDefaultIdentityAction();
         } else {
             return $this->errorOut('Unsupported mode');
         }
     }
 
         } else {
             return $this->errorOut('Unsupported mode');
         }
     }
 
+    /**
+     * Post a comment, like or bookmark via micropub
+     */
     protected function postAction()
     {
     protected function postAction()
     {
-        if (!isset($_POST['me'])) {
-            return $this->errorOut('"me" parameter missing');
+        $action = 'comment';
+        if (isset($_POST['action'])) {
+            $action = trim($_POST['action']);
         }
         }
-        $me = trim($_POST['me']);
-
-        if (!isset($_POST['replyTo'])) {
-            return $this->errorOut('"replyTo" parameter missing');
+        if (array_search($action, ['bookmark', 'comment', 'like']) === false) {
+            return $this->errorOut('"action" parameter invalid');
         }
         }
-        $replyTo = trim($_POST['replyTo']);
 
 
-        if (!isset($_POST['content'])) {
-            return $this->errorOut('"content" parameter missing');
+        if (!isset($_POST['me'])) {
+            return $this->errorOut('"me" parameter missing');
         }
         }
-        $content = trim($_POST['content']);
-
+        $me = trim($_POST['me']);
         $accounts = PluginHost::getInstance()->get($this, 'accounts', []);
         if (!isset($accounts[$me])) {
             return $this->errorOut('"me" parameter invalid');
         }
         $account = $accounts[$me];
 
         $accounts = PluginHost::getInstance()->get($this, 'accounts', []);
         if (!isset($accounts[$me])) {
             return $this->errorOut('"me" parameter invalid');
         }
         $account = $accounts[$me];
 
+        if (!isset($_POST['postUrl'])) {
+            return $this->errorOut('"postUrl" parameter missing');
+        }
+        $postUrl = trim($_POST['postUrl']);
+
+        if ($action == 'comment') {
+            if (!isset($_POST['content'])) {
+                return $this->errorOut('"content" parameter missing');
+            }
+            $content = trim($_POST['content']);
+            if (!strlen($_POST['content'])) {
+                return $this->errorOut('"content" is empty');
+            }
+        }
+
+
         $links = $this->getLinks($me);
         if (!count($links)) {
             return $this->errorOut('No links found');
         $links = $this->getLinks($me);
         if (!count($links)) {
             return $this->errorOut('No links found');
@@ -198,20 +232,30 @@ class Micropub extends Plugin implements IHandler
             return $this->errorOut('No micropub endpoint found');
         }
 
             return $this->errorOut('No micropub endpoint found');
         }
 
+        $parameters = [
+            'access_token' => $account['access_token'],
+            'h'            => 'entry',
+        ];
+
+        if ($action == 'bookmark') {
+            $parameters['bookmark-of'] = $postUrl;
+
+        } else if ($action == 'comment') {
+            $parameters['in-reply-to'] = $postUrl;
+            $parameters['content']     = $content;
+
+        } else if ($action == 'like') {
+            $parameters['like-of'] = $postUrl;
+        }
+
+
         /* unfortunately fetch_file_contents() does not return headers
            so we have to bring our own way to POST data */
         $opts = [
             'http' => [
                 'method'  => 'POST',
                 'header'  => 'Content-type: application/x-www-form-urlencoded',
         /* unfortunately fetch_file_contents() does not return headers
            so we have to bring our own way to POST data */
         $opts = [
             'http' => [
                 'method'  => 'POST',
                 'header'  => 'Content-type: application/x-www-form-urlencoded',
-                'content' => http_build_query(
-                    [
-                        'access_token' => $account['access_token'],
-                        'h'            => 'entry',
-                        'in-reply-to'  => $replyTo,
-                        'content'      => $content,
-                    ]
-                ),
+                'content' => http_build_query($parameters),
                 'ignore_errors' => true,
             ]
         ];
                 'ignore_errors' => true,
             ]
         ];
@@ -228,9 +272,18 @@ class Micropub extends Plugin implements IHandler
         $status = array_shift($headers);
         list($httpver, $code, $text) = explode(' ', $status, 3);
         if ($code != 201 && $code != 202) {
         $status = array_shift($headers);
         list($httpver, $code, $text) = explode(' ', $status, 3);
         if ($code != 201 && $code != 202) {
+            $errData = json_decode($content);
+            if (isset($errData->error_description)
+                && $errData->error_description != ''
+            ) {
+                return $this->errorOut(
+                    'Error creating post: '
+                    . $errData->error_description
+                );
+            }
             return $this->errorOut(
             return $this->errorOut(
-                'An error occured: '
-                . $code . ' ' . $text
+                'Error creating post: '
+                . $code . ' ' . $text.$content
             );
         }
 
             );
         }
 
@@ -357,6 +410,7 @@ class Micropub extends Plugin implements IHandler
             'access_token' => $data['access_token'],
             'scope'        => $data['scope'],
         ];
             'access_token' => $data['access_token'],
             'scope'        => $data['scope'],
         ];
+        $accounts = $this->fixDefaultIdentity($accounts);
         $host->set($this, 'accounts', $accounts);
 
         //all fine now.
         $host->set($this, 'accounts', $accounts);
 
         //all fine now.
@@ -383,9 +437,10 @@ class Micropub extends Plugin implements IHandler
         }
 
         unset($accounts[$me]);
         }
 
         unset($accounts[$me]);
+        $accounts = $this->fixDefaultIdentity($accounts);
         $host->set($this, 'accounts', $accounts);
         $host->set($this, 'accounts', $accounts);
-        header('Content-type: application/json');
 
 
+        header('Content-type: application/json');
         echo json_encode(
             [
                 'code'     => '200',
         echo json_encode(
             [
                 'code'     => '200',
@@ -395,6 +450,63 @@ class Micropub extends Plugin implements IHandler
         exit();
     }
 
         exit();
     }
 
+    /**
+     * Backend preferences action: Make a given account the default
+     */
+    protected function setDefaultIdentityAction()
+    {
+        if (!isset($_POST['me'])) {
+            return $this->errorOut('"me" parameter missing');
+        }
+        $me = trim($_POST['me']);
+
+        $host = PluginHost::getInstance();
+        $accounts = $host->get($this, 'accounts', []);
+        if (!isset($accounts[$me])) {
+            return $this->errorOut('Unknown identity');
+        }
+        foreach ($accounts as $url => $data) {
+            $accounts[$url]['default'] = ($url == $me);
+        }
+        $host->set($this, 'accounts', $accounts);
+
+        header('Content-type: application/json');
+        echo json_encode(
+            [
+                'code'     => '200',
+                'message'  => 'Default account set',
+            ]
+        );
+        exit();
+    }
+
+    /**
+     * Set the default identity if there is none
+     *
+     * @param array $accounts Array of account data arrays
+     *
+     * @return array Array of account data arrays
+     */
+    protected function fixDefaultIdentity($accounts)
+    {
+        if (!count($accounts)) {
+            return $accounts;
+        }
+
+        $hasDefault = false;
+        foreach ($accounts as $account) {
+            if ($account['default']) {
+                $hasDefault = true;
+            }
+        }
+
+        if (!$hasDefault) {
+            reset($accounts);
+            $accounts[key($accounts)]['default'] = true;
+        }
+        return $accounts;
+    }
+
     /**
      * Send an error message.
      * Automatically in the correct format (plain text or json)
     /**
      * Send an error message.
      * Automatically in the correct format (plain text or json)
@@ -455,9 +567,27 @@ class Micropub extends Plugin implements IHandler
         return $links;
     }
 
         return $links;
     }
 
+    /**
+     * If a valid CSRF token is necessary or not
+     *
+     * @param string $method Plugin method name (here: "action")
+     *
+     * @return boolean True if an invalid CSRF token shall be ignored
+     */
     function csrf_ignore($method)
     {
     function csrf_ignore($method)
     {
-        return true;
+        $mode = null;
+        if (isset($_POST['mode'])) {
+            $mode = $_POST['mode'];
+        } else if (isset($_GET['mode'])) {
+            $mode = $_GET['mode'];
+        }
+
+        if ($mode == 'authreturn') {
+            return true;
+        }
+
+        return false;
     }
 
     /**
     }
 
     /**