]> git.mxchange.org Git - friendica-addons.git/blobdiff - twitter/twitter.php
Merge pull request #585 from annando/nicer-cat
[friendica-addons.git] / twitter / twitter.php
index 7a94ebbc1d1ae62909491e7fcff5c7973cbfd98d..5036f515eb517d8511d31e7bc417d3d6f836a5fd 100644 (file)
@@ -200,11 +200,11 @@ function twitter_settings_post(App $a, $post)
                return;
        }
        // don't check twitter settings if twitter submit button is not clicked
-       if (!x($_POST, 'twitter-submit')) {
+       if (empty($_POST['twitter-disconnect']) && empty($_POST['twitter-submit'])) {
                return;
        }
 
-       if (isset($_POST['twitter-disconnect'])) {
+       if (!empty($_POST['twitter-disconnect'])) {
                /*               * *
                 * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
                 * from the user configuration
@@ -229,12 +229,20 @@ function twitter_settings_post(App $a, $post)
                        //  the token and secret for which the PIN was generated were hidden in the settings
                        //  form as token and token2, we need a new connection to Twitter using these token
                        //  and secret to request a Access Token with the PIN
-                       $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
-                       $token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_POST['twitter-pin']]);
-                       //  ok, now that we have the Access Token, save them in the user config
-                       PConfig::set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
-                       PConfig::set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
-                       PConfig::set(local_user(), 'twitter', 'post', 1);
+                       try {
+                               if (empty($_POST['twitter-pin'])) {
+                                       throw new Exception(L10n::t('You submitted an empty PIN, please Sign In with Twitter again to get a new one.'));
+                               }
+
+                               $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
+                               $token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_POST['twitter-pin']]);
+                               //  ok, now that we have the Access Token, save them in the user config
+                               PConfig::set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
+                               PConfig::set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
+                               PConfig::set(local_user(), 'twitter', 'post', 1);
+                       } catch(Exception $e) {
+                               info($e->getMessage());
+                       }
                        //  reload the Addon Settings page, if we don't do it see Bug #42
                        goaway('settings/connectors');
                } else {
@@ -288,34 +296,28 @@ function twitter_settings(App $a, &$s)
        $s .= '</span>';
 
        if ((!$ckey) && (!$csecret)) {
-               /*               * *
-                * no global consumer keys
+               /* no global consumer keys
                 * display warning and skip personal config
                 */
                $s .= '<p>' . L10n::t('No consumer key pair for Twitter found. Please contact your site administrator.') . '</p>';
        } else {
-               /*               * *
-                * ok we have a consumer key pair now look into the OAuth stuff
-                */
+               // ok we have a consumer key pair now look into the OAuth stuff
                if ((!$otoken) && (!$osecret)) {
-                       /*                       * *
-                        * the user has not yet connected the account to twitter...
+                       /* the user has not yet connected the account to twitter...
                         * get a temporary OAuth key/secret pair and display a button with
                         * which the user can request a PIN to connect the account to a
                         * account at Twitter.
                         */
                        $connection = new TwitterOAuth($ckey, $csecret);
                        $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
-                       /*                       * *
-                        *  make some nice form
-                        */
+
                        $s .= '<p>' . L10n::t('At this Friendica instance the Twitter addon was enabled but you have not yet connected your account to your Twitter account. To do so click the button below to get a PIN from Twitter which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to Twitter.') . '</p>';
-                       $s .= '<a href="' . $connection->url('oauth/authorize', ['oauth_token' => $result->oauth_token]) . '" target="_twitter"><img src="addon/twitter/lighter.png" alt="' . L10n::t('Log in with Twitter') . '"></a>';
+                       $s .= '<a href="' . $connection->url('oauth/authorize', ['oauth_token' => $result['oauth_token']]) . '" target="_twitter"><img src="addon/twitter/lighter.png" alt="' . L10n::t('Log in with Twitter') . '"></a>';
                        $s .= '<div id="twitter-pin-wrapper">';
                        $s .= '<label id="twitter-pin-label" for="twitter-pin">' . L10n::t('Copy the PIN from Twitter here') . '</label>';
                        $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
-                       $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result->oauth_token . '" />';
-                       $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result->oauth_token_secret . '" />';
+                       $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result['oauth_token'] . '" />';
+                       $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result['oauth_token_secret'] . '" />';
                        $s .= '</div><div class="clear"></div>';
                        $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
                } else {
@@ -526,6 +528,9 @@ function twitter_post_hook(App $a, &$b)
 
                $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
 
+               // Set the timeout for upload to 30 seconds
+               $connection->setTimeouts(10, 30);
+
                $max_char = 280;
                $msgarr = BBCode::toPlaintext($b, $max_char, true, 8);
                $msg = $msgarr["text"];
@@ -538,87 +543,76 @@ function twitter_post_hook(App $a, &$b)
 
                if (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;
+               }
+
                // and now tweet it :-)
-               if (strlen($msg) && ($image != "")) {
-                       $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
-                       $media = $connection->upload('media/upload', ['media' => $image]);
+               $post = [];
 
-                       $post = ['status' => $msg, 'media_ids' => $media->media_id_string];
+               if (!empty($image)) {
+                       try {
+                               $img_str = Network::fetchUrl($image);
 
-                       if ($iscomment) {
-                               $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
-                       }
+                               $tempfile = tempnam(get_temppath(), 'cache');
+                               file_put_contents($tempfile, $img_str);
 
-                       $result = $connection->post('statuses/update', $post);
+                               $media = $connection->upload('media/upload', ['media' => $tempfile]);
 
-                       logger('twitter_post_with_media send, result: ' . print_r($result, true), LOGGER_DEBUG);
+                               unlink($tempfile);
 
-                       if ($result->source) {
-                               Config::set("twitter", "application_name", strip_tags($result->source));
-                       }
-
-                       if ($result->errors || $result->error) {
-                               logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
+                               $post['media_ids'] = $media->media_id_string;
+                       } catch (Exception $e) {
+                               logger('Exception when trying to send to Twitter: ' . $e->getMessage());
 
                                // Workaround: Remove the picture link so that the post can be reposted without it
-                               $msg .= " " . $image;
+                               // When there is another url already added, a second url would be superfluous.
+                               if (!$url_added) {
+                                       $msg .= "\n" . $image;
+                               }
+
                                $image = "";
-                       } elseif ($iscomment) {
-                               logger('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']);
-                               Item::update(['extid' => "twitter::" . $result->id_str, 'body' => $result->text], ['id' => $b['id']]);
                        }
                }
 
-               if (strlen($msg) && ($image == "")) {
-// -----------------
-                       $max_char = 280;
-                       $msgarr = BBCode::toPlaintext($b, $max_char, true, 8);
-                       $msg = $msgarr["text"];
+               $post['status'] = $msg;
 
-                       if (($msg == "") && isset($msgarr["title"])) {
-                               $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
-                       }
+               if ($iscomment) {
+                       $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
+               }
 
-                       if (isset($msgarr["url"])) {
-                               $msg .= "\n" . $msgarr["url"];
-                       }
-// -----------------
-                       $url = 'statuses/update';
-                       $post = ['status' => $msg, 'weighted_character_count' => 'true'];
+               $url = 'statuses/update';
+               $result = $connection->post($url, $post);
+               logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG);
 
-                       if ($iscomment) {
-                               $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
-                       }
+               if ($result->source) {
+                       Config::set("twitter", "application_name", strip_tags($result->source));
+               }
 
-                       $result = $connection->post($url, $post);
-                       logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG);
+               if ($result->errors) {
+                       logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
 
-                       if ($result->source) {
-                               Config::set("twitter", "application_name", strip_tags($result->source));
+                       $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
+                       if (count($r)) {
+                               $a->contact = $r[0]["id"];
                        }
 
-                       if ($result->errors) {
-                               logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
-
-                               $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
-                               if (count($r)) {
-                                       $a->contact = $r[0]["id"];
-                               }
+                       $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $post]);
 
-                               $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $post]);
-
-                               Queue::add($a->contact, NETWORK_TWITTER, $s);
-                               notice(L10n::t('Twitter post failed. Queued for retry.') . EOL);
-                       } elseif ($iscomment) {
-                               logger('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']);
-                               Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]);
-                       }
+                       Queue::add($a->contact, NETWORK_TWITTER, $s);
+                       notice(L10n::t('Twitter post failed. Queued for retry.') . EOL);
+               } elseif ($iscomment) {
+                       logger('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']);
+                       Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]);
                }
        }
 }