Array instead of a string
[friendica-addons.git/.git] / twitter / twitter.php
index f6d5912..ac23b84 100644 (file)
@@ -64,6 +64,7 @@
 
 use Abraham\TwitterOAuth\TwitterOAuth;
 use Abraham\TwitterOAuth\TwitterOAuthException;
+use Codebird\Codebird;
 use Friendica\App;
 use Friendica\Content\OEmbed;
 use Friendica\Content\Text\BBCode;
@@ -79,13 +80,12 @@ use Friendica\Core\Worker;
 use Friendica\Database\DBA;
 use Friendica\Model\Contact;
 use Friendica\Model\Conversation;
-use Friendica\Model\GContact;
 use Friendica\Model\Group;
 use Friendica\Model\Item;
 use Friendica\Model\ItemContent;
 use Friendica\Model\User;
 use Friendica\Object\Image;
-use Friendica\Util\Config\ConfigFileLoader;
+use Friendica\Util\ConfigFileLoader;
 use Friendica\Util\DateTimeFormat;
 use Friendica\Util\Network;
 use Friendica\Util\Strings;
@@ -575,7 +575,7 @@ function twitter_post_hook(App $a, array &$b)
                return;
        }
 
-       Logger::log('twitter post invoked');
+       Logger::notice('twitter post invoked', ['id' => $b['id'], 'guid' => $b['guid']]);
 
        PConfig::load($b['uid'], 'twitter');
 
@@ -592,6 +592,10 @@ function twitter_post_hook(App $a, array &$b)
                        return;
                }
 
+               Codebird::setConsumerKey($ckey, $csecret);
+               $cb = Codebird::getInstance();
+               $cb->setToken($otoken, $osecret);
+
                $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
 
                // Set the timeout for upload to 30 seconds
@@ -610,25 +614,22 @@ function twitter_post_hook(App $a, array &$b)
                $b['body'] = twitter_update_mentions($b['body']);
 
                $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 8);
+               Logger::info('Got plaintext', $msgarr);
                $msg = $msgarr["text"];
 
                if (($msg == "") && isset($msgarr["title"])) {
                        $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
                }
 
-               $image = "";
-
-               if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
+               if (($msgarr['url'] == $b['plink']) && !empty($msgarr['images']) && (count($msgarr['images']) <= 4)) {
+                       $url_added = false;
+               } elseif (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
                        $msg .= "\n" . $msgarr["url"];
                        $url_added = true;
                } else {
                        $url_added = false;
                }
 
-               if (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
-                       $image = $msgarr["image"];
-               }
-
                if (empty($msg)) {
                        return;
                }
@@ -636,32 +637,42 @@ function twitter_post_hook(App $a, array &$b)
                // and now tweet it :-)
                $post = [];
 
