Official Addons for the Friendica Communications Platform. (please note that this is a clone of the repository at github, issues are handled there)
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
friendica-addons/twitter/twitter.php

1899 lines
62 KiB

<?php
/**
* Name: Twitter Connector
* Description: Bidirectional (posting, relaying and reading) connector for Twitter.
* Version: 1.1.0
10 years ago
* Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
* Author: Michael Vogel <https://pirati.ca/profile/heluecht>
* Maintainer: Hypolite Petovan <https://friendica.mrpetovan.com/profile/hypolite>
10 years ago
*
* Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel, Hypolite Petovan
10 years ago
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* * copyright notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the distribution.
* * Neither the name of the <organization> nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
/* Twitter Addon for Friendica
*
* Author: Tobias Diekershoff
* tobias.diekershoff@gmx.net
*
* License:3-clause BSD license
*
* Configuration:
* To use this addon you need a OAuth Consumer key pair (key & secret)
* you can get it from Twitter at https://twitter.com/apps
*
* Register your Friendica site as "Client" application with "Read & Write" access
* we do not need "Twitter as login". When you've registered the app you get the
* OAuth Consumer key and secret pair for your application/site.
*
* Add this key pair to your global config/addon.config.php or use the admin panel.
*
* 'twitter' => [
* 'consumerkey' => '',
* 'consumersecret' => '',
* ],
*
* To activate the addon itself add it to the system.addon
* setting. After this, your user can configure their Twitter account settings
* from "Settings -> Addon Settings".
*
* Requirements: PHP5, curl
*/
use Abraham\TwitterOAuth\TwitterOAuth;
use Abraham\TwitterOAuth\TwitterOAuthException;
use Friendica\App;
use Friendica\Content\OEmbed;
use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\Plaintext;
use Friendica\Core\Config;
use Friendica\Core\Hook;
use Friendica\Core\L10n;
use Friendica\Core\Logger;
use Friendica\Core\PConfig;
use Friendica\Core\Protocol;
use Friendica\Core\Renderer;
use Friendica\Core\Worker;
use Friendica\Database\DBA;
use Friendica\Model\Contact;
use Friendica\Model\Conversation;
use Friendica\Model\Group;
use Friendica\Model\Item;
use Friendica\Model\ItemContent;
use Friendica\Model\User;
use Friendica\Object\Image;
use Friendica\Util\ConfigFileLoader;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Network;
use Friendica\Util\Strings;
require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
function twitter_install()
{
// we need some hooks, for the configuration and for sending tweets
Hook::register('load_config' , __FILE__, 'twitter_load_config');
Hook::register('connector_settings' , __FILE__, 'twitter_settings');
Hook::register('connector_settings_post', __FILE__, 'twitter_settings_post');
Hook::register('hook_fork' , __FILE__, 'twitter_hook_fork');
Hook::register('post_local' , __FILE__, 'twitter_post_local');
Hook::register('notifier_normal' , __FILE__, 'twitter_post_hook');
Hook::register('jot_networks' , __FILE__, 'twitter_jot_nets');
Hook::register('cron' , __FILE__, 'twitter_cron');
Hook::register('follow' , __FILE__, 'twitter_follow');
Hook::register('expire' , __FILE__, 'twitter_expire');
Hook::register('prepare_body' , __FILE__, 'twitter_prepare_body');
Hook::register('check_item_notification', __FILE__, 'twitter_check_item_notification');
Logger::log("installed twitter");
}
function twitter_uninstall()
{
Hook::unregister('load_config' , __FILE__, 'twitter_load_config');
Hook::unregister('connector_settings' , __FILE__, 'twitter_settings');
Hook::unregister('connector_settings_post', __FILE__, 'twitter_settings_post');
Hook::unregister('hook_fork' , __FILE__, 'twitter_hook_fork');
Hook::unregister('post_local' , __FILE__, 'twitter_post_local');
Hook::unregister('notifier_normal' , __FILE__, 'twitter_post_hook');
Hook::unregister('jot_networks' , __FILE__, 'twitter_jot_nets');
Hook::unregister('cron' , __FILE__, 'twitter_cron');
Hook::unregister('follow' , __FILE__, 'twitter_follow');
Hook::unregister('expire' , __FILE__, 'twitter_expire');
Hook::unregister('prepare_body' , __FILE__, 'twitter_prepare_body');
Hook::unregister('check_item_notification', __FILE__, 'twitter_check_item_notification');
// old setting - remove only
Hook::unregister('post_local_end' , __FILE__, 'twitter_post_hook');
Hook::unregister('addon_settings' , __FILE__, 'twitter_settings');
Hook::unregister('addon_settings_post', __FILE__, 'twitter_settings_post');
}
function twitter_load_config(App $a, ConfigFileLoader $loader)
{
$a->getConfigCache()->load($loader->loadAddonConfig('twitter'));
}
function twitter_check_item_notification(App $a, array &$notification_data)
{
$own_id = PConfig::get($notification_data["uid"], 'twitter', 'own_id');
$own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
intval($notification_data["uid"]),
DBA::escape("twitter::".$own_id)
);
if ($own_user) {
$notification_data["profiles"][] = $own_user[0]["url"];
}
}
function twitter_follow(App $a, array &$contact)
{
Logger::log("twitter_follow: Check if contact is twitter contact. " . $contact["url"], Logger::DEBUG);
if (!strstr($contact["url"], "://twitter.com") && !strstr($contact["url"], "@twitter.com")) {
return;
}
// contact seems to be a twitter contact, so continue
$nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $contact["url"]);
$nickname = str_replace("@twitter.com", "", $nickname);
$uid = $a->user["uid"];
$ckey = Config::get('twitter', 'consumerkey');
$csecret = Config::get('twitter', 'consumersecret');
$otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
$osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
// 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;
}
$connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
$connection->post('friendships/create', ['screen_name' => $nickname]);
twitter_fetchuser($a, $uid, $nickname);
$r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
FROM `contact` WHERE `uid` = %d AND `nick` = '%s'",
intval($uid),
DBA::escape($nickname));
if (DBA::isResult($r)) {
$contact["contact"] = $r[0];
}
}
function twitter_jot_nets(App $a, array &$jotnets_fields)
{
if (!local_user()) {
return;
}
if (PConfig::get(local_user(), 'twitter', 'post')) {
$jotnets_fields[] = [
'type' => 'checkbox',
'field' => [
'twitter_enable',
L10n::t('Post to Twitter'),
PConfig::get(local_user(), 'twitter', 'post_by_default')
]
];
}
}
function twitter_settings_post(App $a)
{
if (!local_user()) {
return;
}
// don't check twitter settings if twitter submit button is not clicked
if (empty($_POST['twitter-disconnect']) && empty($_POST['twitter-submit'])) {
return;
}
if (!empty($_POST['twitter-disconnect'])) {
/* * *
* if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
* from the user configuration
*/
PConfig::delete(local_user(), 'twitter', 'consumerkey');
PConfig::delete(local_user(), 'twitter', 'consumersecret');
PConfig::delete(local_user(), 'twitter', 'oauthtoken');
PConfig::delete(local_user(), 'twitter', 'oauthsecret');
PConfig::delete(local_user(), 'twitter', 'post');
PConfig::delete(local_user(), 'twitter', 'post_by_default');
PConfig::delete(local_user(), 'twitter', 'lastid');
PConfig::delete(local_user(), 'twitter', 'mirror_posts');
PConfig::delete(local_user(), 'twitter', 'import');
PConfig::delete(local_user(), 'twitter', 'create_user');
PConfig::delete(local_user(), 'twitter', 'own_id');
} else {
if (isset($_POST['twitter-pin'])) {
// if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
Logger::log('got a Twitter PIN');
$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
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());
} catch(TwitterOAuthException $e) {
info($e->getMessage());
}
// reload the Addon Settings page, if we don't do it see Bug #42
$a->internalRedirect('settings/connectors');
} else {
// if no PIN is supplied in the POST variables, the user has changed the setting
// to post a tweet for every new __public__ posting to the wall
PConfig::set(local_user(), 'twitter', 'post', intval($_POST['twitter-enable']));
PConfig::set(local_user(), 'twitter', 'post_by_default', intval($_POST['twitter-default']));
PConfig::set(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror']));
PConfig::set(local_user(), 'twitter', 'import', intval($_POST['twitter-import']));
PConfig::set(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user']));
if (!intval($_POST['twitter-mirror'])) {
PConfig::delete(local_user(), 'twitter', 'lastid');
}
info(L10n::t('Twitter settings updated.') . EOL);
}
}
}
function twitter_settings(App $a, &$s)
{
if (!local_user()) {
return;
}
$a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
/* * *
* 1) Check that we have global consumer key & secret
* 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');
$enabled = intval(PConfig::get(local_user(), 'twitter', 'post'));
$defenabled = intval(PConfig::get(local_user(), 'twitter', 'post_by_default'));
$mirrorenabled = intval(PConfig::get(local_user(), 'twitter', 'mirror_posts'));
$importenabled = intval(PConfig::get(local_user(), 'twitter', 'import'));
$create_userenabled = intval(PConfig::get(local_user(), 'twitter', 'create_user'));
$css = (($enabled) ? '' : '-disabled');
$s .= '<span id="settings_twitter_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
$s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
$s .= '</span>';
$s .= '<div id="settings_twitter_expanded" class="settings-block" style="display: none;">';
$s .= '<span class="fakelink" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
$s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
$s .= '</span>';
if ((!$ckey) && (!$csecret)) {
/* 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
if ((!$otoken) && (!$osecret)) {
/* 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);
try {
$result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
$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 .= '<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 .= '</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>';
} catch (TwitterOAuthException $e) {
$s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
}
} else {
/* * *
* we have an OAuth key / secret pair for the user
* so let's give a chance to disable the postings to Twitter
*/
$connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
try {
$details = $connection->get('account/verify_credentials');
$field_checkbox = Renderer::getMarkupTemplate('field_checkbox.tpl');
$s .= '<div id="twitter-info" >
<p>' . L10n::t('Currently connected to: ') . '<a href="https://twitter.com/' . $details->screen_name . '" target="_twitter">' . $details->screen_name . '</a>
<button type="submit" name="twitter-disconnect" value="1">' . L10n::t('Disconnect') . '</button>
</p>
<p id="twitter-info-block">
<a href="https://twitter.com/' . $details->screen_name . '" target="_twitter"><img id="twitter-avatar" src="' . $details->profile_image_url . '" /></a>
<em>' . $details->description . '</em>
</p>
</div>';
$s .= '<div class="clear"></div>';
$s .= Renderer::replaceMacros($field_checkbox, [
'$field' => ['twitter-enable', L10n::t('Allow posting to Twitter'), $enabled, L10n::t('If enabled all your <strong>public</strong> postings can be posted to the associated Twitter account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.')]
]);
if ($a->user['hidewall']) {
$s .= '<p>' . L10n::t('<strong>Note</strong>: Due to your privacy settings (<em>Hide your profile details from unknown viewers?</em>) the link potentially included in public postings relayed to Twitter will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') . '</p>';
}
$s .= Renderer::replaceMacros($field_checkbox, [
'$field' => ['twitter-default', L10n::t('Send public postings to Twitter by default'), $defenabled, '']
]);
$s .= Renderer::replaceMacros($field_checkbox, [
'$field' => ['twitter-mirror', L10n::t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '']
]);
$s .= Renderer::replaceMacros($field_checkbox, [
'$field' => ['twitter-import', L10n::t('Import the remote timeline'), $importenabled, '']
]);
$s .= Renderer::replaceMacros($field_checkbox, [
'$field' => ['twitter-create_user', L10n::t('Automatically create contacts'), $create_userenabled, L10n::t('This will automatically create a contact in Friendica as soon as you receive a message from an existing contact via the Twitter network. If you do not enable this, you need to manually add those Twitter contacts in Friendica from whom you would like to see posts here. However if enabled, you cannot merely remove a twitter contact from the Friendica contact list, as it will recreate this contact when they post again.')]
]);
$s .= '<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>';
} catch (TwitterOAuthException $e) {
$s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
}
}
}
$s .= '</div><div class="clear"></div>';
}
function twitter_hook_fork(App $a, array &$b)
{
if ($b['name'] != 'notifier_normal') {
return;
}
$post = $b['data'];
// Deleting and editing is not supported by the addon (deleting could, but isn't by now)
if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
$b['execute'] = false;
return;
}
// if post comes from twitter don't send it back
if ($post['extid'] == Protocol::TWITTER) {
$b['execute'] = false;
return;
}
if ($post['app'] == 'Twitter') {
$b['execute'] = false;
return;
}
if (PConfig::get($post['uid'], 'twitter', 'import')) {
// Don't fork if it isn't a reply to a twitter post
if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::TWITTER])) {
Logger::log('No twitter parent found for item ' . $post['id']);
$b['execute'] = false;
return;
}
} else {
// Comments are never exported when we don't import the twitter timeline
if (!strstr($post['postopts'], 'twitter') || ($post['parent'] != $post['id']) || $post['private']) {
$b['execute'] = false;
return;
}
}
}
function twitter_post_local(App $a, array &$b)
{
if ($b['edit']) {
return;
}
if (!local_user() || (local_user() != $b['uid'])) {
return;
}
$twitter_post = intval(PConfig::get(local_user(), 'twitter', 'post'));
$twitter_enable = (($twitter_post && !empty($_REQUEST['twitter_enable'])) ? intval($_REQUEST['twitter_enable']) : 0);
// if API is used, default to the chosen settings
if ($b['api_source'] && intval(PConfig::get(local_user(), 'twitter', 'post_by_default'))) {
$twitter_enable = 1;
}
if (!$twitter_enable) {
return;
}
if (strlen($b['postopts'])) {
$b['postopts'] .= ',';
}
$b['postopts'] .= 'twitter';
}
function twitter_action(App $a, $uid, $pid, $action)
{
$ckey = Config::get('twitter', 'consumerkey');
$csecret = Config::get('twitter', 'consumersecret');
$otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
$osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
$connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
$post = ['id' => $pid];
Logger::log("twitter_action '" . $action . "' ID: " . $pid . " data: " . print_r($post, true), Logger::DATA);
switch ($action) {
case "delete":
// To-Do: $result = $connection->post('statuses/destroy', $post);
$result = [];
break;
case "like":
$result = $connection->post('favorites/create', $post);
break;
case "unlike":
$result = $connection->post('favorites/destroy', $post);
break;
default:
Logger::log('Unhandled action ' . $action, Logger::DEBUG);
$result = [];
}
Logger::log("twitter_action '" . $action . "' send, result: " . print_r($result, true), Logger::DEBUG);
}
function twitter_post_hook(App $a, array &$b)
{
// Post to Twitter
if (!PConfig::get($b["uid"], 'twitter', 'import')
&& ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
return;
}
if ($b['parent'] != $b['id']) {
Logger::log("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::"))
{
Logger::log("twitter_post_hook: no twitter post " . $b["parent"]);
return;
}
$condition = ['uri' => $b["thr-parent"], 'uid' => $b["uid"]];
$orig_post = Item::selectFirst([], $condition);
if (!DBA::isResult($orig_post)) {
Logger::log("twitter_post_hook: no parent found " . $b["thr-parent"]);
return;
} else {
$iscomment = true;
}
$nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
$nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
$nicknameplain = "@" . $nicknameplain;
Logger::log("twitter_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], Logger::DEBUG);
if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
$b["body"] = $nickname . " " . $b["body"];
}
Logger::log("twitter_post_hook: parent found " . print_r($orig_post, true), Logger::DATA);
} else {
$iscomment = false;
if ($b['private'] || !strstr($b['postopts'], 'twitter')) {
return;
}
// Dont't post if the post doesn't belong to us.
// This is a check for forum postings
$self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
if ($b['contact-id'] != $self['id']) {
return;
}
}
if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
twitter_action($a, $b["uid"], substr($orig_post["uri"], 9), "delete");
}
if ($b['verb'] == ACTIVITY_LIKE) {
Logger::log("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), Logger::DEBUG);
if ($b['deleted']) {
twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike");
} else {
twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "like");
}
return;
}
if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
return;
}
// if post comes from twitter don't send it back
if ($b['extid'] == Protocol::TWITTER) {
return;
}
if ($b['app'] == "Twitter") {
return;
}
Logger::notice('twitter post invoked', ['id' => $b['id'], 'guid' => $b['guid']]);
PConfig::load($b['uid'], 'twitter');
$ckey = Config::get('twitter', 'consumerkey');
$csecret = Config::get('twitter', 'consumersecret');
$otoken = PConfig::get($b['uid'], 'twitter', 'oauthtoken');
$osecret = PConfig::get($b['uid'], 'twitter', 'oauthsecret');
if ($ckey && $csecret && $otoken && $osecret) {
Logger::log('twitter: we have customer key and oauth stuff, going to send.', Logger::DEBUG);
// If it's a repeated message from twitter then do a native retweet and exit
if (twitter_is_retweet($a, $b['uid'], $b['body'])) {
return;
}
$connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
// Set the timeout for upload to 30 seconds
$connection->setTimeouts(10, 30);
$max_char = 280;
// Handling non-native reshares
$b['body'] = Friendica\Content\Text\BBCode::convertShare(
$b['body'],
function (array $attributes, array $author_contact, $content, $is_quote_share) {
return twitter_convert_share($attributes, $author_contact, $content, $is_quote_share);
}
);
$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")) {
$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 :-)
$post = [];
if (!empty($image)) {
try {
$img_str = Network::fetchUrl($image);
$tempfile = tempnam(get_temppath(), 'cache');
file_put_contents($tempfile, $img_str);
$media = $connection->upload('media/upload', ['media' => $tempfile]);
unlink($tempfile);
if (isset($media->media_id_string)) {
$post['media_ids'] = $media->media_id_string;
} else {
throw new Exception('Failed upload of ' . $image);
}
} 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 = "";
}
}
$post['status'] = $msg;
if ($iscomment) {