web/tweet_ajax.php
changeset 1558 761ba7426984
parent 1557 7c67caaafdeb
child 1575 ce1d5b0d1479
--- a/web/tweet_ajax.php	Mon Nov 20 18:10:58 2023 +0100
+++ b/web/tweet_ajax.php	Tue Sep 03 11:09:40 2024 +0200
@@ -1,14 +1,13 @@
 <?php
 
 include_once 'common.php';
+
 use Abraham\TwitterOAuth\TwitterOAuth;
+use GuzzleHttp\Client;
 
-/**
- * Check for a POSTed status message to send to Twitter
- */
-if (!empty($_POST) && isset($_POST['status'])
-&& isset($_SESSION['SOCIAL_ACCESS_TOKEN'])) {
 
+function sendTwitter()
+{
     $token = unserialize($_SESSION['SOCIAL_ACCESS_TOKEN']);
     $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $token['oauth_token'], $token['oauth_token_secret']);
 
@@ -36,7 +35,60 @@
      * Tweet sent (hopefully), redirect back home...
      */
     //header('Location: ' . URL_ROOT . '?result=' . $result);
-	echo($result);
+    echo ($result);
+}
+
+function addHashtagMastodon($status, $hashtag, $group) : string {
+    $res = $status;
+    $to_add = "";
+
+    if(!str_contains($status, "#$hashtag")) {
+        $to_add .= " #$hashtag";
+    }
+    if(!str_contains($status, $group)) {
+        $to_add .= " $group";
+    }
+
+    return mb_substr($status,0, 512-mb_strlen($to_add)).$to_add;
+}
+
+function sendMastodon()
+{
+    $token = unserialize($_SESSION['SOCIAL_ACCESS_TOKEN']);
+    $domain = $_SESSION['SOCIAL_LOGIN_DOMAIN'];
+    $status = addHashtagMastodon($_POST['status'], ltrim($_POST['hashtag'], '#'), $_POST['group']);
+
+    $client = new Client([
+        'base_uri' => "https://$domain",
+        'timeout'  => 2.0,
+    ]);
+    $resp = $client->post("/api/v1/statuses", [
+        'headers' => [
+            'Authorization'   => 'Bearer ' . $token,
+            'Accept'          => 'application/json',
+            'Idempotency-Key' => hash('sha256', $status),
+        ],
+        'form_params' => [ 'status' => $status ],
+    ]);
+    echo('true');
+}
+
+
+/**
+ * Check for a POSTed status message to send to Twitter
+ */
+if (
+    !empty($_POST) && isset($_POST['status'])
+    && isset($_SESSION['SOCIAL_ACCESS_TOKEN'])
+) {
+
+    $socialNetwork = isset($_POST['social_network']) ? $_POST['social_network'] : "Twitter";
+
+    if ($socialNetwork == "Twitter") {
+        sendTwitter();
+    } else {
+        sendMastodon();
+    }
 } else {
     /**
      * Mistaken request? Some malfeasant trying something?