-               if (!empty($image)) {
+               if (!empty($msgarr['images'])) {
                        try {
-                               $img_str = Network::fetchUrl($image);
+                               $media_ids = [];
+                               foreach ($msgarr['images'] as $image) {
+                                       if (count($media_ids) == 4) {
+                                               continue;
+                                       }
 
-                               $tempfile = tempnam(get_temppath(), 'cache');
-                               file_put_contents($tempfile, $img_str);
+                                       $img_str = Network::fetchUrl($image['url']);
 
-                               $media = $connection->upload('media/upload', ['media' => $tempfile]);
+                                       $tempfile = tempnam(get_temppath(), 'cache');
+                                       file_put_contents($tempfile, $img_str);
 
-                               unlink($tempfile);
+                                       $media = $connection->upload('media/upload', ['media' => $tempfile]);
 
-                               if (isset($media->media_id_string)) {
-                                       $post['media_ids'] = $media->media_id_string;
-                               } else {
-                                       throw new Exception('Failed upload of ' . $image);
+                                       unlink($tempfile);
+
+                                       if (isset($media->media_id_string)) {
+                                               $media_ids[] = $media->media_id_string;
+
+                                               if (!empty($image['description'])) {
+                                                       $data = ['media_id' => $media->media_id_string,
+                                                               'alt_text' => ['text' => substr($image['description'], 0, 420)]];
+                                                       $ret = $cb->media_metadata_create($data);
+                                                       Logger::info('Metadata create', ['data' => $data, 'return' => json_encode($ret)]);
+                                               }
+                                       } else {
+                                               throw new Exception('Failed upload of ' . $image['url']);
+                                       }
+                               }
+                               $post['media_ids'] = implode(',', $media_ids);
+                               if (empty($post['media_ids'])) {
+                                       unset($post['media_ids']);
                                }
                        } catch (Exception $e) {
                                Logger::log('Exception when trying to send to Twitter: ' . $e->getMessage());
-
-                               // Workaround: Remove the picture link so that the post can be reposted without it
-                               // When there is another url already added, a second url would be superfluous.
-                               if (!$url_added) {
-                                       $msg .= "\n" . $image;
-                               }
-
-                               $image = "";
                        }
                }
 
@@ -814,7 +825,7 @@ function twitter_prepare_body(App $a, array &$b)
        if ($b["preview"]) {
                $max_char = 280;
                $item = $b["item"];
-               $item["plink"] = $a->getBaseURL() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
+               $item["plink"] = $a->getBaseURL() . "/display/" . $item["guid"];
 
                $condition = ['uri' => $item["thr-parent"], 'uid' => local_user()];
                $orig_post = Item::selectFirst(['author-link'], $condition);
@@ -925,7 +936,7 @@ function twitter_fetchtimeline(App $a, $uid)
 
        $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
 
-       $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
+       $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended", "include_ext_alt_text" => true];
 
        $first_time = ($lastid == "");
 
@@ -1004,12 +1015,6 @@ function twitter_fetch_contact($uid, $data, $create_user)
        $url = "https://twitter.com/" . $data->screen_name;
        $addr = $data->screen_name . "@twitter.com";
 
-       GContact::update(["url" => $url, "network" => Protocol::TWITTER,
-               "photo" => $avatar, "hide" => true,
-               "name" => $data->name, "nick" => $data->screen_name,
-               "location" => $data->location, "about" => $data->description,
-               "addr" => $addr, "generation" => 2]);
-
        $fields = ['url' => $url, 'network' => Protocol::TWITTER,
                'name' => $data->name, 'nick' => $data->screen_name, 'addr' => $addr,
                 'location' => $data->location, 'about' => $data->description];
@@ -1184,7 +1189,7 @@ function twitter_expand_entities(App $a, $body, $item, $picture)
                                } elseif ($oembed_data->type != 'link') {
                                        $body = str_replace($url->url, '[url=' . $expanded_url . ']' . $url->display_url . '[/url]', $body);
                                } else {
-                                       $img_str = Network::fetchUrl($final_url, true, $redirects, 4);
+                                       $img_str = Network::fetchUrl($final_url, true, 4);
 
                                        $tempfile = tempnam(get_temppath(), 'cache');
                                        file_put_contents($tempfile, $img_str);
@@ -1318,12 +1323,24 @@ function twitter_media_entities($post, array &$postarray)
                }
                switch ($medium->type) {
                        case 'photo':
-                               $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
+                               if (!empty($medium->ext_alt_text)) {
+                                       Logger::info('Got text description', ['alt_text' => $medium->ext_alt_text]);
+                                       $media[$medium->url] .= "\n[img=" . $medium->media_url_https .']' . $medium->ext_alt_text . '[/img]';
+                               } else {
+                                       $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
+                               }
+
                                $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
                                break;
                        case 'video':
                        case 'animated_gif':
-                               $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
+                               if (!empty($medium->ext_alt_text)) {
+                                       Logger::info('Got text description', ['alt_text' => $medium->ext_alt_text]);
+                                       $media[$medium->url] .= "\n[img=" . $medium->media_url_https .']' . $medium->ext_alt_text . '[/img]';
+                               } else {
+                                       $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
+                               }
+
                                $postarray['object-type'] = ACTIVITY_OBJ_VIDEO;
                                if (is_array($medium->video_info->variants)) {
                                        $bitrate = 0;
@@ -1539,7 +1556,7 @@ function twitter_fetchparentposts(App $a, $uid, $post, TwitterOAuth $connection,
        $posts = [];
 
        while (!empty($post->in_reply_to_status_id_str)) {
-               $parameters = ["trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str];
+               $parameters = ["trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str, "include_ext_alt_text" => true];
 
                try {
                        $post = $connection->get('statuses/show', $parameters);
@@ -1549,7 +1566,7 @@ function twitter_fetchparentposts(App $a, $uid, $post, TwitterOAuth $connection,
                }
 
                if (empty($post)) {
-                       Logger::log("twitter_fetchparentposts: Can't fetch post " . $parameters->id, Logger::DEBUG);
+                       Logger::log("twitter_fetchparentposts: Can't fetch post " . $parameters['id'], Logger::DEBUG);
                        break;
                }
 
@@ -1629,7 +1646,7 @@ function twitter_fetchhometimeline(App $a, $uid)
                return;
        }
 
-       $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
+       $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended", "include_ext_alt_text" => true];
        //$parameters["count"] = 200;
        // Fetching timeline
        $lastid = PConfig::get($uid, 'twitter', 'lasthometimelineid');