add support for media endpoints
[shpub.git] / src / shpub / Config / Endpoints.php
index 2e58e7abd15699c4389ee267bdb7b517add21d60..c3435505d131f9bc1d59315ae1533c311c3967b4 100644 (file)
@@ -44,7 +44,7 @@ class Config_Endpoints
         $baseUrl = new \Net_URL2($server);
 
         $doc = new \DOMDocument();
-        $doc->loadHTMLFile($server);
+        @$doc->loadHTMLFile($server);
         $sx = simplexml_import_dom($doc);
         if ($sx === false) {
             Log::err('Error loading URL: ' . $server);
@@ -86,6 +86,44 @@ class Config_Endpoints
         );
     }
 
+    public function discoverMedia($accessToken)
+    {
+        $configUrl = $this->micropub;
+        if (strpos($configUrl, '?') === false) {
+            $configUrl .= '?q=config';
+        } else {
+            $configUrl .= '&q=config';
+        }
+
+        $ctx = stream_context_create(
+            [
+                'http' => [
+                    'header' => [
+                        'Accept: application/json',
+                        'Authorization: Bearer ' . $accessToken
+                    ],
+                ]
+            ]
+        );
+        $json = @file_get_contents($configUrl, false, $ctx);
+        if ($json === false) {
+            //does not exist
+            return;
+        }
+        $configData = json_decode($json);
+        if ($configData === null) {
+            //json could not be decoded
+            Log::err('micropub configuration is invalid');
+            return;
+        }
+        if (isset($configData->{'media-endpoint'})) {
+            $configUrlObj = new \Net_URL2($configUrl);
+            $this->media = (string) $configUrlObj->resolve(
+                $configData->{'media-endpoint'}
+            );
+        }
+    }
+
     public function load($server)
     {
         $file = $this->getCacheFilePath($server, false);
@@ -112,10 +150,11 @@ class Config_Endpoints
 
         file_put_contents(
             $file,
-            'micropub=' . $this->micropub . "\n"
-            . 'media=' . $this->media . "\n"
-            . 'token=' . $this->token . "\n"
-             . 'authorization=' . $this->authorization . "\n"
+            'micropub=' . Config::quoteIniValue($this->micropub) . "\n"
+            . 'media=' . Config::quoteIniValue($this->media) . "\n"
+            . 'token=' . Config::quoteIniValue($this->token) . "\n"
+            . 'authorization='
+            . Config::quoteIniValue($this->authorization) . "\n"
         );
     }