X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=twitter%2Ftwitter.php;h=29a1a631adff61b2cf22332898e64cdb18e24219;hb=7b7019477fe29dd89378fe5012f909b604995879;hp=1863b8bcb47ec6826edf03828a0f28f43aa94ab7;hpb=633c54d64287bf8d4f5801a22a88ddd1a77d3a14;p=friendica-addons.git diff --git a/twitter/twitter.php b/twitter/twitter.php index 1863b8bc..29a1a631 100644 --- a/twitter/twitter.php +++ b/twitter/twitter.php @@ -77,6 +77,7 @@ use Friendica\Model\Photo; use Friendica\Model\Queue; use Friendica\Model\User; use Friendica\Object\Image; +use Friendica\Util\DateTimeFormat; use Friendica\Util\Network; require_once 'boot.php'; @@ -199,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 @@ -228,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 { @@ -287,34 +296,28 @@ function twitter_settings(App $a, &$s) $s .= ''; if ((!$ckey) && (!$csecret)) { - /* * * - * no global consumer keys + /* no global consumer keys * display warning and skip personal config */ $s .= '

' . L10n::t('No consumer key pair for Twitter found. Please contact your site administrator.') . '

'; } 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 .= '

' . 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 public posts will be posted to Twitter.') . '

'; - $s .= '' . L10n::t('Log in with Twitter') . ''; + $s .= '' . L10n::t('Log in with Twitter') . ''; $s .= '
'; $s .= ''; $s .= ''; - $s .= ''; - $s .= ''; + $s .= ''; + $s .= ''; $s .= '
'; $s .= '
'; } else { @@ -525,6 +528,9 @@ function twitter_post_hook(App $a, &$b) $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + // Set the timeout for upload to 15 seconds + $connection->setTimeouts(10, 15); + $max_char = 280; $msgarr = BBCode::toPlaintext($b, $max_char, true, 8); $msg = $msgarr["text"]; @@ -545,36 +551,46 @@ function twitter_post_hook(App $a, &$b) // and now tweet it :-) if (strlen($msg) && ($image != "")) { - $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); - $media = $connection->upload('media/upload', ['media' => $image]); + try { + $img_str = Network::fetchUrl($image); - $post = ['status' => $msg, 'media_ids' => $media->media_id_string]; + $tempfile = tempnam(get_temppath(), 'cache'); + file_put_contents($tempfile, $img_str); - if ($iscomment) { - $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9); - } + $media = $connection->upload('media/upload', ['media' => $tempfile]); - $result = $connection->post('statuses/update', $post); + unlink($tempfile); - logger('twitter_post_with_media send, result: ' . print_r($result, true), LOGGER_DEBUG); + $post = ['status' => $msg, 'media_ids' => $media->media_id_string]; - if ($result->source) { - Config::set("twitter", "application_name", strip_tags($result->source)); - } + if ($iscomment) { + $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9); + } - if ($result->errors || $result->error) { - logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"'); + $result = $connection->post('statuses/update', $post); + + logger('twitter_post_with_media send, result: ' . print_r($result, true), LOGGER_DEBUG); + + 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) . '"'); + + // Workaround: Remove the picture link so that the post can be reposted without it + $msg .= " " . $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']]); + } + } 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; $image = ""; - } elseif ($iscomment) { - logger('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']); - q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d", - dbesc("twitter::" . $result->id_str), - dbesc($result->text), - intval($b['id']) - ); } } @@ -620,10 +636,7 @@ function twitter_post_hook(App $a, &$b) 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']); - q("UPDATE `item` SET `extid` = '%s' WHERE `id` = %d", - dbesc("twitter::" . $result->id_str), - intval($b['id']) - ); + Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]); } } } @@ -681,7 +694,7 @@ function twitter_cron(App $a, $b) $abandon_days = 0; } - $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400); + $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400); $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1'"); if (count($r)) { @@ -1016,7 +1029,7 @@ function twitter_fetch_contact($uid, $contact, $create_user) `location`, `about`, `writable`, `blocked`, `readonly`, `pending`) VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)", intval($uid), - dbesc(datetime_convert()), + dbesc(DateTimeFormat::utcNow()), dbesc("https://twitter.com/" . $contact->screen_name), dbesc(normalise_link("https://twitter.com/" . $contact->screen_name)), dbesc($contact->screen_name."@twitter.com"), @@ -1060,16 +1073,16 @@ function twitter_fetch_contact($uid, $contact, $create_user) dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), - dbesc(datetime_convert()), - dbesc(datetime_convert()), - dbesc(datetime_convert()), + dbesc(DateTimeFormat::utcNow()), + dbesc(DateTimeFormat::utcNow()), + dbesc(DateTimeFormat::utcNow()), intval($contact_id) ); } } else { // update profile photos once every two weeks as we have no notification of when they change. - //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false); - $update_photo = ($r[0]['avatar-date'] < datetime_convert('', '', 'now -12 hours')); + //$update_photo = (($r[0]['avatar-date'] < DateTimeFormat::convert('now -2 days', '', '', )) ? true : false); + $update_photo = ($r[0]['avatar-date'] < DateTimeFormat::utc('now -12 hours')); // check that we have all the photos, this has been known to fail on occasion if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) { @@ -1095,9 +1108,9 @@ function twitter_fetch_contact($uid, $contact, $create_user) dbesc($photos[0]), dbesc($photos[1]), dbesc($photos[2]), - dbesc(datetime_convert()), - dbesc(datetime_convert()), - dbesc(datetime_convert()), + dbesc(DateTimeFormat::utcNow()), + dbesc(DateTimeFormat::utcNow()), + dbesc(DateTimeFormat::utcNow()), dbesc("https://twitter.com/".$contact->screen_name), dbesc(normalise_link("https://twitter.com/".$contact->screen_name)), dbesc($contact->screen_name."@twitter.com"), @@ -1153,12 +1166,24 @@ function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "") return $contact_id; } -function twitter_expand_entities(App $a, $body, $item, $no_tags = false, $picture) +function twitter_expand_entities(App $a, $body, $item, $picture) { - $tags = ""; - $plain = $body; + $tags_arr = []; + + foreach ($item->entities->hashtags AS $hashtag) { + $url = "#[url=" . $a->get_baseurl() . "/search?tag=" . rawurlencode($hashtag->text) . "]" . $hashtag->text . "[/url]"; + $tags_arr["#" . $hashtag->text] = $url; + $body = str_replace("#" . $hashtag->text, $url, $body); + } + + foreach ($item->entities->user_mentions AS $mention) { + $url = "@[url=https://twitter.com/" . rawurlencode($mention->screen_name) . "]" . $mention->screen_name . "[/url]"; + $tags_arr["@" . $mention->screen_name] = $url; + $body = str_replace("@" . $mention->screen_name, $url, $body); + } + if (isset($item->entities->urls)) { $type = ""; $footerurl = ""; @@ -1239,66 +1264,49 @@ function twitter_expand_entities(App $a, $body, $item, $no_tags = false, $pictur } elseif (($footer == "") && ($picture == "")) { $body = add_page_info_to_body($body); } + } - if ($no_tags) { - return ["body" => $body, "tags" => "", "plain" => $plain]; - } - - $tags_arr = []; - - foreach ($item->entities->hashtags AS $hashtag) { - $url = "#[url=" . $a->get_baseurl() . "/search?tag=" . rawurlencode($hashtag->text) . "]" . $hashtag->text . "[/url]"; - $tags_arr["#" . $hashtag->text] = $url; - $body = str_replace("#" . $hashtag->text, $url, $body); - } + // it seems as if the entities aren't always covering all mentions. So the rest will be checked here + $tags = get_tags($body); - foreach ($item->entities->user_mentions AS $mention) { - $url = "@[url=https://twitter.com/" . rawurlencode($mention->screen_name) . "]" . $mention->screen_name . "[/url]"; - $tags_arr["@" . $mention->screen_name] = $url; - $body = str_replace("@" . $mention->screen_name, $url, $body); - } - - // it seems as if the entities aren't always covering all mentions. So the rest will be checked here - $tags = get_tags($body); + if (count($tags)) { + foreach ($tags as $tag) { + if (strstr(trim($tag), " ")) { + continue; + } - if (count($tags)) { - foreach ($tags as $tag) { - if (strstr(trim($tag), " ")) { + if (strpos($tag, '#') === 0) { + if (strpos($tag, '[url=')) { continue; } - if (strpos($tag, '#') === 0) { - if (strpos($tag, '[url=')) { - continue; - } - - // don't link tags that are already embedded in links - if (preg_match('/\[(.*?)' . preg_quote($tag, '/') . '(.*?)\]/', $body)) { - continue; - } - if (preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag, '/') . '(.*?)\)/', $body)) { - continue; - } - - $basetag = str_replace('_', ' ', substr($tag, 1)); - $url = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]'; - $body = str_replace($tag, $url, $body); - $tags_arr["#" . $basetag] = $url; - } elseif (strpos($tag, '@') === 0) { - if (strpos($tag, '[url=')) { - continue; - } + // don't link tags that are already embedded in links + if (preg_match('/\[(.*?)' . preg_quote($tag, '/') . '(.*?)\]/', $body)) { + continue; + } + if (preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag, '/') . '(.*?)\)/', $body)) { + continue; + } - $basetag = substr($tag, 1); - $url = '@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]'; - $body = str_replace($tag, $url, $body); - $tags_arr["@" . $basetag] = $url; + $basetag = str_replace('_', ' ', substr($tag, 1)); + $url = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]'; + $body = str_replace($tag, $url, $body); + $tags_arr["#" . $basetag] = $url; + } elseif (strpos($tag, '@') === 0) { + if (strpos($tag, '[url=')) { + continue; } + + $basetag = substr($tag, 1); + $url = '@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]'; + $body = str_replace($tag, $url, $body); + $tags_arr["@" . $basetag] = $url; } } - - $tags = implode($tags_arr, ","); } + + $tags = implode($tags_arr, ","); + return ["body" => $body, "tags" => $tags, "plain" => $plain]; } @@ -1308,7 +1316,7 @@ function twitter_expand_entities(App $a, $body, $item, $no_tags = false, $pictur * @param object $post Twitter object with the post * @param array $postarray Array of the item that is about to be posted * - * @return $picture string Returns a a single picture string if it isn't a media post + * @return $picture string Image URL or empty string */ function twitter_media_entities($post, &$postarray) { @@ -1486,11 +1494,11 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis // Search for media links $picture = twitter_media_entities($post, $postarray); - $converted = twitter_expand_entities($a, $postarray['body'], $post, false, $picture); + $converted = twitter_expand_entities($a, $postarray['body'], $post, $picture); $postarray['body'] = $converted["body"]; $postarray['tag'] = $converted["tags"]; - $postarray['created'] = datetime_convert('UTC', 'UTC', $post->created_at); - $postarray['edited'] = datetime_convert('UTC', 'UTC', $post->created_at); + $postarray['created'] = DateTimeFormat::utc($post->created_at); + $postarray['edited'] = DateTimeFormat::utc($post->created_at); $statustext = $converted["plain"];