X-Git-Url: https://git.mxchange.org/?a=blobdiff_plain;f=twitter%2Ftwitter.php;h=a460fd70f14b894f506805bcb45a7accec0ca4d1;hb=7e516b541dd92691ad490e1fb6efae123599cd85;hp=6402b82d2a508fe748f84d3e0cb93460061cb2f9;hpb=e09e16fd5632f5916c1ee3bd3501924ddfc9d272;p=friendica-addons.git diff --git a/twitter/twitter.php b/twitter/twitter.php index 6402b82d..a460fd70 100644 --- a/twitter/twitter.php +++ b/twitter/twitter.php @@ -2,11 +2,12 @@ /** * Name: Twitter Connector * Description: Bidirectional (posting, relaying and reading) connector for Twitter. - * Version: 1.0.4 + * Version: 1.1.0 * Author: Tobias Diekershoff * Author: Michael Vogel + * Maintainer: Hypolite Petovan * - * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel + * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel, Hypolite Petovan * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -56,9 +57,10 @@ * setting. After this, your user can configure their Twitter account settings * from "Settings -> Addon Settings". * - * Requirements: PHP5, curl [Slinky library] + * Requirements: PHP5, curl */ +use Abraham\TwitterOAuth\TwitterOAuth; use Friendica\App; use Friendica\Content\OEmbed; use Friendica\Content\Text\BBCode; @@ -70,12 +72,20 @@ use Friendica\Core\PConfig; use Friendica\Core\Worker; use Friendica\Model\GContact; use Friendica\Model\Group; +use Friendica\Model\Item; 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'; +require_once 'include/dba.php'; require_once 'include/enotify.php'; +require_once 'include/text.php'; + +require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php'; define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes @@ -144,21 +154,19 @@ function twitter_follow(App $a, &$contact) $uid = $a->user["uid"]; - $ckey = Config::get('twitter', 'consumerkey'); + $ckey = Config::get('twitter', 'consumerkey'); $csecret = Config::get('twitter', 'consumersecret'); - $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); + $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); $osecret = PConfig::get($uid, 'twitter', 'oauthsecret'); - require_once "addon/twitter/codebird.php"; - - $cb = \Codebird\Codebird::getInstance(); - $cb->setConsumerKey($ckey, $csecret); - $cb->setToken($otoken, $osecret); - - $parameters = []; - $parameters["screen_name"] = $nickname; + // If the addon is not configured (general or for this user) quit here + if (empty($ckey) || empty($csecret) || empty($otoken) || empty($osecret)) { + $contact = false; + return; + } - $user = $cb->friendships_create($parameters); + $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + $connection->post('friendships/create', ['screen_name' => $nickname]); twitter_fetchuser($a, $uid, $nickname); @@ -192,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 @@ -216,18 +224,25 @@ function twitter_settings_post(App $a, $post) if (isset($_POST['twitter-pin'])) { // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen logger('got a Twitter PIN'); - require_once 'library/twitteroauth.php'; $ckey = Config::get('twitter', 'consumerkey'); $csecret = Config::get('twitter', 'consumersecret'); // 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->getAccessToken($_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 { @@ -259,10 +274,10 @@ function twitter_settings(App $a, &$s) * 2) If no OAuthtoken & stuff is present, generate button to get some * 3) Checkbox for "Send public notices (280 chars only) */ - $ckey = Config::get('twitter', 'consumerkey' ); - $csecret = Config::get('twitter', 'consumersecret' ); - $otoken = PConfig::get(local_user(), 'twitter', 'oauthtoken' ); - $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret' ); + $ckey = Config::get('twitter', 'consumerkey'); + $csecret = Config::get('twitter', 'consumersecret'); + $otoken = PConfig::get(local_user(), 'twitter', 'oauthtoken'); + $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret'); $enabled = intval(PConfig::get(local_user(), 'twitter', 'post')); $defenabled = intval(PConfig::get(local_user(), 'twitter', 'post_by_default')); @@ -281,36 +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. */ - require_once 'library/twitteroauth.php'; $connection = new TwitterOAuth($ckey, $csecret); - $request_token = $connection->getRequestToken(); - $token = $request_token['oauth_token']; - /* * * - * make some nice form - */ + $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']); + $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 { @@ -318,7 +325,6 @@ function twitter_settings(App $a, &$s) * we have an OAuth key / secret pair for the user * so let's give a chance to disable the postings to Twitter */ - require_once 'library/twitteroauth.php'; $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); $details = $connection->get('account/verify_credentials'); @@ -397,11 +403,7 @@ function twitter_action(App $a, $uid, $pid, $action) $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); $osecret = PConfig::get($uid, 'twitter', 'oauthsecret'); - require_once "addon/twitter/codebird.php"; - - $cb = \Codebird\Codebird::getInstance(); - $cb->setConsumerKey($ckey, $csecret); - $cb->setToken($otoken, $osecret); + $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); $post = ['id' => $pid]; @@ -409,13 +411,13 @@ function twitter_action(App $a, $uid, $pid, $action) switch ($action) { case "delete": - // To-Do: $result = $cb->statuses_destroy($post); + // To-Do: $result = $connection->post('statuses/destroy', $post); break; case "like": - $result = $cb->favorites_create($post); + $result = $connection->post('favorites/create', $post); break; case "unlike": - $result = $cb->favorites_destroy($post); + $result = $connection->post('favorites/destroy', $post); break; } logger("twitter_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG); @@ -424,8 +426,6 @@ function twitter_action(App $a, $uid, $pid, $action) function twitter_post_hook(App $a, &$b) { // Post to Twitter - require_once "include/network.php"; - if (!PConfig::get($b["uid"], 'twitter', 'import') && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) { return; @@ -435,7 +435,10 @@ function twitter_post_hook(App $a, &$b) logger("twitter_post_hook: parameter " . print_r($b, true), LOGGER_DATA); // Looking if its a reply to a twitter post - if ((substr($b["parent-uri"], 0, 9) != "twitter::") && (substr($b["extid"], 0, 9) != "twitter::") && (substr($b["thr-parent"], 0, 9) != "twitter::")) { + if ((substr($b["parent-uri"], 0, 9) != "twitter::") + && (substr($b["extid"], 0, 9) != "twitter::") + && (substr($b["thr-parent"], 0, 9) != "twitter::")) + { logger("twitter_post_hook: no twitter post " . $b["parent"]); return; } @@ -484,10 +487,12 @@ function twitter_post_hook(App $a, &$b) if ($b['verb'] == ACTIVITY_LIKE) { logger("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), LOGGER_DEBUG); - if ($b['deleted']) + if ($b['deleted']) { twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike"); - else + } else { twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "like"); + } + return; } @@ -521,9 +526,7 @@ function twitter_post_hook(App $a, &$b) return; } - require_once 'library/twitteroauth.php'; - require_once 'include/bbcode.php'; - $tweet = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); $max_char = 280; $msgarr = BBCode::toPlaintext($b, $max_char, true, 8); @@ -545,29 +548,16 @@ function twitter_post_hook(App $a, &$b) // and now tweet it :-) if (strlen($msg) && ($image != "")) { - $img_str = fetch_url($image); - - $tempfile = tempnam(get_temppath(), "cache"); - file_put_contents($tempfile, $img_str); - - // Twitter had changed something so that the old library doesn't work anymore - // so we are using a new library for twitter - // To-Do: - // Switching completely to this library with all functions - require_once "addon/twitter/codebird.php"; - - $cb = \Codebird\Codebird::getInstance(); - $cb->setConsumerKey($ckey, $csecret); - $cb->setToken($otoken, $osecret); + $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + $media = $connection->upload('media/upload', ['media' => $image]); - $post = ['status' => $msg, 'media[]' => $tempfile]; + $post = ['status' => $msg, 'media_ids' => $media->media_id_string]; if ($iscomment) { $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9); } - $result = $cb->statuses_updateWithMedia($post); - unlink($tempfile); + $result = $connection->post('statuses/update', $post); logger('twitter_post_with_media send, result: ' . print_r($result, true), LOGGER_DEBUG); @@ -583,11 +573,7 @@ function twitter_post_hook(App $a, &$b) $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']) - ); + Item::update(['extid' => "twitter::" . $result->id_str, 'body' => $result->text], ['id' => $b['id']]); } } @@ -612,7 +598,7 @@ function twitter_post_hook(App $a, &$b) $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9); } - $result = $tweet->post($url, $post); + $result = $connection->post($url, $post); logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG); if ($result->source) { @@ -628,15 +614,12 @@ function twitter_post_hook(App $a, &$b) } $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']); - 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']]); } } } @@ -644,8 +627,8 @@ function twitter_post_hook(App $a, &$b) function twitter_addon_admin_post(App $a) { - $consumerkey = x($_POST, 'consumerkey') ? notags(trim($_POST['consumerkey'])) : ''; - $consumersecret = x($_POST, 'consumersecret') ? notags(trim($_POST['consumersecret'])) : ''; + $consumerkey = x($_POST, 'consumerkey') ? notags(trim($_POST['consumerkey'])) : ''; + $consumersecret = x($_POST, 'consumersecret') ? notags(trim($_POST['consumersecret'])) : ''; Config::set('twitter', 'consumerkey', $consumerkey); Config::set('twitter', 'consumersecret', $consumersecret); info(L10n::t('Settings updated.') . EOL); @@ -690,10 +673,11 @@ function twitter_cron(App $a, $b) } $abandon_days = intval(Config::get('system', 'account_abandon_days')); - if ($abandon_days < 1) + if ($abandon_days < 1) { $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)) { @@ -756,7 +740,7 @@ function twitter_expire(App $a, $b) if (count($r)) { foreach ($r as $rr) { logger('twitter_expire: user ' . $rr['uid']); - item_expire($rr['uid'], $days, NETWORK_TWITTER, true); + Item::expire($rr['uid'], $days, NETWORK_TWITTER, true); } } @@ -828,7 +812,14 @@ function twitter_do_mirrorpost(App $a, $uid, $post) // We don't support nested shares, so we mustn't show quotes as shares on retweets $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true); - $datarray['body'] = "\n" . share_header($item['author-name'], $item['author-link'], $item['author-avatar'], "", $item['created'], $item['plink']); + $datarray['body'] = "\n" . share_header( + $item['author-name'], + $item['author-link'], + $item['author-avatar'], + "", + $item['created'], + $item['plink'] + ); $datarray['body'] .= $item['body'] . '[/share]'; } else { @@ -871,7 +862,6 @@ function twitter_fetchtimeline(App $a, $uid) require_once 'include/items.php'; require_once 'mod/share.php'; - require_once 'library/twitteroauth.php'; $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"]; @@ -954,15 +944,8 @@ function twitter_queue_hook(App $a, &$b) $z = unserialize($x['content']); - require_once "addon/twitter/codebird.php"; - - $cb = \Codebird\Codebird::getInstance(); - $cb->setConsumerKey($ckey, $csecret); - $cb->setToken($otoken, $osecret); - - if ($z['url'] == "statuses/update") { - $result = $cb->statuses_update($z['post']); - } + $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + $result = $connection->post($z['url'], $z['post']); logger('twitter_queue: post result: ' . print_r($result, true), LOGGER_DEBUG); @@ -1010,7 +993,8 @@ function twitter_fetch_contact($uid, $contact, $create_user) "addr" => $contact->screen_name . "@twitter.com", "generation" => 2]); $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", - intval($uid), dbesc("twitter::" . $contact->id_str)); + intval($uid), + dbesc("twitter::" . $contact->id_str)); if (!count($r) && !$create_user) { return 0; @@ -1028,7 +1012,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"), @@ -1072,16 +1056,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)) { @@ -1107,9 +1091,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"), @@ -1128,17 +1112,11 @@ function twitter_fetch_contact($uid, $contact, $create_user) function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "") { - $ckey = Config::get('twitter', 'consumerkey'); + $ckey = Config::get('twitter', 'consumerkey'); $csecret = Config::get('twitter', 'consumersecret'); - $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); + $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); $osecret = PConfig::get($uid, 'twitter', 'oauthsecret'); - require_once "addon/twitter/codebird.php"; - - $cb = \Codebird\Codebird::getInstance(); - $cb->setConsumerKey($ckey, $csecret); - $cb->setToken($otoken, $osecret); - $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1", intval($uid)); @@ -1159,7 +1137,8 @@ function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "") } // Fetching user data - $user = $cb->users_show($parameters); + $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); + $user = $connection->get('users/show', $parameters); if (!is_object($user)) { return; @@ -1170,13 +1149,23 @@ 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) { - require_once "include/network.php"; + $plain = $body; - $tags = ""; + $tags_arr = []; - $plain = $body; + 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 = ""; @@ -1184,11 +1173,11 @@ function twitter_expand_entities(App $a, $body, $item, $no_tags = false, $pictur $footerlink = ""; $footer = ""; - foreach ($item->entities->urls AS $url) { + foreach ($item->entities->urls as $url) { $plain = str_replace($url->url, '', $plain); if ($url->url && $url->expanded_url && $url->display_url) { - $expanded_url = original_url($url->expanded_url); + $expanded_url = Network::finalUrl($url->expanded_url); $oembed_data = OEmbed::fetchURL($expanded_url); @@ -1217,7 +1206,7 @@ function twitter_expand_entities(App $a, $body, $item, $no_tags = false, $pictur } elseif ($oembed_data->type != "link") { $body = str_replace($url->url, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body); } else { - $img_str = fetch_url($expanded_url, true, $redirects, 4); + $img_str = Network::fetchUrl($expanded_url, true, $redirects, 4); $tempfile = tempnam(get_temppath(), "cache"); file_put_contents($tempfile, $img_str); @@ -1258,66 +1247,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); - } - - 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); - // 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]; } @@ -1327,7 +1299,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) { @@ -1397,8 +1369,8 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis // Don't import our own comments $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1", - dbesc($postarray['uri']), - intval($uid) + dbesc($postarray['uri']), + intval($uid) ); if (count($r)) { @@ -1412,8 +1384,8 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis $parent = "twitter::" . $post->in_reply_to_status_id_str; $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", - dbesc($parent), - intval($uid) + dbesc($parent), + intval($uid) ); if (count($r)) { $postarray['thr-parent'] = $r[0]["uri"]; @@ -1422,8 +1394,8 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis $postarray['object-type'] = ACTIVITY_OBJ_COMMENT; } else { $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1", - dbesc($parent), - intval($uid) + dbesc($parent), + intval($uid) ); if (count($r)) { $postarray['thr-parent'] = $r[0]['uri']; @@ -1505,11 +1477,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"]; @@ -1544,7 +1516,14 @@ function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_exis $postarray['body'] = $statustext; - $postarray['body'] .= "\n" . share_header($quoted['author-name'], $quoted['author-link'], $quoted['author-avatar'], "", $quoted['created'], $quoted['plink']); + $postarray['body'] .= "\n" . share_header( + $quoted['author-name'], + $quoted['author-link'], + $quoted['author-avatar'], + "", + $quoted['created'], + $quoted['plink'] + ); $postarray['body'] .= $quoted['body'] . '[/share]'; } @@ -1556,7 +1535,7 @@ function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray) { /// TODO: this whole function doesn't seem to work. Needs complete check $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", - intval($uid) + intval($uid) ); if (!count($user)) { @@ -1569,8 +1548,8 @@ function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray) } $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1", - intval($uid), - dbesc("twitter::".$own_id) + intval($uid), + dbesc("twitter::".$own_id) ); if (!count($own_user)) { @@ -1583,8 +1562,8 @@ function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray) } $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0", - dbesc($postarray['parent-uri']), - intval($uid) + dbesc($postarray['parent-uri']), + intval($uid) ); if (count($myconv)) { @@ -1606,7 +1585,7 @@ function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray) 'to_email' => $user[0]['email'], 'uid' => $user[0]['uid'], 'item' => $postarray, - 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($top_item)), + 'link' => $a->get_baseurl() . '/display/' . urlencode(Item::getGuidById($top_item)), 'source_name' => $postarray['author-name'], 'source_link' => $postarray['author-link'], 'source_photo' => $postarray['author-avatar'], @@ -1638,8 +1617,8 @@ function twitter_fetchparentposts(App $a, $uid, $post, $connection, $self, $own_ } $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1", - dbesc("twitter::".$post->id_str), - intval($uid) + dbesc("twitter::".$post->id_str), + intval($uid) ); if (count($r)) { @@ -1657,10 +1636,11 @@ function twitter_fetchparentposts(App $a, $uid, $post, $connection, $self, $own_ foreach ($posts as $post) { $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false); - if (trim($postarray['body']) == "") + if (trim($postarray['body']) == "") { continue; + } - $item = item_store($postarray); + $item = Item::insert($postarray); $postarray["id"] = $item; logger('twitter_fetchparentpost: User ' . $self["nick"] . ' posted parent timeline item ' . $item); @@ -1689,7 +1669,6 @@ function twitter_fetchhometimeline(App $a, $uid) $application_name = $a->get_hostname(); } - require_once 'library/twitteroauth.php'; require_once 'include/items.php'; $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); @@ -1777,7 +1756,7 @@ function twitter_fetchhometimeline(App $a, $uid) continue; } - $item = item_store($postarray); + $item = Item::insert($postarray); $postarray["id"] = $item; logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item); @@ -1829,7 +1808,7 @@ function twitter_fetchhometimeline(App $a, $uid) continue; } - $item = item_store($postarray); + $item = Item::insert($postarray); $postarray["id"] = $item; if ($item && function_exists("check_item_notification")) { @@ -1851,8 +1830,9 @@ function twitter_fetchhometimeline(App $a, $uid) $item = $r[0]['id']; $parent_id = $r[0]['parent']; } - } else + } else { $parent_id = $postarray['parent']; + } if (($item != 0) && !function_exists("check_item_notification")) { require_once 'include/enotify.php'; @@ -1864,7 +1844,7 @@ function twitter_fetchhometimeline(App $a, $uid) 'to_email' => $u[0]['email'], 'uid' => $u[0]['uid'], 'item' => $postarray, - 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($item)), + 'link' => $a->get_baseurl() . '/display/' . urlencode(Item::getGuidById($item)), 'source_name' => $postarray['author-name'], 'source_link' => $postarray['author-link'], 'source_photo' => $postarray['author-avatar'], @@ -1891,8 +1871,6 @@ function twitter_fetch_own_contact(App $a, $uid) $contact_id = 0; if ($own_id == "") { - require_once 'library/twitteroauth.php'; - $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); // Fetching user data @@ -1959,9 +1937,7 @@ function twitter_is_retweet(App $a, $uid, $body) $otoken = PConfig::get($uid, 'twitter', 'oauthtoken'); $osecret = PConfig::get($uid, 'twitter', 'oauthsecret'); - require_once 'library/twitteroauth.php'; $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret); - $result = $connection->post('statuses/retweet/' . $id); logger('twitter_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);