3 * Name: Twitter Connector
4 * Description: Bidirectional (posting, relaying and reading) connector for Twitter.
6 * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8 * Maintainer: Hypolite Petovan <https://friendica.mrpetovan.com/profile/hypolite>
10 * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel, Hypolite Petovan
11 * All rights reserved.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions are met:
15 * * Redistributions of source code must retain the above copyright notice,
16 * this list of conditions and the following disclaimer.
17 * * Redistributions in binary form must reproduce the above
18 * * copyright notice, this list of conditions and the following disclaimer in
19 * the documentation and/or other materials provided with the distribution.
20 * * Neither the name of the <organization> nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
28 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
32 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 /* Twitter Addon for Friendica
38 * Author: Tobias Diekershoff
39 * tobias.diekershoff@gmx.net
41 * License:3-clause BSD license
44 * To use this addon you need a OAuth Consumer key pair (key & secret)
45 * you can get it from Twitter at https://twitter.com/apps
47 * Register your Friendica site as "Client" application with "Read & Write" access
48 * we do not need "Twitter as login". When you've registered the app you get the
49 * OAuth Consumer key and secret pair for your application/site.
51 * Add this key pair to your global config/addon.config.php or use the admin panel.
54 * 'consumerkey' => '',
55 * 'consumersecret' => '',
58 * To activate the addon itself add it to the system.addon
59 * setting. After this, your user can configure their Twitter account settings
60 * from "Settings -> Addon Settings".
62 * Requirements: PHP5, curl
65 use Abraham\TwitterOAuth\TwitterOAuth;
66 use Abraham\TwitterOAuth\TwitterOAuthException;
67 use Codebird\Codebird;
69 use Friendica\Content\OEmbed;
70 use Friendica\Content\Text\BBCode;
71 use Friendica\Content\Text\Plaintext;
72 use Friendica\Core\Config;
73 use Friendica\Core\Hook;
74 use Friendica\Core\L10n;
75 use Friendica\Core\Logger;
76 use Friendica\Core\PConfig;
77 use Friendica\Core\Protocol;
78 use Friendica\Core\Renderer;
79 use Friendica\Core\Worker;
80 use Friendica\Database\DBA;
81 use Friendica\Model\Contact;
82 use Friendica\Model\Conversation;
83 use Friendica\Model\Group;
84 use Friendica\Model\Item;
85 use Friendica\Model\ItemContent;
86 use Friendica\Model\User;
87 use Friendica\Object\Image;
88 use Friendica\Util\ConfigFileLoader;
89 use Friendica\Util\DateTimeFormat;
90 use Friendica\Util\Network;
91 use Friendica\Util\Strings;
93 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
95 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
97 function twitter_install()
99 // we need some hooks, for the configuration and for sending tweets
100 Hook::register('load_config' , __FILE__, 'twitter_load_config');
101 Hook::register('connector_settings' , __FILE__, 'twitter_settings');
102 Hook::register('connector_settings_post', __FILE__, 'twitter_settings_post');
103 Hook::register('hook_fork' , __FILE__, 'twitter_hook_fork');
104 Hook::register('post_local' , __FILE__, 'twitter_post_local');
105 Hook::register('notifier_normal' , __FILE__, 'twitter_post_hook');
106 Hook::register('jot_networks' , __FILE__, 'twitter_jot_nets');
107 Hook::register('cron' , __FILE__, 'twitter_cron');
108 Hook::register('follow' , __FILE__, 'twitter_follow');
109 Hook::register('expire' , __FILE__, 'twitter_expire');
110 Hook::register('prepare_body' , __FILE__, 'twitter_prepare_body');
111 Hook::register('check_item_notification', __FILE__, 'twitter_check_item_notification');
112 Logger::log("installed twitter");
115 function twitter_uninstall()
117 Hook::unregister('load_config' , __FILE__, 'twitter_load_config');
118 Hook::unregister('connector_settings' , __FILE__, 'twitter_settings');
119 Hook::unregister('connector_settings_post', __FILE__, 'twitter_settings_post');
120 Hook::unregister('hook_fork' , __FILE__, 'twitter_hook_fork');
121 Hook::unregister('post_local' , __FILE__, 'twitter_post_local');
122 Hook::unregister('notifier_normal' , __FILE__, 'twitter_post_hook');
123 Hook::unregister('jot_networks' , __FILE__, 'twitter_jot_nets');
124 Hook::unregister('cron' , __FILE__, 'twitter_cron');
125 Hook::unregister('follow' , __FILE__, 'twitter_follow');
126 Hook::unregister('expire' , __FILE__, 'twitter_expire');
127 Hook::unregister('prepare_body' , __FILE__, 'twitter_prepare_body');
128 Hook::unregister('check_item_notification', __FILE__, 'twitter_check_item_notification');
130 // old setting - remove only
131 Hook::unregister('post_local_end' , __FILE__, 'twitter_post_hook');
132 Hook::unregister('addon_settings' , __FILE__, 'twitter_settings');
133 Hook::unregister('addon_settings_post', __FILE__, 'twitter_settings_post');
136 function twitter_load_config(App $a, ConfigFileLoader $loader)
138 $a->getConfigCache()->load($loader->loadAddonConfig('twitter'));
141 function twitter_check_item_notification(App $a, array &$notification_data)
143 $own_id = PConfig::get($notification_data["uid"], 'twitter', 'own_id');
145 $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
146 intval($notification_data["uid"]),
147 DBA::escape("twitter::".$own_id)
151 $notification_data["profiles"][] = $own_user[0]["url"];
155 function twitter_follow(App $a, array &$contact)
157 Logger::log("twitter_follow: Check if contact is twitter contact. " . $contact["url"], Logger::DEBUG);
159 if (!strstr($contact["url"], "://twitter.com") && !strstr($contact["url"], "@twitter.com")) {
163 // contact seems to be a twitter contact, so continue
164 $nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $contact["url"]);
165 $nickname = str_replace("@twitter.com", "", $nickname);
167 $uid = $a->user["uid"];
169 $ckey = Config::get('twitter', 'consumerkey');
170 $csecret = Config::get('twitter', 'consumersecret');
171 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
172 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
174 // If the addon is not configured (general or for this user) quit here
175 if (empty($ckey) || empty($csecret) || empty($otoken) || empty($osecret)) {
180 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
181 $connection->post('friendships/create', ['screen_name' => $nickname]);
183 twitter_fetchuser($a, $uid, $nickname);
185 $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
186 FROM `contact` WHERE `uid` = %d AND `nick` = '%s'",
188 DBA::escape($nickname));
189 if (DBA::isResult($r)) {
190 $contact["contact"] = $r[0];
194 function twitter_jot_nets(App $a, array &$jotnets_fields)
200 if (PConfig::get(local_user(), 'twitter', 'post')) {
201 $jotnets_fields[] = [
202 'type' => 'checkbox',
205 L10n::t('Post to Twitter'),
206 PConfig::get(local_user(), 'twitter', 'post_by_default')
213 function twitter_settings_post(App $a)
218 // don't check twitter settings if twitter submit button is not clicked
219 if (empty($_POST['twitter-disconnect']) && empty($_POST['twitter-submit'])) {
223 if (!empty($_POST['twitter-disconnect'])) {
225 * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
226 * from the user configuration
228 PConfig::delete(local_user(), 'twitter', 'consumerkey');
229 PConfig::delete(local_user(), 'twitter', 'consumersecret');
230 PConfig::delete(local_user(), 'twitter', 'oauthtoken');
231 PConfig::delete(local_user(), 'twitter', 'oauthsecret');
232 PConfig::delete(local_user(), 'twitter', 'post');
233 PConfig::delete(local_user(), 'twitter', 'post_by_default');
234 PConfig::delete(local_user(), 'twitter', 'lastid');
235 PConfig::delete(local_user(), 'twitter', 'mirror_posts');
236 PConfig::delete(local_user(), 'twitter', 'import');
237 PConfig::delete(local_user(), 'twitter', 'create_user');
238 PConfig::delete(local_user(), 'twitter', 'own_id');
240 if (isset($_POST['twitter-pin'])) {
241 // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
242 Logger::log('got a Twitter PIN');
243 $ckey = Config::get('twitter', 'consumerkey');
244 $csecret = Config::get('twitter', 'consumersecret');
245 // the token and secret for which the PIN was generated were hidden in the settings
246 // form as token and token2, we need a new connection to Twitter using these token
247 // and secret to request a Access Token with the PIN
249 if (empty($_POST['twitter-pin'])) {
250 throw new Exception(L10n::t('You submitted an empty PIN, please Sign In with Twitter again to get a new one.'));
253 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
254 $token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_POST['twitter-pin']]);
255 // ok, now that we have the Access Token, save them in the user config
256 PConfig::set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
257 PConfig::set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
258 PConfig::set(local_user(), 'twitter', 'post', 1);
259 } catch(Exception $e) {
260 info($e->getMessage());
261 } catch(TwitterOAuthException $e) {
262 info($e->getMessage());
264 // reload the Addon Settings page, if we don't do it see Bug #42
265 $a->internalRedirect('settings/connectors');
267 // if no PIN is supplied in the POST variables, the user has changed the setting
268 // to post a tweet for every new __public__ posting to the wall
269 PConfig::set(local_user(), 'twitter', 'post', intval($_POST['twitter-enable']));
270 PConfig::set(local_user(), 'twitter', 'post_by_default', intval($_POST['twitter-default']));
271 PConfig::set(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror']));
272 PConfig::set(local_user(), 'twitter', 'import', intval($_POST['twitter-import']));
273 PConfig::set(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user']));
275 if (!intval($_POST['twitter-mirror'])) {
276 PConfig::delete(local_user(), 'twitter', 'lastid');
279 info(L10n::t('Twitter settings updated.') . EOL);
284 function twitter_settings(App $a, &$s)
289 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
291 * 1) Check that we have global consumer key & secret
292 * 2) If no OAuthtoken & stuff is present, generate button to get some
293 * 3) Checkbox for "Send public notices (280 chars only)
295 $ckey = Config::get('twitter', 'consumerkey');
296 $csecret = Config::get('twitter', 'consumersecret');
297 $otoken = PConfig::get(local_user(), 'twitter', 'oauthtoken');
298 $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret');
300 $enabled = intval(PConfig::get(local_user(), 'twitter', 'post'));
301 $defenabled = intval(PConfig::get(local_user(), 'twitter', 'post_by_default'));
302 $mirrorenabled = intval(PConfig::get(local_user(), 'twitter', 'mirror_posts'));
303 $importenabled = intval(PConfig::get(local_user(), 'twitter', 'import'));
304 $create_userenabled = intval(PConfig::get(local_user(), 'twitter', 'create_user'));
306 $css = (($enabled) ? '' : '-disabled');
308 $s .= '<span id="settings_twitter_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
309 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
311 $s .= '<div id="settings_twitter_expanded" class="settings-block" style="display: none;">';
312 $s .= '<span class="fakelink" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
313 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
316 if ((!$ckey) && (!$csecret)) {
317 /* no global consumer keys
318 * display warning and skip personal config
320 $s .= '<p>' . L10n::t('No consumer key pair for Twitter found. Please contact your site administrator.') . '</p>';
322 // ok we have a consumer key pair now look into the OAuth stuff
323 if ((!$otoken) && (!$osecret)) {
324 /* the user has not yet connected the account to twitter...
325 * get a temporary OAuth key/secret pair and display a button with
326 * which the user can request a PIN to connect the account to a
327 * account at Twitter.
329 $connection = new TwitterOAuth($ckey, $csecret);
331 $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
332 $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>';
333 $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>';
334 $s .= '<div id="twitter-pin-wrapper">';
335 $s .= '<label id="twitter-pin-label" for="twitter-pin">' . L10n::t('Copy the PIN from Twitter here') . '</label>';
336 $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
337 $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result['oauth_token'] . '" />';
338 $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result['oauth_token_secret'] . '" />';
339 $s .= '</div><div class="clear"></div>';
340 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
341 } catch (TwitterOAuthException $e) {
342 $s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
346 * we have an OAuth key / secret pair for the user
347 * so let's give a chance to disable the postings to Twitter
349 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
351 $details = $connection->get('account/verify_credentials');
353 $field_checkbox = Renderer::getMarkupTemplate('field_checkbox.tpl');
355 if (property_exists($details, 'screen_name') &&
356 property_exists($details, 'description') &&
357 property_exists($details, 'profile_image_url')) {
358 $s .= '<div id="twitter-info" >
359 <p>' . L10n::t('Currently connected to: ') . '<a href="https://twitter.com/' . $details->screen_name . '" target="_twitter">' . $details->screen_name . '</a>
360 <button type="submit" name="twitter-disconnect" value="1">' . L10n::t('Disconnect') . '</button>
362 <p id="twitter-info-block">
363 <a href="https://twitter.com/' . $details->screen_name . '" target="_twitter"><img id="twitter-avatar" src="' . $details->profile_image_url . '" /></a>
364 <em>' . $details->description . '</em>
368 $s .= '<div id="twitter-info" >
369 <p>Invalid Twitter info</p>
371 Logger::info('Invalid twitter info (verify credentials).', ['auth' => TwitterOAuth::class]);
373 $s .= '<div class="clear"></div>';
375 $s .= Renderer::replaceMacros($field_checkbox, [
376 '$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.')]
378 if ($a->user['hidewall']) {
379 $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>';
381 $s .= Renderer::replaceMacros($field_checkbox, [
382 '$field' => ['twitter-default', L10n::t('Send public postings to Twitter by default'), $defenabled, '']
384 $s .= Renderer::replaceMacros($field_checkbox, [
385 '$field' => ['twitter-mirror', L10n::t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '']
387 $s .= Renderer::replaceMacros($field_checkbox, [
388 '$field' => ['twitter-import', L10n::t('Import the remote timeline'), $importenabled, '']
390 $s .= Renderer::replaceMacros($field_checkbox, [
391 '$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.')]
393 $s .= '<div class="clear"></div>';
394 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
395 } catch (TwitterOAuthException $e) {
396 $s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
400 $s .= '</div><div class="clear"></div>';
403 function twitter_hook_fork(App $a, array &$b)
405 if ($b['name'] != 'notifier_normal') {
411 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
412 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
413 $b['execute'] = false;
417 // if post comes from twitter don't send it back
418 if ($post['extid'] == Protocol::TWITTER) {
419 $b['execute'] = false;
423 if ($post['app'] == 'Twitter') {
424 $b['execute'] = false;
428 if (PConfig::get($post['uid'], 'twitter', 'import')) {
429 // Don't fork if it isn't a reply to a twitter post
430 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::TWITTER])) {
431 Logger::log('No twitter parent found for item ' . $post['id']);
432 $b['execute'] = false;
436 // Comments are never exported when we don't import the twitter timeline
437 if (!strstr($post['postopts'], 'twitter') || ($post['parent'] != $post['id']) || $post['private']) {
438 $b['execute'] = false;
444 function twitter_post_local(App $a, array &$b)
450 if (!local_user() || (local_user() != $b['uid'])) {
454 $twitter_post = intval(PConfig::get(local_user(), 'twitter', 'post'));
455 $twitter_enable = (($twitter_post && !empty($_REQUEST['twitter_enable'])) ? intval($_REQUEST['twitter_enable']) : 0);
457 // if API is used, default to the chosen settings
458 if ($b['api_source'] && intval(PConfig::get(local_user(), 'twitter', 'post_by_default'))) {
462 if (!$twitter_enable) {
466 if (strlen($b['postopts'])) {
467 $b['postopts'] .= ',';
470 $b['postopts'] .= 'twitter';
473 function twitter_action(App $a, $uid, $pid, $action)
475 $ckey = Config::get('twitter', 'consumerkey');
476 $csecret = Config::get('twitter', 'consumersecret');
477 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
478 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
480 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
482 $post = ['id' => $pid];
484 Logger::log("twitter_action '" . $action . "' ID: " . $pid . " data: " . print_r($post, true), Logger::DATA);
488 // To-Do: $result = $connection->post('statuses/destroy', $post);
492 $result = $connection->post('favorites/create', $post);
495 $result = $connection->post('favorites/destroy', $post);
498 Logger::log('Unhandled action ' . $action, Logger::DEBUG);
501 Logger::log("twitter_action '" . $action . "' send, result: " . print_r($result, true), Logger::DEBUG);
504 function twitter_post_hook(App $a, array &$b)
507 if (!PConfig::get($b["uid"], 'twitter', 'import')
508 && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
512 if ($b['parent'] != $b['id']) {
513 Logger::log("twitter_post_hook: parameter " . print_r($b, true), Logger::DATA);
515 // Looking if its a reply to a twitter post
516 if ((substr($b["parent-uri"], 0, 9) != "twitter::")
517 && (substr($b["extid"], 0, 9) != "twitter::")
518 && (substr($b["thr-parent"], 0, 9) != "twitter::"))
520 Logger::log("twitter_post_hook: no twitter post " . $b["parent"]);
524 $condition = ['uri' => $b["thr-parent"], 'uid' => $b["uid"]];
525 $orig_post = Item::selectFirst([], $condition);
526 if (!DBA::isResult($orig_post)) {
527 Logger::log("twitter_post_hook: no parent found " . $b["thr-parent"]);
534 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
535 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
536 $nicknameplain = "@" . $nicknameplain;
538 Logger::log("twitter_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], Logger::DEBUG);
539 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
540 $b["body"] = $nickname . " " . $b["body"];
543 Logger::log("twitter_post_hook: parent found " . print_r($orig_post, true), Logger::DATA);
547 if ($b['private'] || !strstr($b['postopts'], 'twitter')) {
551 // Dont't post if the post doesn't belong to us.
552 // This is a check for forum postings
553 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
554 if ($b['contact-id'] != $self['id']) {
559 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
560 twitter_action($a, $b["uid"], substr($orig_post["uri"], 9), "delete");
563 if ($b['verb'] == ACTIVITY_LIKE) {
564 Logger::log("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), Logger::DEBUG);
566 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike");
568 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "like");
574 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
578 // if post comes from twitter don't send it back
579 if ($b['extid'] == Protocol::TWITTER) {
583 if ($b['app'] == "Twitter") {
587 Logger::notice('twitter post invoked', ['id' => $b['id'], 'guid' => $b['guid']]);
589 PConfig::load($b['uid'], 'twitter');
591 $ckey = Config::get('twitter', 'consumerkey');
592 $csecret = Config::get('twitter', 'consumersecret');
593 $otoken = PConfig::get($b['uid'], 'twitter', 'oauthtoken');
594 $osecret = PConfig::get($b['uid'], 'twitter', 'oauthsecret');
596 if ($ckey && $csecret && $otoken && $osecret) {
597 Logger::log('twitter: we have customer key and oauth stuff, going to send.', Logger::DEBUG);
599 // If it's a repeated message from twitter then do a native retweet and exit
600 if (twitter_is_retweet($a, $b['uid'], $b['body'])) {
604 Codebird::setConsumerKey($ckey, $csecret);
605 $cb = Codebird::getInstance();
606 $cb->setToken($otoken, $osecret);
608 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
610 // Set the timeout for upload to 30 seconds
611 $connection->setTimeouts(10, 30);
615 // Handling non-native reshares
616 $b['body'] = Friendica\Content\Text\BBCode::convertShare(
618 function (array $attributes, array $author_contact, $content, $is_quote_share) {
619 return twitter_convert_share($attributes, $author_contact, $content, $is_quote_share);
623 $b['body'] = twitter_update_mentions($b['body']);
625 $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 8);
626 Logger::info('Got plaintext', $msgarr);
627 $msg = $msgarr["text"];
629 if (($msg == "") && isset($msgarr["title"])) {
630 $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
633 if (($msgarr['url'] == $b['plink']) && !empty($msgarr['images']) && (count($msgarr['images']) <= 4)) {
635 } elseif (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
636 $msg .= "\n" . $msgarr["url"];
646 // and now tweet it :-)
649 if (!empty($msgarr['images'])) {
652 foreach ($msgarr['images'] as $image) {
653 if (count($media_ids) == 4) {
657 $img_str = Network::fetchUrl($image['url']);
659 $tempfile = tempnam(get_temppath(), 'cache');
660 file_put_contents($tempfile, $img_str);
662 $media = $connection->upload('media/upload', ['media' => $tempfile]);
666 if (isset($media->media_id_string)) {
667 $media_ids[] = $media->media_id_string;
669 if (!empty($image['description'])) {
670 $data = ['media_id' => $media->media_id_string,
671 'alt_text' => ['text' => substr($image['description'], 0, 420)]];
672 $ret = $cb->media_metadata_create($data);
673 Logger::info('Metadata create', ['data' => $data, 'return' => json_encode($ret)]);
676 throw new Exception('Failed upload of ' . $image['url']);
679 $post['media_ids'] = implode(',', $media_ids);
680 if (empty($post['media_ids'])) {
681 unset($post['media_ids']);
683 } catch (Exception $e) {
684 Logger::log('Exception when trying to send to Twitter: ' . $e->getMessage());
688 $post['status'] = $msg;
691 $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
694 $url = 'statuses/update';
695 $result = $connection->post($url, $post);
696 Logger::log('twitter_post send, result: ' . print_r($result, true), Logger::DEBUG);
698 if (!empty($result->source)) {
699 Config::set("twitter", "application_name", strip_tags($result->source));
702 if (!empty($result->errors)) {
703 Logger::log('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
705 } elseif ($iscomment) {
706 Logger::log('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']);
707 Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]);
712 function twitter_addon_admin_post(App $a)
714 $consumerkey = !empty($_POST['consumerkey']) ? Strings::escapeTags(trim($_POST['consumerkey'])) : '';
715 $consumersecret = !empty($_POST['consumersecret']) ? Strings::escapeTags(trim($_POST['consumersecret'])) : '';
716 Config::set('twitter', 'consumerkey', $consumerkey);
717 Config::set('twitter', 'consumersecret', $consumersecret);
718 info(L10n::t('Settings updated.') . EOL);
721 function twitter_addon_admin(App $a, &$o)
723 $t = Renderer::getMarkupTemplate("admin.tpl", "addon/twitter/");
725 $o = Renderer::replaceMacros($t, [
726 '$submit' => L10n::t('Save Settings'),
727 // name, label, value, help, [extra values]
728 '$consumerkey' => ['consumerkey', L10n::t('Consumer key'), Config::get('twitter', 'consumerkey'), ''],
729 '$consumersecret' => ['consumersecret', L10n::t('Consumer secret'), Config::get('twitter', 'consumersecret'), ''],
733 function twitter_cron(App $a)
735 $last = Config::get('twitter', 'last_poll');
737 $poll_interval = intval(Config::get('twitter', 'poll_interval'));
738 if (!$poll_interval) {
739 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
743 $next = $last + ($poll_interval * 60);
744 if ($next > time()) {
745 Logger::log('twitter: poll intervall not reached');
749 Logger::log('twitter: cron_start');
751 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1'");
752 if (DBA::isResult($r)) {
753 foreach ($r as $rr) {
754 Logger::log('twitter: fetching for user ' . $rr['uid']);
755 Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], "addon/twitter/twitter_sync.php", 1, (int) $rr['uid']);
759 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
760 if ($abandon_days < 1) {
764 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
766 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1'");
767 if (DBA::isResult($r)) {
768 foreach ($r as $rr) {
769 if ($abandon_days != 0) {
770 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
771 if (!DBA::isResult($user)) {
772 Logger::log('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
777 Logger::log('twitter: importing timeline from user ' . $rr['uid']);
778 Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], "addon/twitter/twitter_sync.php", 2, (int) $rr['uid']);
781 // check for new contacts once a day
782 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
783 if($last_contact_check)
784 $next_contact_check = $last_contact_check + 86400;
786 $next_contact_check = 0;
788 if($next_contact_check <= time()) {
789 pumpio_getallusers($a, $rr["uid"]);
790 PConfig::set($rr['uid'],'pumpio','contact_check',time());
796 Logger::log('twitter: cron_end');
798 Config::set('twitter', 'last_poll', time());
801 function twitter_expire(App $a)
803 $days = Config::get('twitter', 'expire');
809 $r = Item::select(['id'], ['deleted' => true, 'network' => Protocol::TWITTER]);
810 while ($row = DBA::fetch($r)) {
811 DBA::delete('item', ['id' => $row['id']]);
815 Logger::log('twitter_expire: expire_start');
817 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
818 if (DBA::isResult($r)) {
819 foreach ($r as $rr) {
820 Logger::log('twitter_expire: user ' . $rr['uid']);
821 Item::expire($rr['uid'], $days, Protocol::TWITTER, true);
825 Logger::log('twitter_expire: expire_end');
828 function twitter_prepare_body(App $a, array &$b)
830 if ($b["item"]["network"] != Protocol::TWITTER) {
837 $item["plink"] = $a->getBaseURL() . "/display/" . $item["guid"];
839 $condition = ['uri' => $item["thr-parent"], 'uid' => local_user()];
840 $orig_post = Item::selectFirst(['author-link'], $condition);
841 if (DBA::isResult($orig_post)) {
842 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
843 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
844 $nicknameplain = "@" . $nicknameplain;
846 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
847 $item["body"] = $nickname . " " . $item["body"];
851 $msgarr = ItemContent::getPlaintextPost($item, $max_char, true, 8);
852 $msg = $msgarr["text"];
854 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
855 $msg .= " " . $msgarr["url"];
858 if (isset($msgarr["image"])) {
859 $msg .= " " . $msgarr["image"];
862 $b['html'] = nl2br(htmlspecialchars($msg));
867 * @brief Build the item array for the mirrored post
869 * @param App $a Application class
870 * @param integer $uid User id
871 * @param object $post Twitter object with the post
873 * @return array item data to be posted
875 function twitter_do_mirrorpost(App $a, $uid, $post)
877 $datarray['api_source'] = true;
878 $datarray['profile_uid'] = $uid;
879 $datarray['extid'] = Protocol::TWITTER;
880 $datarray['message_id'] = Item::newURI($uid, Protocol::TWITTER . ':' . $post->id);
881 $datarray['protocol'] = Conversation::PARCEL_TWITTER;
882 $datarray['source'] = json_encode($post);
883 $datarray['title'] = '';
885 if (!empty($post->retweeted_status)) {
886 // We don't support nested shares, so we mustn't show quotes as shares on retweets
887 $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true);
889 if (empty($item['body'])) {
893 $datarray['body'] = "\n" . share_header(
894 $item['author-name'],
895 $item['author-link'],
896 $item['author-avatar'],
902 $datarray['body'] .= $item['body'] . '[/share]';
904 $item = twitter_createpost($a, $uid, $post, ['id' => 0], false, false, false);
906 if (empty($item['body'])) {
910 $datarray['body'] = $item['body'];
913 $datarray['source'] = $item['app'];
914 $datarray['verb'] = $item['verb'];
916 if (isset($item['location'])) {
917 $datarray['location'] = $item['location'];
920 if (isset($item['coord'])) {
921 $datarray['coord'] = $item['coord'];
927 function twitter_fetchtimeline(App $a, $uid)
929 $ckey = Config::get('twitter', 'consumerkey');
930 $csecret = Config::get('twitter', 'consumersecret');
931 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
932 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
933 $lastid = PConfig::get($uid, 'twitter', 'lastid');
935 $application_name = Config::get('twitter', 'application_name');
937 if ($application_name == "") {
938 $application_name = $a->getHostName();
941 $has_picture = false;
943 require_once 'mod/item.php';
944 require_once 'mod/share.php';
946 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
948 $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended", "include_ext_alt_text" => true];
950 $first_time = ($lastid == "");
953 $parameters["since_id"] = $lastid;
957 $items = $connection->get('statuses/user_timeline', $parameters);
958 } catch (TwitterOAuthException $e) {
959 Logger::log('Error fetching timeline for user ' . $uid . ': ' . $e->getMessage());
963 if (!is_array($items)) {
964 Logger::log('No items for user ' . $uid, Logger::INFO);
968 $posts = array_reverse($items);
970 Logger::log('Starting from ID ' . $lastid . ' for user ' . $uid, Logger::DEBUG);
973 foreach ($posts as $post) {
974 if ($post->id_str > $lastid) {
975 $lastid = $post->id_str;
976 PConfig::set($uid, 'twitter', 'lastid', $lastid);
983 if (!stristr($post->source, $application_name)) {
984 $_SESSION["authenticated"] = true;
985 $_SESSION["uid"] = $uid;
987 Logger::log('Preparing Twitter ID ' . $post->id_str . ' for user ' . $uid, Logger::DEBUG);
989 $_REQUEST = twitter_do_mirrorpost($a, $uid, $post);
991 if (empty($_REQUEST['body'])) {
995 Logger::log('Posting Twitter ID ' . $post->id_str . ' for user ' . $uid);
1001 PConfig::set($uid, 'twitter', 'lastid', $lastid);
1002 Logger::log('Last ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
1005 function twitter_fix_avatar($avatar)
1007 $new_avatar = str_replace("_normal.", ".", $avatar);
1009 $info = Image::getInfoFromURL($new_avatar);
1011 $new_avatar = $avatar;
1017 function twitter_fetch_contact($uid, $data, $create_user)
1019 if (empty($data->id_str)) {
1023 $avatar = twitter_fix_avatar($data->profile_image_url_https);
1024 $url = "https://twitter.com/" . $data->screen_name;
1025 $addr = $data->screen_name . "@twitter.com";
1027 $fields = ['url' => $url, 'network' => Protocol::TWITTER,
1028 'name' => $data->name, 'nick' => $data->screen_name, 'addr' => $addr,
1029 'location' => $data->location, 'about' => $data->description];
1031 $cid = Contact::getIdForURL($url, 0, true, $fields);
1033 DBA::update('contact', $fields, ['id' => $cid]);
1034 Contact::updateAvatar($avatar, 0, $cid);
1037 $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'alias' => "twitter::" . $data->id_str]);
1038 if (!DBA::isResult($contact) && !$create_user) {
1042 if (!DBA::isResult($contact)) {
1043 // create contact record
1044 $fields['uid'] = $uid;
1045 $fields['created'] = DateTimeFormat::utcNow();
1046 $fields['nurl'] = Strings::normaliseLink($url);
1047 $fields['alias'] = 'twitter::' . $data->id_str;
1048 $fields['poll'] = 'twitter::' . $data->id_str;
1049 $fields['rel'] = Contact::FRIEND;
1050 $fields['priority'] = 1;
1051 $fields['writable'] = true;
1052 $fields['blocked'] = false;
1053 $fields['readonly'] = false;
1054 $fields['pending'] = false;
1056 if (!DBA::insert('contact', $fields)) {
1060 $contact_id = DBA::lastInsertId();
1062 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1064 Contact::updateAvatar($avatar, $uid, $contact_id);
1066 if ($contact["readonly"] || $contact["blocked"]) {
1067 Logger::log("twitter_fetch_contact: Contact '" . $contact["nick"] . "' is blocked or readonly.", Logger::DEBUG);
1071 $contact_id = $contact['id'];
1073 // update profile photos once every twelve hours as we have no notification of when they change.
1074 $update_photo = ($contact['avatar-date'] < DateTimeFormat::utc('now -12 hours'));
1076 // check that we have all the photos, this has been known to fail on occasion
1077 if (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']) || $update_photo) {
1078 Logger::log("twitter_fetch_contact: Updating contact " . $data->screen_name, Logger::DEBUG);
1080 Contact::updateAvatar($avatar, $uid, $contact['id']);
1082 $fields['name-date'] = DateTimeFormat::utcNow();
1083 $fields['uri-date'] = DateTimeFormat::utcNow();
1085 DBA::update('contact', $fields, ['id' => $contact['id']]);
1092 function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1094 $ckey = Config::get('twitter', 'consumerkey');
1095 $csecret = Config::get('twitter', 'consumersecret');
1096 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1097 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1099 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1102 if (DBA::isResult($r)) {
1110 if ($screen_name != "") {
1111 $parameters["screen_name"] = $screen_name;
1114 if ($user_id != "") {
1115 $parameters["user_id"] = $user_id;
1118 // Fetching user data
1119 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1121 $user = $connection->get('users/show', $parameters);
1122 } catch (TwitterOAuthException $e) {
1123 Logger::log('twitter_fetchuser: Error fetching user ' . $uid . ': ' . $e->getMessage());
1127 if (!is_object($user)) {
1131 $contact_id = twitter_fetch_contact($uid, $user, true);
1136 function twitter_expand_entities(App $a, $body, $item, $picture)
1142 foreach ($item->entities->hashtags AS $hashtag) {
1143 $url = '#[url=' . $a->getBaseURL() . '/search?tag=' . $hashtag->text . ']' . $hashtag->text . '[/url]';
1144 $tags_arr['#' . $hashtag->text] = $url;
1145 $body = str_replace('#' . $hashtag->text, $url, $body);
1148 foreach ($item->entities->user_mentions AS $mention) {
1149 $url = '@[url=https://twitter.com/' . rawurlencode($mention->screen_name) . ']' . $mention->screen_name . '[/url]';
1150 $tags_arr['@' . $mention->screen_name] = $url;
1151 $body = str_replace('@' . $mention->screen_name, $url, $body);
1154 if (isset($item->entities->urls)) {
1160 foreach ($item->entities->urls as $url) {
1161 $plain = str_replace($url->url, '', $plain);
1163 if ($url->url && $url->expanded_url && $url->display_url) {
1164 // Quote tweet, we just remove the quoted tweet URL from the body, the share block will be added later.
1165 if (isset($item->quoted_status_id_str)
1166 && substr($url->expanded_url, -strlen($item->quoted_status_id_str)) == $item->quoted_status_id_str ) {
1167 $body = str_replace($url->url, '', $body);
1171 $expanded_url = $url->expanded_url;
1173 $final_url = Network::finalUrl($url->expanded_url);
1175 $oembed_data = OEmbed::fetchURL($final_url);
1177 if (empty($oembed_data) || empty($oembed_data->type)) {
1181 // Quickfix: Workaround for URL with '[' and ']' in it
1182 if (strpos($expanded_url, '[') || strpos($expanded_url, ']')) {
1183 $expanded_url = $url->url;
1187 $type = $oembed_data->type;
1190 if ($oembed_data->type == 'video') {
1191 $type = $oembed_data->type;
1192 $footerurl = $expanded_url;
1193 $footerlink = '[url=' . $expanded_url . ']' . $url->display_url . '[/url]';
1195 $body = str_replace($url->url, $footerlink, $body);
1196 } elseif (($oembed_data->type == 'photo') && isset($oembed_data->url)) {
1197 $body = str_replace($url->url, '[url=' . $expanded_url . '][img]' . $oembed_data->url . '[/img][/url]', $body);
1198 } elseif ($oembed_data->type != 'link') {
1199 $body = str_replace($url->url, '[url=' . $expanded_url . ']' . $url->display_url . '[/url]', $body);
1201 $img_str = Network::fetchUrl($final_url, true, 4);
1203 $tempfile = tempnam(get_temppath(), 'cache');
1204 file_put_contents($tempfile, $img_str);
1206 // See http://php.net/manual/en/function.exif-imagetype.php#79283
1207 if (filesize($tempfile) > 11) {
1208 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1215 if (substr($mime, 0, 6) == 'image/') {
1217 $body = str_replace($url->url, '[img]' . $final_url . '[/img]', $body);
1219 $type = $oembed_data->type;
1220 $footerurl = $expanded_url;
1221 $footerlink = '[url=' . $expanded_url . ']' . $url->display_url . '[/url]';
1223 $body = str_replace($url->url, $footerlink, $body);
1229 // Footer will be taken care of with a share block in the case of a quote
1230 if (empty($item->quoted_status)) {
1231 if ($footerurl != '') {
1232 $footer = add_page_info($footerurl, false, $picture);
1235 if (($footerlink != '') && (trim($footer) != '')) {
1236 $removedlink = trim(str_replace($footerlink, '', $body));
1238 if (($removedlink == '') || strstr($body, $removedlink)) {
1239 $body = $removedlink;
1245 if ($footer == '' && $picture != '') {
1246 $body .= "\n\n[img]" . $picture . "[/img]\n";
1247 } elseif ($footer == '' && $picture == '') {
1248 $body = add_page_info_to_body($body);
1253 // it seems as if the entities aren't always covering all mentions. So the rest will be checked here
1254 $tags = BBCode::getTags($body);
1257 foreach ($tags as $tag) {
1258 if (strstr(trim($tag), ' ')) {
1262 if (strpos($tag, '#') === 0) {
1263 if (strpos($tag, '[url=')) {
1267 // don't link tags that are already embedded in links
1268 if (preg_match('/\[(.*?)' . preg_quote($tag, '/') . '(.*?)\]/', $body)) {
1271 if (preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag, '/') . '(.*?)\)/', $body)) {
1275 $basetag = str_replace('_', ' ', substr($tag, 1));
1276 $url = '#[url=' . $a->getBaseURL() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
1277 $body = str_replace($tag, $url, $body);
1278 $tags_arr['#' . $basetag] = $url;
1279 } elseif (strpos($tag, '@') === 0) {
1280 if (strpos($tag, '[url=')) {
1284 $basetag = substr($tag, 1);
1285 $url = '@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1286 $body = str_replace($tag, $url, $body);
1287 $tags_arr['@' . $basetag] = $url;
1292 $tags = implode($tags_arr, ',');
1294 return ['body' => $body, 'tags' => $tags, 'plain' => $plain];
1298 * @brief Fetch media entities and add media links to the body
1300 * @param object $post Twitter object with the post
1301 * @param array $postarray Array of the item that is about to be posted
1303 * @return $picture string Image URL or empty string
1305 function twitter_media_entities($post, array &$postarray)
1307 // There are no media entities? So we quit.
1308 if (empty($post->extended_entities->media)) {
1312 // When the post links to an external page, we only take one picture.
1313 // We only do this when there is exactly one media.
1314 if ((count($post->entities->urls) > 0) && (count($post->extended_entities->media) == 1)) {
1315 $medium = $post->extended_entities->media[0];
1317 foreach ($post->entities->urls as $link) {
1318 // Let's make sure the external link url matches the media url
1319 if ($medium->url == $link->url && isset($medium->media_url_https)) {
1320 $picture = $medium->media_url_https;
1321 $postarray['body'] = str_replace($medium->url, '', $postarray['body']);
1327 // This is a pure media post, first search for all media urls
1329 foreach ($post->extended_entities->media AS $medium) {
1330 if (!isset($media[$medium->url])) {
1331 $media[$medium->url] = '';
1333 switch ($medium->type) {
1335 if (!empty($medium->ext_alt_text)) {
1336 Logger::info('Got text description', ['alt_text' => $medium->ext_alt_text]);
1337 $media[$medium->url] .= "\n[img=" . $medium->media_url_https .']' . $medium->ext_alt_text . '[/img]';
1339 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
1342 $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
1345 case 'animated_gif':
1346 if (!empty($medium->ext_alt_text)) {
1347 Logger::info('Got text description', ['alt_text' => $medium->ext_alt_text]);
1348 $media[$medium->url] .= "\n[img=" . $medium->media_url_https .']' . $medium->ext_alt_text . '[/img]';
1350 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
1353 $postarray['object-type'] = ACTIVITY_OBJ_VIDEO;
1354 if (is_array($medium->video_info->variants)) {
1356 // We take the video with the highest bitrate
1357 foreach ($medium->video_info->variants AS $variant) {
1358 if (($variant->content_type == 'video/mp4') && ($variant->bitrate >= $bitrate)) {
1359 $media[$medium->url] = "\n[video]" . $variant->url . '[/video]';
1360 $bitrate = $variant->bitrate;
1365 // The following code will only be activated for test reasons
1367 // $postarray['body'] .= print_r($medium, true);
1371 // Now we replace the media urls.
1372 foreach ($media AS $key => $value) {
1373 $postarray['body'] = str_replace($key, "\n" . $value . "\n", $postarray['body']);
1379 function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $only_existing_contact, $noquote)
1382 $postarray['network'] = Protocol::TWITTER;
1383 $postarray['uid'] = $uid;
1384 $postarray['wall'] = 0;
1385 $postarray['uri'] = "twitter::" . $post->id_str;
1386 $postarray['protocol'] = Conversation::PARCEL_TWITTER;
1387 $postarray['source'] = json_encode($post);
1389 // Don't import our own comments
1390 if (Item::exists(['extid' => $postarray['uri'], 'uid' => $uid])) {
1391 Logger::log("Item with extid " . $postarray['uri'] . " found.", Logger::DEBUG);
1397 if ($post->in_reply_to_status_id_str != "") {
1398 $parent = "twitter::" . $post->in_reply_to_status_id_str;
1400 $fields = ['uri', 'parent-uri', 'parent'];
1401 $parent_item = Item::selectFirst($fields, ['uri' => $parent, 'uid' => $uid]);
1402 if (!DBA::isResult($parent_item)) {
1403 $parent_item = Item::selectFirst($fields, ['extid' => $parent, 'uid' => $uid]);
1406 if (DBA::isResult($parent_item)) {
1407 $postarray['thr-parent'] = $parent_item['uri'];
1408 $postarray['parent-uri'] = $parent_item['parent-uri'];
1409 $postarray['parent'] = $parent_item['parent'];
1410 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1412 $postarray['thr-parent'] = $postarray['uri'];
1413 $postarray['parent-uri'] = $postarray['uri'];
1414 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1418 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1420 if ($post->user->id_str == $own_id) {
1421 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1424 if (DBA::isResult($r)) {
1425 $contactid = $r[0]["id"];
1427 $postarray['owner-name'] = $r[0]["name"];
1428 $postarray['owner-link'] = $r[0]["url"];
1429 $postarray['owner-avatar'] = $r[0]["photo"];
1431 Logger::log("No self contact for user " . $uid, Logger::DEBUG);
1435 // Don't create accounts of people who just comment something
1436 $create_user = false;
1438 $postarray['parent-uri'] = $postarray['uri'];
1439 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1442 if ($contactid == 0) {
1443 $contactid = twitter_fetch_contact($uid, $post->user, $create_user);
1445 $postarray['owner-name'] = $post->user->name;
1446 $postarray['owner-link'] = "https://twitter.com/" . $post->user->screen_name;
1447 $postarray['owner-avatar'] = twitter_fix_avatar($post->user->profile_image_url_https);
1450 if (($contactid == 0) && !$only_existing_contact) {
1451 $contactid = $self['id'];
1452 } elseif ($contactid <= 0) {
1453 Logger::log("Contact ID is zero or less than zero.", Logger::DEBUG);
1457 $postarray['contact-id'] = $contactid;
1459 $postarray['verb'] = ACTIVITY_POST;
1460 $postarray['author-name'] = $postarray['owner-name'];
1461 $postarray['author-link'] = $postarray['owner-link'];
1462 $postarray['author-avatar'] = $postarray['owner-avatar'];
1463 $postarray['plink'] = "https://twitter.com/" . $post->user->screen_name . "/status/" . $post->id_str;
1464 $postarray['app'] = strip_tags($post->source);
1466 if ($post->user->protected) {
1467 $postarray['private'] = 1;
1468 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1470 $postarray['private'] = 0;
1471 $postarray['allow_cid'] = '';
1474 if (!empty($post->full_text)) {
1475 $postarray['body'] = $post->full_text;
1477 $postarray['body'] = $post->text;
1480 // When the post contains links then use the correct object type
1481 if (count($post->entities->urls) > 0) {
1482 $postarray['object-type'] = ACTIVITY_OBJ_BOOKMARK;
1485 // Search for media links
1486 $picture = twitter_media_entities($post, $postarray);
1488 $converted = twitter_expand_entities($a, $postarray['body'], $post, $picture);
1489 $postarray['body'] = $converted["body"];
1490 $postarray['tag'] = $converted["tags"];
1491 $postarray['created'] = DateTimeFormat::utc($post->created_at);
1492 $postarray['edited'] = DateTimeFormat::utc($post->created_at);
1494 $statustext = $converted["plain"];
1496 if (!empty($post->place->name)) {
1497 $postarray["location"] = $post->place->name;
1499 if (!empty($post->place->full_name)) {
1500 $postarray["location"] = $post->place->full_name;
1502 if (!empty($post->geo->coordinates)) {
1503 $postarray["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
1505 if (!empty($post->coordinates->coordinates)) {
1506 $postarray["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
1508 if (!empty($post->retweeted_status)) {
1509 $retweet = twitter_createpost($a, $uid, $post->retweeted_status, $self, false, false, $noquote);
1511 if (empty($retweet['body'])) {
1516 // Store the original tweet
1517 Item::insert($retweet);
1519 // CHange the other post into a reshare activity
1520 $postarray['verb'] = ACTIVITY2_ANNOUNCE;
1521 $postarray['gravity'] = GRAVITY_ACTIVITY;
1522 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1524 $postarray['thr-parent'] = $retweet['uri'];
1525 $postarray['parent-uri'] = $retweet['uri'];
1527 $retweet['source'] = $postarray['source'];
1528 $retweet['private'] = $postarray['private'];
1529 $retweet['allow_cid'] = $postarray['allow_cid'];
1530 $retweet['contact-id'] = $postarray['contact-id'];
1531 $retweet['owner-name'] = $postarray['owner-name'];
1532 $retweet['owner-link'] = $postarray['owner-link'];
1533 $retweet['owner-avatar'] = $postarray['owner-avatar'];
1535 $postarray = $retweet;
1539 if (!empty($post->quoted_status) && !$noquote) {
1540 $quoted = twitter_createpost($a, $uid, $post->quoted_status, $self, false, false, true);
1542 if (empty($quoted['body'])) {
1546 $postarray['body'] .= "\n" . share_header(
1547 $quoted['author-name'],
1548 $quoted['author-link'],
1549 $quoted['author-avatar'],
1555 $postarray['body'] .= $quoted['body'] . '[/share]';
1561 function twitter_fetchparentposts(App $a, $uid, $post, TwitterOAuth $connection, array $self)
1563 Logger::log("twitter_fetchparentposts: Fetching for user " . $uid . " and post " . $post->id_str, Logger::DEBUG);
1567 while (!empty($post->in_reply_to_status_id_str)) {
1568 $parameters = ["trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str, "include_ext_alt_text" => true];
1571 $post = $connection->get('statuses/show', $parameters);
1572 } catch (TwitterOAuthException $e) {
1573 Logger::log('twitter_fetchparentposts: Error fetching for user ' . $uid . ' and post ' . $post->id_str . ': ' . $e->getMessage());
1578 Logger::log("twitter_fetchparentposts: Can't fetch post " . $parameters['id'], Logger::DEBUG);
1582 if (empty($post->id_str)) {
1583 Logger::log("twitter_fetchparentposts: This is not a post " . json_encode($post), Logger::DEBUG);
1587 if (Item::exists(['uri' => 'twitter::' . $post->id_str, 'uid' => $uid])) {
1594 Logger::log("twitter_fetchparentposts: Fetching " . count($posts) . " parents", Logger::DEBUG);
1596 $posts = array_reverse($posts);
1598 if (!empty($posts)) {
1599 foreach ($posts as $post) {
1600 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1602 if (empty($postarray['body'])) {
1606 $item = Item::insert($postarray);
1608 $postarray["id"] = $item;
1610 Logger::log('twitter_fetchparentpost: User ' . $self["nick"] . ' posted parent timeline item ' . $item);
1615 function twitter_fetchhometimeline(App $a, $uid)
1617 $ckey = Config::get('twitter', 'consumerkey');
1618 $csecret = Config::get('twitter', 'consumersecret');
1619 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1620 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1621 $create_user = PConfig::get($uid, 'twitter', 'create_user');
1622 $mirror_posts = PConfig::get($uid, 'twitter', 'mirror_posts');
1624 Logger::log("Fetching timeline for user " . $uid, Logger::DEBUG);
1626 $application_name = Config::get('twitter', 'application_name');
1628 if ($application_name == "") {
1629 $application_name = $a->getHostName();
1632 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1635 $own_contact = twitter_fetch_own_contact($a, $uid);
1636 } catch (TwitterOAuthException $e) {
1637 Logger::log('Error fetching own contact for user ' . $uid . ': ' . $e->getMessage());
1641 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1642 intval($own_contact),
1645 if (DBA::isResult($r)) {
1646 $own_id = $r[0]["nick"];
1648 Logger::log("Own twitter contact not found for user " . $uid);
1652 $self = User::getOwnerDataById($uid);
1653 if ($self === false) {
1654 Logger::log("Own contact not found for user " . $uid);
1658 $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended", "include_ext_alt_text" => true];
1659 //$parameters["count"] = 200;
1660 // Fetching timeline
1661 $lastid = PConfig::get($uid, 'twitter', 'lasthometimelineid');
1663 $first_time = ($lastid == "");
1665 if ($lastid != "") {
1666 $parameters["since_id"] = $lastid;
1670 $items = $connection->get('statuses/home_timeline', $parameters);
1671 } catch (TwitterOAuthException $e) {
1672 Logger::log('Error fetching home timeline for user ' . $uid . ': ' . $e->getMessage());
1676 if (!is_array($items)) {
1677 Logger::log('No array while fetching home timeline for user ' . $uid . ': ' . print_r($items, true));
1681 if (empty($items)) {
1682 Logger::log('No new timeline content for user ' . $uid, Logger::INFO);
1686 $posts = array_reverse($items);
1688 Logger::log('Fetching timeline from ID ' . $lastid . ' for user ' . $uid . ' ' . sizeof($posts) . ' items', Logger::DEBUG);
1690 if (count($posts)) {
1691 foreach ($posts as $post) {
1692 if ($post->id_str > $lastid) {
1693 $lastid = $post->id_str;
1694 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1701 if (stristr($post->source, $application_name) && $post->user->screen_name == $own_id) {
1702 Logger::log("Skip previously sent post", Logger::DEBUG);
1706 if ($mirror_posts && $post->user->screen_name == $own_id && $post->in_reply_to_status_id_str == "") {
1707 Logger::log("Skip post that will be mirrored", Logger::DEBUG);
1711 if ($post->in_reply_to_status_id_str != "") {
1712 twitter_fetchparentposts($a, $uid, $post, $connection, $self);
1715 Logger::log('Preparing post ' . $post->id_str . ' for user ' . $uid, Logger::DEBUG);
1717 $postarray = twitter_createpost($a, $uid, $post, $self, $create_user, true, false);
1719 if (empty($postarray['body']) || trim($postarray['body']) == "") {
1720 Logger::log('Empty body for post ' . $post->id_str . ' and user ' . $uid, Logger::DEBUG);
1726 if (($postarray['uri'] == $postarray['parent-uri']) && ($postarray['author-link'] == $postarray['owner-link'])) {
1727 $contact = DBA::selectFirst('contact', [], ['id' => $postarray['contact-id'], 'self' => false]);
1728 if (DBA::isResult($contact)) {
1729 $notify = Item::isRemoteSelf($contact, $postarray);
1733 $item = Item::insert($postarray, false, $notify);
1734 $postarray["id"] = $item;
1736 Logger::log('User ' . $uid . ' posted home timeline item ' . $item);
1739 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1741 Logger::log('Last timeline ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
1743 // Fetching mentions
1744 $lastid = PConfig::get($uid, 'twitter', 'lastmentionid');
1746 $first_time = ($lastid == "");
1748 if ($lastid != "") {
1749 $parameters["since_id"] = $lastid;
1753 $items = $connection->get('statuses/mentions_timeline', $parameters);
1754 } catch (TwitterOAuthException $e) {
1755 Logger::log('Error fetching mentions: ' . $e->getMessage());
1759 if (!is_array($items)) {
1760 Logger::log("Error fetching mentions: " . print_r($items, true), Logger::DEBUG);
1764 $posts = array_reverse($items);
1766 Logger::log("Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", Logger::DEBUG);
1768 if (count($posts)) {
1769 foreach ($posts as $post) {
1770 if ($post->id_str > $lastid) {
1771 $lastid = $post->id_str;
1778 if ($post->in_reply_to_status_id_str != "") {
1779 twitter_fetchparentposts($a, $uid, $post, $connection, $self);
1782 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1784 if (empty($postarray['body'])) {
1788 $item = Item::insert($postarray);
1790 Logger::log('User ' . $uid . ' posted mention timeline item ' . $item);
1794 PConfig::set($uid, 'twitter', 'lastmentionid', $lastid);
1796 Logger::log('Last mentions ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
1799 function twitter_fetch_own_contact(App $a, $uid)
1801 $ckey = Config::get('twitter', 'consumerkey');
1802 $csecret = Config::get('twitter', 'consumersecret');
1803 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1804 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1806 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1810 if ($own_id == "") {
1811 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1813 // Fetching user data
1814 // get() may throw TwitterOAuthException, but we will catch it later
1815 $user = $connection->get('account/verify_credentials');
1816 if (empty($user) || empty($user->id_str)) {
1820 PConfig::set($uid, 'twitter', 'own_id', $user->id_str);
1822 $contact_id = twitter_fetch_contact($uid, $user, true);
1824 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1826 DBA::escape("twitter::" . $own_id));
1827 if (DBA::isResult($r)) {
1828 $contact_id = $r[0]["id"];
1830 PConfig::delete($uid, 'twitter', 'own_id');
1837 function twitter_is_retweet(App $a, $uid, $body)
1839 $body = trim($body);
1841 // Skip if it isn't a pure repeated messages
1842 // Does it start with a share?
1843 if (strpos($body, "[share") > 0) {
1847 // Does it end with a share?
1848 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1852 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1853 // Skip if there is no shared message in there
1854 if ($body == $attributes) {
1859 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1860 if (!empty($matches[1])) {
1861 $link = $matches[1];
1864 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1865 if (!empty($matches[1])) {
1866 $link = $matches[1];
1869 $id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link);
1874 Logger::log('twitter_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, Logger::DEBUG);
1876 $ckey = Config::get('twitter', 'consumerkey');
1877 $csecret = Config::get('twitter', 'consumersecret');
1878 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1879 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1881 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1882 $result = $connection->post('statuses/retweet/' . $id);
1884 Logger::log('twitter_is_retweet: result ' . print_r($result, true), Logger::DEBUG);
1886 return !isset($result->errors);
1889 function twitter_update_mentions($body)
1891 $URLSearchString = "^\[\]";
1892 $return = preg_replace_callback(
1893 "/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1894 function ($matches) {
1895 if (strpos($matches[1], 'twitter.com')) {
1896 $return = '@' . substr($matches[1], strrpos($matches[1], '/') + 1);
1898 $return = $matches[2] . ' (' . $matches[1] . ')';
1909 function twitter_convert_share(array $attributes, array $author_contact, $content, $is_quote_share)
1911 if ($author_contact['network'] == Protocol::TWITTER) {
1912 $mention = '@' . $author_contact['nick'];
1914 $mention = $author_contact['addr'];
1917 return ($is_quote_share ? "\n\n" : '' ) . 'RT ' . $mention . ': ' . $content . "\n\n" . $attributes['link'];