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\Text\BBCode;
70 use Friendica\Content\Text\Plaintext;
71 use Friendica\Core\Hook;
72 use Friendica\Core\Logger;
73 use Friendica\Core\Protocol;
74 use Friendica\Core\Renderer;
75 use Friendica\Core\Worker;
76 use Friendica\Database\DBA;
78 use Friendica\Model\Contact;
79 use Friendica\Model\Conversation;
80 use Friendica\Model\Group;
81 use Friendica\Model\Item;
82 use Friendica\Model\ItemURI;
83 use Friendica\Model\Post;
84 use Friendica\Model\Tag;
85 use Friendica\Model\User;
86 use Friendica\Protocol\Activity;
87 use Friendica\Util\ConfigFileLoader;
88 use Friendica\Util\DateTimeFormat;
89 use Friendica\Util\Images;
90 use Friendica\Util\Strings;
92 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
94 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
96 function twitter_install()
98 // we need some hooks, for the configuration and for sending tweets
99 Hook::register('load_config' , __FILE__, 'twitter_load_config');
100 Hook::register('connector_settings' , __FILE__, 'twitter_settings');
101 Hook::register('connector_settings_post', __FILE__, 'twitter_settings_post');
102 Hook::register('hook_fork' , __FILE__, 'twitter_hook_fork');
103 Hook::register('post_local' , __FILE__, 'twitter_post_local');
104 Hook::register('notifier_normal' , __FILE__, 'twitter_post_hook');
105 Hook::register('jot_networks' , __FILE__, 'twitter_jot_nets');
106 Hook::register('cron' , __FILE__, 'twitter_cron');
107 Hook::register('support_follow' , __FILE__, 'twitter_support_follow');
108 Hook::register('follow' , __FILE__, 'twitter_follow');
109 Hook::register('unfollow' , __FILE__, 'twitter_unfollow');
110 Hook::register('block' , __FILE__, 'twitter_block');
111 Hook::register('unblock' , __FILE__, 'twitter_unblock');
112 Hook::register('expire' , __FILE__, 'twitter_expire');
113 Hook::register('prepare_body' , __FILE__, 'twitter_prepare_body');
114 Hook::register('check_item_notification', __FILE__, 'twitter_check_item_notification');
115 Hook::register('probe_detect' , __FILE__, 'twitter_probe_detect');
116 Hook::register('parse_link' , __FILE__, 'twitter_parse_link');
117 Logger::info("installed twitter");
122 function twitter_load_config(App $a, ConfigFileLoader $loader)
124 $a->getConfigCache()->load($loader->loadAddonConfig('twitter'));
127 function twitter_check_item_notification(App $a, array &$notification_data)
129 $own_id = DI::pConfig()->get($notification_data['uid'], 'twitter', 'own_id');
131 $own_user = Contact::selectFirst(['url'], ['uid' => $notification_data['uid'], 'alias' => 'twitter::'.$own_id]);
133 $notification_data['profiles'][] = $own_user['url'];
137 function twitter_support_follow(App $a, array &$data)
139 if ($data['protocol'] == Protocol::TWITTER) {
140 $data['result'] = true;
144 function twitter_follow(App $a, array &$contact)
146 Logger::info('Check if contact is twitter contact', ['url' => $contact["url"]]);
148 if (!strstr($contact["url"], "://twitter.com") && !strstr($contact["url"], "@twitter.com")) {
152 // contact seems to be a twitter contact, so continue
153 $nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $contact["url"]);
154 $nickname = str_replace("@twitter.com", "", $nickname);
156 $uid = $a->getLoggedInUserId();
158 twitter_api_contact('friendships/create', ['network' => Protocol::TWITTER, 'nick' => $nickname], $uid);
160 $user = twitter_fetchuser($nickname);
162 $contact_id = twitter_fetch_contact($uid, $user, true);
164 $contact = Contact::getById($contact_id, ['name', 'nick', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'photo', 'priority', 'network', 'alias', 'pubkey']);
166 if (DBA::isResult($contact)) {
167 $contact["contact"] = $contact;
171 function twitter_unfollow(App $a, array &$hook_data)
173 $hook_data['result'] = twitter_api_contact('friendships/destroy', $hook_data['contact'], $hook_data['contact']['uid']);
176 function twitter_block(App $a, array &$hook_data)
178 $hook_data['result'] = twitter_api_contact('blocks/create', $hook_data['contact'], $hook_data['uid']);
180 if ($hook_data['result'] === true) {
181 Contact::removeFollower($hook_data['contact']);
182 Contact::unfollow($hook_data['contact']['id'], $hook_data['uid']);
186 function twitter_unblock(App $a, array &$hook_data)
188 $hook_data['result'] = twitter_api_contact('blocks/destroy', $hook_data['contact'], $hook_data['uid']);
191 function twitter_api_contact(string $apiPath, array $contact, int $uid): ?bool
193 if ($contact['network'] !== Protocol::TWITTER) {
197 return twitter_api_call($uid, $apiPath, ['screen_name' => $contact['nick']]);
200 function twitter_jot_nets(App $a, array &$jotnets_fields)
206 if (DI::pConfig()->get(local_user(), 'twitter', 'post')) {
207 $jotnets_fields[] = [
208 'type' => 'checkbox',
211 DI::l10n()->t('Post to Twitter'),
212 DI::pConfig()->get(local_user(), 'twitter', 'post_by_default')
219 function twitter_settings_post(App $a)
224 // don't check twitter settings if twitter submit button is not clicked
225 if (empty($_POST['twitter-disconnect']) && empty($_POST['twitter-submit'])) {
229 if (!empty($_POST['twitter-disconnect'])) {
231 * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
232 * from the user configuration
234 DI::pConfig()->delete(local_user(), 'twitter', 'consumerkey');
235 DI::pConfig()->delete(local_user(), 'twitter', 'consumersecret');
236 DI::pConfig()->delete(local_user(), 'twitter', 'oauthtoken');
237 DI::pConfig()->delete(local_user(), 'twitter', 'oauthsecret');
238 DI::pConfig()->delete(local_user(), 'twitter', 'post');
239 DI::pConfig()->delete(local_user(), 'twitter', 'post_by_default');
240 DI::pConfig()->delete(local_user(), 'twitter', 'lastid');
241 DI::pConfig()->delete(local_user(), 'twitter', 'mirror_posts');
242 DI::pConfig()->delete(local_user(), 'twitter', 'import');
243 DI::pConfig()->delete(local_user(), 'twitter', 'create_user');
244 DI::pConfig()->delete(local_user(), 'twitter', 'own_id');
246 if (isset($_POST['twitter-pin'])) {
247 // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
248 Logger::notice('got a Twitter PIN');
249 $ckey = DI::config()->get('twitter', 'consumerkey');
250 $csecret = DI::config()->get('twitter', 'consumersecret');
251 // the token and secret for which the PIN was generated were hidden in the settings
252 // form as token and token2, we need a new connection to Twitter using these token
253 // and secret to request a Access Token with the PIN
255 if (empty($_POST['twitter-pin'])) {
256 throw new Exception(DI::l10n()->t('You submitted an empty PIN, please Sign In with Twitter again to get a new one.'));
259 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
260 $token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_POST['twitter-pin']]);
261 // ok, now that we have the Access Token, save them in the user config
262 DI::pConfig()->set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
263 DI::pConfig()->set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
264 DI::pConfig()->set(local_user(), 'twitter', 'post', 1);
265 } catch(Exception $e) {
266 notice($e->getMessage());
267 } catch(TwitterOAuthException $e) {
268 notice($e->getMessage());
270 // reload the Addon Settings page, if we don't do it see Bug #42
271 DI::baseUrl()->redirect('settings/connectors');
273 // if no PIN is supplied in the POST variables, the user has changed the setting
274 // to post a tweet for every new __public__ posting to the wall
275 DI::pConfig()->set(local_user(), 'twitter', 'post', intval($_POST['twitter-enable']));
276 DI::pConfig()->set(local_user(), 'twitter', 'post_by_default', intval($_POST['twitter-default']));
277 DI::pConfig()->set(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror']));
278 DI::pConfig()->set(local_user(), 'twitter', 'import', intval($_POST['twitter-import']));
279 DI::pConfig()->set(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user']));
281 if (!intval($_POST['twitter-mirror'])) {
282 DI::pConfig()->delete(local_user(), 'twitter', 'lastid');
288 function twitter_settings(App $a, &$s)
294 $user = User::getById(local_user());
296 DI::page()['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . DI::baseUrl()->get() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
298 * 1) Check that we have global consumer key & secret
299 * 2) If no OAuthtoken & stuff is present, generate button to get some
300 * 3) Checkbox for "Send public notices (280 chars only)
302 $ckey = DI::config()->get('twitter', 'consumerkey');
303 $csecret = DI::config()->get('twitter', 'consumersecret');
304 $otoken = DI::pConfig()->get(local_user(), 'twitter', 'oauthtoken');
305 $osecret = DI::pConfig()->get(local_user(), 'twitter', 'oauthsecret');
307 $enabled = intval(DI::pConfig()->get(local_user(), 'twitter', 'post'));
308 $defenabled = intval(DI::pConfig()->get(local_user(), 'twitter', 'post_by_default'));
309 $mirrorenabled = intval(DI::pConfig()->get(local_user(), 'twitter', 'mirror_posts'));
310 $importenabled = intval(DI::pConfig()->get(local_user(), 'twitter', 'import'));
311 $create_userenabled = intval(DI::pConfig()->get(local_user(), 'twitter', 'create_user'));
313 $css = (($enabled) ? '' : '-disabled');
315 $s .= '<span id="settings_twitter_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
316 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . DI::l10n()->t('Twitter Import/Export/Mirror') . '</h3>';
318 $s .= '<div id="settings_twitter_expanded" class="settings-block" style="display: none;">';
319 $s .= '<span class="fakelink" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
320 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . DI::l10n()->t('Twitter Import/Export/Mirror') . '</h3>';
323 if ((!$ckey) && (!$csecret)) {
324 /* no global consumer keys
325 * display warning and skip personal config
327 $s .= '<p>' . DI::l10n()->t('No consumer key pair for Twitter found. Please contact your site administrator.') . '</p>';
329 // ok we have a consumer key pair now look into the OAuth stuff
330 if ((!$otoken) && (!$osecret)) {
331 /* the user has not yet connected the account to twitter...
332 * get a temporary OAuth key/secret pair and display a button with
333 * which the user can request a PIN to connect the account to a
334 * account at Twitter.
336 $connection = new TwitterOAuth($ckey, $csecret);
338 $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
339 $s .= '<p>' . DI::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>';
340 $s .= '<a href="' . $connection->url('oauth/authorize', ['oauth_token' => $result['oauth_token']]) . '" target="_twitter"><img src="addon/twitter/lighter.png" alt="' . DI::l10n()->t('Log in with Twitter') . '"></a>';
341 $s .= '<div id="twitter-pin-wrapper">';
342 $s .= '<label id="twitter-pin-label" for="twitter-pin">' . DI::l10n()->t('Copy the PIN from Twitter here') . '</label>';
343 $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
344 $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result['oauth_token'] . '" />';
345 $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result['oauth_token_secret'] . '" />';
346 $s .= '</div><div class="clear"></div>';
347 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div>';
348 } catch (TwitterOAuthException $e) {
349 $s .= '<p>' . DI::l10n()->t('An error occured: ') . $e->getMessage() . '</p>';
353 * we have an OAuth key / secret pair for the user
354 * so let's give a chance to disable the postings to Twitter
356 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
358 $details = $connection->get('account/verify_credentials');
360 $field_checkbox = Renderer::getMarkupTemplate('field_checkbox.tpl');
362 if (property_exists($details, 'screen_name') &&
363 property_exists($details, 'description') &&
364 property_exists($details, 'profile_image_url')) {
365 $s .= '<div id="twitter-info" >
366 <p>' . DI::l10n()->t('Currently connected to: ') . '<a href="https://twitter.com/' . $details->screen_name . '" target="_twitter">' . $details->screen_name . '</a>
367 <button type="submit" name="twitter-disconnect" value="1">' . DI::l10n()->t('Disconnect') . '</button>
369 <p id="twitter-info-block">
370 <a href="https://twitter.com/' . $details->screen_name . '" target="_twitter"><img id="twitter-avatar" src="' . $details->profile_image_url . '" /></a>
371 <em>' . $details->description . '</em>
375 $s .= '<div id="twitter-info" >
376 <p>Invalid Twitter info</p>
377 <button type="submit" name="twitter-disconnect" value="1">' . DI::l10n()->t('Disconnect') . '</button>
379 Logger::notice('Invalid twitter info (verify credentials).', ['auth' => TwitterOAuth::class]);
381 $s .= '<div class="clear"></div>';
383 $s .= Renderer::replaceMacros($field_checkbox, [
384 '$field' => ['twitter-enable', DI::l10n()->t('Allow posting to Twitter'), $enabled, DI::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.')]
386 if ($user['hidewall']) {
387 $s .= '<p>' . DI::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>';
389 $s .= Renderer::replaceMacros($field_checkbox, [
390 '$field' => ['twitter-default', DI::l10n()->t('Send public postings to Twitter by default'), $defenabled, '']
392 $s .= Renderer::replaceMacros($field_checkbox, [
393 '$field' => ['twitter-mirror', DI::l10n()->t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '']
395 $s .= Renderer::replaceMacros($field_checkbox, [
396 '$field' => ['twitter-import', DI::l10n()->t('Import the remote timeline'), $importenabled, '']
398 $s .= Renderer::replaceMacros($field_checkbox, [
399 '$field' => ['twitter-create_user', DI::l10n()->t('Automatically create contacts'), $create_userenabled, DI::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.')]
401 $s .= '<div class="clear"></div>';
402 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . DI::l10n()->t('Save Settings') . '" /></div>';
403 } catch (TwitterOAuthException $e) {
404 $s .= '<p>' . DI::l10n()->t('An error occured: ') . $e->getMessage() . '</p>';
408 $s .= '</div><div class="clear"></div>';
411 function twitter_hook_fork(App $a, array &$b)
413 if ($b['name'] != 'notifier_normal') {
419 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
420 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
421 $b['execute'] = false;
425 // if post comes from twitter don't send it back
426 if (($post['extid'] == Protocol::TWITTER) || twitter_get_id($post['extid'])) {
427 $b['execute'] = false;
431 if (substr($post['app'], 0, 7) == 'Twitter') {
432 $b['execute'] = false;
436 if (DI::pConfig()->get($post['uid'], 'twitter', 'import')) {
437 // Don't fork if it isn't a reply to a twitter post
438 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::TWITTER])) {
439 Logger::notice('No twitter parent found', ['item' => $post['id']]);
440 $b['execute'] = false;
444 // Comments are never exported when we don't import the twitter timeline
445 if (!strstr($post['postopts'], 'twitter') || ($post['parent'] != $post['id']) || $post['private']) {
446 $b['execute'] = false;
452 function twitter_post_local(App $a, array &$b)
458 if (!local_user() || (local_user() != $b['uid'])) {
462 $twitter_post = intval(DI::pConfig()->get(local_user(), 'twitter', 'post'));
463 $twitter_enable = (($twitter_post && !empty($_REQUEST['twitter_enable'])) ? intval($_REQUEST['twitter_enable']) : 0);
465 // if API is used, default to the chosen settings
466 if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'twitter', 'post_by_default'))) {
470 if (!$twitter_enable) {
474 if (strlen($b['postopts'])) {
475 $b['postopts'] .= ',';
478 $b['postopts'] .= 'twitter';
481 function twitter_probe_detect(App $a, array &$hookData)
483 // Don't overwrite an existing result
484 if ($hookData['result']) {
488 // Avoid a lookup for the wrong network
489 if (!in_array($hookData['network'], ['', Protocol::TWITTER])) {
493 if (preg_match('=([^@]+)@(?:mobile\.)?twitter\.com$=i', $hookData['uri'], $matches)) {
495 } elseif (preg_match('=^https?://(?:mobile\.)?twitter\.com/(.+)=i', $hookData['uri'], $matches)) {
501 $user = twitter_fetchuser($nick);
504 $hookData['result'] = twitter_user_to_contact($user);
508 function twitter_api_post(string $apiPath, string $pid, int $uid): ?bool
514 return twitter_api_call($uid, $apiPath, ['id' => $pid]);
517 function twitter_api_call(int $uid, string $apiPath, array $parameters = []): ?bool
519 $ckey = DI::config()->get('twitter', 'consumerkey');
520 $csecret = DI::config()->get('twitter', 'consumersecret');
521 $otoken = DI::pConfig()->get($uid, 'twitter', 'oauthtoken');
522 $osecret = DI::pConfig()->get($uid, 'twitter', 'oauthsecret');
524 // If the addon is not configured (general or for this user) quit here
525 if (empty($ckey) || empty($csecret) || empty($otoken) || empty($osecret)) {
530 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
531 $result = $connection->post($apiPath, $parameters);
533 if ($connection->getLastHttpCode() != 200) {
534 throw new Exception($result->errors[0]->message ?? json_encode($result), $connection->getLastHttpCode());
537 if (!empty($result->errors)) {
538 throw new Exception($result->errors[0]->message, $result->errors[0]->code);
541 Logger::info('[twitter] API call successful', ['apiPath' => $apiPath, 'parameters' => $parameters]);
542 Logger::debug('[twitter] API call result', ['apiPath' => $apiPath, 'parameters' => $parameters, 'result' => $result]);
545 } catch (TwitterOAuthException $twitterOAuthException) {
546 Logger::warning('Unable to communicate with twitter', ['apiPath' => $apiPath, 'parameters' => $parameters, 'code' => $twitterOAuthException->getCode(), 'exception' => $twitterOAuthException]);
548 } catch (Exception $e) {
549 Logger::notice('[twitter] API call failed', ['apiPath' => $apiPath, 'parameters' => $parameters, 'code' => $e->getCode(), 'message' => $e->getMessage()]);
554 function twitter_get_id(string $uri)
556 if ((substr($uri, 0, 9) != 'twitter::') || (strlen($uri) <= 9)) {
560 $id = substr($uri, 9);
561 if (!is_numeric($id)) {
568 function twitter_post_hook(App $a, array &$b)
571 if (!DI::pConfig()->get($b["uid"], 'twitter', 'import')
572 && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
576 $b['body'] = Post\Media::addAttachmentsToBody($b['uri-id'], $b['body']);
580 if ($b['parent'] != $b['id']) {
581 Logger::debug('Got comment', ['item' => $b]);
583 // Looking if its a reply to a twitter post
584 if (!twitter_get_id($b["parent-uri"]) &&
585 !twitter_get_id($b["extid"]) &&
586 !twitter_get_id($b["thr-parent"])) {
587 Logger::info('No twitter post', ['parent' => $b["parent"]]);
591 $condition = ['uri' => $b["thr-parent"], 'uid' => $b["uid"]];
592 $thr_parent = Post::selectFirst(['uri', 'extid', 'author-link', 'author-nick', 'author-network'], $condition);
593 if (!DBA::isResult($thr_parent)) {
594 Logger::warning('No parent found', ['thr-parent' => $b["thr-parent"]]);
598 if ($thr_parent['author-network'] == Protocol::TWITTER) {
599 $nickname = '@[url=' . $thr_parent['author-link'] . ']' . $thr_parent['author-nick'] . '[/url]';
600 $nicknameplain = '@' . $thr_parent['author-nick'];
602 Logger::info('Comparing', ['nickname' => $nickname, 'nicknameplain' => $nicknameplain, 'body' => $b["body"]]);
603 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
604 $b["body"] = $nickname . " " . $b["body"];
608 Logger::debug('Parent found', ['parent' => $thr_parent]);
610 if ($b['private'] || !strstr($b['postopts'], 'twitter')) {
614 // Dont't post if the post doesn't belong to us.
615 // This is a check for forum postings
616 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
617 if ($b['contact-id'] != $self['id']) {
623 * @TODO This can't work at the moment:
624 * - Posts created on Friendica and mirrored to Twitter don't have a Twitter ID
625 * - Posts created on Twitter and mirrored on Friendica do not trigger the notifier hook this is part of.
627 //if (($b['verb'] == Activity::POST) && $b['deleted']) {
628 // twitter_api_post('statuses/destroy', twitter_get_id($thr_parent['uri']), $b['uid']);
631 if ($b['verb'] == Activity::LIKE) {
632 Logger::info('Like', ['uid' => $b['uid'], 'id' => twitter_get_id($b["thr-parent"])]);
634 twitter_api_post($b['deleted'] ? 'favorites/destroy' : 'favorites/create', twitter_get_id($b["thr-parent"]), $b["uid"]);
639 if ($b['verb'] == Activity::ANNOUNCE) {
640 Logger::info('Retweet', ['uid' => $b['uid'], 'id' => twitter_get_id($b["thr-parent"])]);
643 * @TODO This can't work at the moment:
644 * - Twitter post reshare removal doesn't seem to trigger the notifier hook this is part of
646 //twitter_api_post('statuses/destroy', twitter_get_id($thr_parent['extid']), $b['uid']);
648 twitter_retweet($b["uid"], twitter_get_id($b["thr-parent"]));
654 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
658 // if post comes from twitter don't send it back
659 if (($b['extid'] == Protocol::TWITTER) || twitter_get_id($b['extid'])) {
663 if ($b['app'] == "Twitter") {
667 Logger::notice('twitter post invoked', ['id' => $b['id'], 'guid' => $b['guid']]);
669 DI::pConfig()->load($b['uid'], 'twitter');
671 $ckey = DI::config()->get('twitter', 'consumerkey');
672 $csecret = DI::config()->get('twitter', 'consumersecret');
673 $otoken = DI::pConfig()->get($b['uid'], 'twitter', 'oauthtoken');
674 $osecret = DI::pConfig()->get($b['uid'], 'twitter', 'oauthsecret');
676 if ($ckey && $csecret && $otoken && $osecret) {
677 Logger::info('We have customer key and oauth stuff, going to send.');
679 // If it's a repeated message from twitter then do a native retweet and exit
680 if (twitter_is_retweet($a, $b['uid'], $b['body'])) {
684 Codebird::setConsumerKey($ckey, $csecret);
685 $cb = Codebird::getInstance();
686 $cb->setToken($otoken, $osecret);
688 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
690 // Set the timeout for upload to 30 seconds
691 $connection->setTimeouts(10, 30);
695 // Handling non-native reshares
696 $b['body'] = Friendica\Content\Text\BBCode::convertShare(
698 function (array $attributes, array $author_contact, $content, $is_quote_share) {
699 return twitter_convert_share($attributes, $author_contact, $content, $is_quote_share);
703 $b['body'] = twitter_update_mentions($b['body']);
705 $msgarr = Plaintext::getPost($b, $max_char, true, BBCode::TWITTER);
706 Logger::info('Got plaintext', ['id' => $b['id'], 'message' => $msgarr]);
707 $msg = $msgarr["text"];
709 if (($msg == "") && isset($msgarr["title"])) {
710 $msg = Plaintext::shorten($msgarr["title"], $max_char - 50, $b['uid']);
713 // Add the link to the body if the type isn't a photo or there are more than 4 images in the post
714 if (!empty($msgarr['url']) && (strpos($msg, $msgarr['url']) === false) && (($msgarr['type'] != 'photo') || empty($msgarr['images']) || (count($msgarr['images']) > 4))) {
715 $msg .= "\n" . $msgarr['url'];
719 Logger::notice('Empty message', ['id' => $b['id']]);
723 // and now tweet it :-)
726 if (!empty($msgarr['images'])) {
727 Logger::info('Got images', ['id' => $b['id'], 'images' => $msgarr['images']]);
730 foreach ($msgarr['images'] as $image) {
731 if (count($media_ids) == 4) {
735 $img_str = DI::httpClient()->fetch($image['url']);
737 $tempfile = tempnam(get_temppath(), 'cache');
738 file_put_contents($tempfile, $img_str);
740 Logger::info('Uploading', ['id' => $b['id'], 'image' => $image['url']]);
741 $media = $connection->upload('media/upload', ['media' => $tempfile]);
745 if (isset($media->media_id_string)) {
746 $media_ids[] = $media->media_id_string;
748 if (!empty($image['description'])) {
749 $data = ['media_id' => $media->media_id_string,
750 'alt_text' => ['text' => substr($image['description'], 0, 420)]];
751 $ret = $cb->media_metadata_create($data);
752 Logger::info('Metadata create', ['id' => $b['id'], 'data' => $data, 'return' => $ret]);
755 Logger::error('Failed upload', ['id' => $b['id'], 'image' => $image['url'], 'return' => $media]);
756 throw new Exception('Failed upload of ' . $image['url']);
759 $post['media_ids'] = implode(',', $media_ids);
760 if (empty($post['media_ids'])) {
761 unset($post['media_ids']);
763 } catch (Exception $e) {
764 Logger::warning('Exception when trying to send to Twitter', ['id' => $b['id'], 'message' => $e->getMessage()]);
768 $post['status'] = $msg;
771 $post['in_reply_to_status_id'] = twitter_get_id($thr_parent['uri']);
774 $result = $connection->post('statuses/update', $post);
775 Logger::info('twitter_post send', ['id' => $b['id'], 'result' => $result]);
777 if (!empty($result->source)) {
778 DI::config()->set("twitter", "application_name", strip_tags($result->source));
781 if (!empty($result->errors)) {
782 Logger::error('Send to Twitter failed', ['id' => $b['id'], 'error' => $result->errors]);
784 } elseif ($thr_parent) {
785 Logger::notice('Post send, updating extid', ['id' => $b['id'], 'extid' => $result->id_str]);
786 Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]);
791 function twitter_addon_admin_post(App $a)
793 $consumerkey = !empty($_POST['consumerkey']) ? Strings::escapeTags(trim($_POST['consumerkey'])) : '';
794 $consumersecret = !empty($_POST['consumersecret']) ? Strings::escapeTags(trim($_POST['consumersecret'])) : '';
795 DI::config()->set('twitter', 'consumerkey', $consumerkey);
796 DI::config()->set('twitter', 'consumersecret', $consumersecret);
799 function twitter_addon_admin(App $a, &$o)
801 $t = Renderer::getMarkupTemplate("admin.tpl", "addon/twitter/");
803 $o = Renderer::replaceMacros($t, [
804 '$submit' => DI::l10n()->t('Save Settings'),
805 // name, label, value, help, [extra values]
806 '$consumerkey' => ['consumerkey', DI::l10n()->t('Consumer key'), DI::config()->get('twitter', 'consumerkey'), ''],
807 '$consumersecret' => ['consumersecret', DI::l10n()->t('Consumer secret'), DI::config()->get('twitter', 'consumersecret'), ''],
811 function twitter_cron(App $a)
813 $last = DI::config()->get('twitter', 'last_poll');
815 $poll_interval = intval(DI::config()->get('twitter', 'poll_interval'));
816 if (!$poll_interval) {
817 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
821 $next = $last + ($poll_interval * 60);
822 if ($next > time()) {
823 Logger::notice('twitter: poll intervall not reached');
827 Logger::notice('twitter: cron_start');
829 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'twitter', 'k' => 'mirror_posts', 'v' => true]);
830 foreach ($pconfigs as $rr) {
831 Logger::notice('Fetching', ['user' => $rr['uid']]);
832 Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], "addon/twitter/twitter_sync.php", 1, (int) $rr['uid']);
835 $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
836 if ($abandon_days < 1) {
840 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
842 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'twitter', 'k' => 'import', 'v' => true]);
843 foreach ($pconfigs as $rr) {
844 if ($abandon_days != 0) {
845 if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $rr['uid'], $abandon_limit])) {
846 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $rr['uid']]);
851 Logger::notice('importing timeline', ['user' => $rr['uid']]);
852 Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], "addon/twitter/twitter_sync.php", 2, (int) $rr['uid']);
855 // check for new contacts once a day
856 $last_contact_check = DI::pConfig()->get($rr['uid'],'pumpio','contact_check');
857 if($last_contact_check)
858 $next_contact_check = $last_contact_check + 86400;
860 $next_contact_check = 0;
862 if($next_contact_check <= time()) {
863 pumpio_getallusers($a, $rr["uid"]);
864 DI::pConfig()->set($rr['uid'],'pumpio','contact_check',time());
869 Logger::notice('twitter: cron_end');
871 DI::config()->set('twitter', 'last_poll', time());
874 function twitter_expire(App $a)
876 $days = DI::config()->get('twitter', 'expire');
882 Logger::notice('Start deleting expired posts');
884 $r = Post::select(['id', 'guid'], ['deleted' => true, 'network' => Protocol::TWITTER]);
885 while ($row = Post::fetch($r)) {
886 Logger::info('[twitter] Delete expired item', ['id' => $row['id'], 'guid' => $row['guid'], 'callstack' => \Friendica\Core\System::callstack()]);
887 Item::markForDeletionById($row['id']);
891 Logger::notice('End deleting expired posts');
893 Logger::notice('Start expiry');
895 $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'twitter', 'k' => 'import', 'v' => true]);
896 foreach ($pconfigs as $rr) {
897 Logger::notice('twitter_expire', ['user' => $rr['uid']]);
898 Item::expire($rr['uid'], $days, Protocol::TWITTER, true);
901 Logger::notice('End expiry');
904 function twitter_prepare_body(App $a, array &$b)
906 if ($b["item"]["network"] != Protocol::TWITTER) {
913 $item["plink"] = DI::baseUrl()->get() . "/display/" . $item["guid"];
915 $condition = ['uri' => $item["thr-parent"], 'uid' => local_user()];
916 $orig_post = Post::selectFirst(['author-link'], $condition);
917 if (DBA::isResult($orig_post)) {
918 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
919 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
920 $nicknameplain = "@" . $nicknameplain;
922 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
923 $item["body"] = $nickname . " " . $item["body"];
927 $msgarr = Plaintext::getPost($item, $max_char, true, BBCode::TWITTER);
928 $msg = $msgarr["text"];
930 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
931 $msg .= " " . $msgarr["url"];
934 if (isset($msgarr["image"])) {
935 $msg .= " " . $msgarr["image"];
938 $b['html'] = nl2br(htmlspecialchars($msg));
942 function twitter_statuses_show(string $id, TwitterOAuth $twitterOAuth = null)
944 if ($twitterOAuth === null) {
945 $ckey = DI::config()->get('twitter', 'consumerkey');
946 $csecret = DI::config()->get('twitter', 'consumersecret');
948 if (empty($ckey) || empty($csecret)) {
949 return new stdClass();
952 $twitterOAuth = new TwitterOAuth($ckey, $csecret);
955 $parameters = ['trim_user' => false, 'tweet_mode' => 'extended', 'id' => $id, 'include_ext_alt_text' => true];
957 return $twitterOAuth->get('statuses/show', $parameters);
961 * Parse Twitter status URLs since Twitter removed OEmbed
964 * @param array $b Expected format:
966 * 'url' => [URL to parse],
967 * 'format' => 'json'|'',
968 * 'text' => Output parameter
970 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
972 function twitter_parse_link(App $a, array &$b)
974 // Only handle Twitter status URLs
975 if (!preg_match('#^https?://(?:mobile\.|www\.)?twitter.com/[^/]+/status/(\d+).*#', $b['url'], $matches)) {
979 $status = twitter_statuses_show($matches[1]);
981 if (empty($status->id)) {
985 $item = twitter_createpost($a, 0, $status, [], true, false, true);
987 if ($b['format'] == 'json') {
989 foreach ($status->extended_entities->media ?? [] as $media) {
990 if (!empty($media->media_url_https)) {
992 'src' => $media->media_url_https,
993 'width' => $media->sizes->thumb->w,
994 'height' => $media->sizes->thumb->h,
1002 'url' => $item['plink'],
1003 'title' => DI::l10n()->t('%s on Twitter', $status->user->name),
1004 'text' => BBCode::toPlaintext($item['body'], false),
1005 'images' => $images,
1007 'contentType' => 'attachment',
1011 $b['text'] = BBCode::getShareOpeningTag(
1012 $item['author-name'],
1013 $item['author-link'],
1014 $item['author-avatar'],
1018 $b['text'] .= $item['body'] . '[/share]';
1023 /*********************
1027 *********************/
1031 * @brief Build the item array for the mirrored post
1033 * @param App $a Application class
1034 * @param integer $uid User id
1035 * @param object $post Twitter object with the post
1037 * @return array item data to be posted
1039 function twitter_do_mirrorpost(App $a, $uid, $post)
1041 $datarray['uid'] = $uid;
1042 $datarray['extid'] = 'twitter::' . $post->id;
1043 $datarray['title'] = '';
1045 if (!empty($post->retweeted_status)) {
1046 // We don't support nested shares, so we mustn't show quotes as shares on retweets
1047 $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true, -1);
1049 if (empty($item['body'])) {
1053 $datarray['body'] = "\n" . BBCode::getShareOpeningTag(
1054 $item['author-name'],
1055 $item['author-link'],
1056 $item['author-avatar'],
1061 $datarray['body'] .= $item['body'] . '[/share]';
1063 $item = twitter_createpost($a, $uid, $post, ['id' => 0], false, false, false, -1);
1065 if (empty($item['body'])) {
1069 $datarray['body'] = $item['body'];
1072 $datarray['app'] = $item['app'];
1073 $datarray['verb'] = $item['verb'];
1075 if (isset($item['location'])) {
1076 $datarray['location'] = $item['location'];
1079 if (isset($item['coord'])) {
1080 $datarray['coord'] = $item['coord'];
1086 function twitter_fetchtimeline(App $a, $uid)
1088 $ckey = DI::config()->get('twitter', 'consumerkey');
1089 $csecret = DI::config()->get('twitter', 'consumersecret');
1090 $otoken = DI::pConfig()->get($uid, 'twitter', 'oauthtoken');
1091 $osecret = DI::pConfig()->get($uid, 'twitter', 'oauthsecret');
1092 $lastid = DI::pConfig()->get($uid, 'twitter', 'lastid');
1094 $application_name = DI::config()->get('twitter', 'application_name');
1096 if ($application_name == "") {
1097 $application_name = DI::baseUrl()->getHostname();
1100 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1102 // Ensure to have the own contact
1104 twitter_fetch_own_contact($a, $uid);
1105 } catch (TwitterOAuthException $e) {
1106 Logger::warning('Error fetching own contact', ['uid' => $uid, 'message' => $e->getMessage()]);
1110 $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended", "include_ext_alt_text" => true];
1112 $first_time = ($lastid == "");
1114 if ($lastid != "") {
1115 $parameters["since_id"] = $lastid;
1119 $items = $connection->get('statuses/user_timeline', $parameters);
1120 } catch (TwitterOAuthException $e) {
1121 Logger::warning('Error fetching timeline', ['uid' => $uid, 'message' => $e->getMessage()]);
1125 if (!is_array($items)) {
1126 Logger::notice('No items', ['user' => $uid]);
1130 $posts = array_reverse($items);
1132 Logger::notice('Start processing posts', ['from' => $lastid, 'user' => $uid, 'count' => count($posts)]);
1134 if (count($posts)) {
1135 foreach ($posts as $post) {
1136 if ($post->id_str > $lastid) {
1137 $lastid = $post->id_str;
1138 DI::pConfig()->set($uid, 'twitter', 'lastid', $lastid);
1145 if (!stristr($post->source, $application_name)) {
1146 Logger::info('Preparing mirror post', ['twitter-id' => $post->id_str, 'uid' => $uid]);
1148 $mirrorpost = twitter_do_mirrorpost($a, $uid, $post);
1150 if (empty($mirrorpost['body'])) {
1154 Logger::info('Posting mirror post', ['twitter-id' => $post->id_str, 'uid' => $uid]);
1156 Post\Delayed::add($mirrorpost['extid'], $mirrorpost, PRIORITY_MEDIUM, Post\Delayed::UNPREPARED);
1160 DI::pConfig()->set($uid, 'twitter', 'lastid', $lastid);
1161 Logger::log('Last ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
1164 function twitter_fix_avatar($avatar)
1166 $new_avatar = str_replace("_normal.", ".", $avatar);
1168 $info = Images::getInfoFromURLCached($new_avatar);
1170 $new_avatar = $avatar;
1176 function twitter_get_relation($uid, $target, $contact = [])
1178 if (isset($contact['rel'])) {
1179 $relation = $contact['rel'];
1184 $ckey = DI::config()->get('twitter', 'consumerkey');
1185 $csecret = DI::config()->get('twitter', 'consumersecret');
1186 $otoken = DI::pConfig()->get($uid, 'twitter', 'oauthtoken');
1187 $osecret = DI::pConfig()->get($uid, 'twitter', 'oauthsecret');
1188 $own_id = DI::pConfig()->get($uid, 'twitter', 'own_id');
1190 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1191 $parameters = ['source_id' => $own_id, 'target_screen_name' => $target];
1194 $status = $connection->get('friendships/show', $parameters);
1195 if ($connection->getLastHttpCode() !== 200) {
1196 throw new Exception($status->errors[0]->message ?? 'HTTP response code ' . $connection->getLastHttpCode(), $status->errors[0]->code ?? $connection->getLastHttpCode());
1199 $following = $status->relationship->source->following;
1200 $followed = $status->relationship->source->followed_by;
1202 if ($following && !$followed) {
1203 $relation = Contact::SHARING;
1204 } elseif (!$following && $followed) {
1205 $relation = Contact::FOLLOWER;
1206 } elseif ($following && $followed) {
1207 $relation = Contact::FRIEND;
1208 } elseif (!$following && !$followed) {
1212 Logger::info('Fetched friendship relation', ['user' => $uid, 'target' => $target, 'relation' => $relation]);
1213 } catch (Throwable $e) {
1214 Logger::warning('Error fetching friendship status', ['uid' => $uid, 'target' => $target, 'message' => $e->getMessage()]);
1224 function twitter_user_to_contact($data)
1226 if (empty($data->id_str)) {
1230 $baseurl = 'https://twitter.com';
1231 $url = $baseurl . '/' . $data->screen_name;
1232 $addr = $data->screen_name . '@twitter.com';
1236 'network' => Protocol::TWITTER,
1237 'alias' => 'twitter::' . $data->id_str,
1238 'baseurl' => $baseurl,
1239 'name' => $data->name,
1240 'nick' => $data->screen_name,
1242 'location' => $data->location,
1243 'about' => $data->description,
1244 'photo' => twitter_fix_avatar($data->profile_image_url_https),
1245 'header' => $data->profile_banner_url ?? $data->profile_background_image_url_https,
1251 function twitter_fetch_contact($uid, $data, $create_user)
1253 $fields = twitter_user_to_contact($data);
1255 if (empty($fields)) {
1259 // photo comes from twitter_user_to_contact but shouldn't be saved directly in the contact row
1260 $avatar = $fields['photo'];
1261 unset($fields['photo']);
1263 // Update the public contact
1264 $pcontact = DBA::selectFirst('contact', ['id'], ['uid' => 0, 'alias' => "twitter::" . $data->id_str]);
1265 if (DBA::isResult($pcontact)) {
1266 $cid = $pcontact['id'];
1268 $cid = Contact::getIdForURL($fields['url'], 0, false, $fields);
1272 Contact::update($fields, ['id' => $cid]);
1273 Contact::updateAvatar($cid, $avatar);
1275 Logger::warning('No contact found', ['fields' => $fields]);
1278 $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'alias' => "twitter::" . $data->id_str]);
1279 if (!DBA::isResult($contact) && empty($cid)) {
1280 Logger::warning('User contact not found', ['uid' => $uid, 'twitter-id' => $data->id_str]);
1282 } elseif (!$create_user) {
1286 if (!DBA::isResult($contact)) {
1287 $relation = twitter_get_relation($uid, $data->screen_name);
1289 // create contact record
1290 $fields['uid'] = $uid;
1291 $fields['created'] = DateTimeFormat::utcNow();
1292 $fields['nurl'] = Strings::normaliseLink($fields['url']);
1293 $fields['poll'] = 'twitter::' . $data->id_str;
1294 $fields['rel'] = $relation;
1295 $fields['priority'] = 1;
1296 $fields['writable'] = true;
1297 $fields['blocked'] = false;
1298 $fields['readonly'] = false;
1299 $fields['pending'] = false;
1301 if (!Contact::insert($fields)) {
1305 $contact_id = DBA::lastInsertId();
1307 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1309 Contact::updateAvatar($contact_id, $avatar);
1311 if ($contact["readonly"] || $contact["blocked"]) {
1312 Logger::notice('Contact is blocked or readonly.', ['nickname' => $contact["nick"]]);
1316 $contact_id = $contact['id'];
1319 // Update the contact relation once per day
1320 if ($contact['updated'] < DateTimeFormat::utc('now -24 hours')) {
1321 $fields['rel'] = twitter_get_relation($uid, $data->screen_name, $contact);
1325 Contact::updateAvatar($contact['id'], $avatar);
1327 if ($contact['name'] != $data->name) {
1328 $fields['name-date'] = $fields['uri-date'] = DateTimeFormat::utcNow();
1332 if ($contact['nick'] != $data->screen_name) {
1333 $fields['uri-date'] = DateTimeFormat::utcNow();
1337 if (($contact['location'] != $data->location) || ($contact['about'] != $data->description)) {
1342 $fields['updated'] = DateTimeFormat::utcNow();
1343 Contact::update($fields, ['id' => $contact['id']]);
1344 Logger::info('Updated contact', ['id' => $contact['id'], 'nick' => $data->screen_name]);
1352 * @param string $screen_name
1353 * @return stdClass|null
1356 function twitter_fetchuser($screen_name)
1358 $ckey = DI::config()->get('twitter', 'consumerkey');
1359 $csecret = DI::config()->get('twitter', 'consumersecret');
1362 // Fetching user data
1363 $connection = new TwitterOAuth($ckey, $csecret);
1364 $parameters = ['screen_name' => $screen_name];
1365 $user = $connection->get('users/show', $parameters);
1366 } catch (TwitterOAuthException $e) {
1367 Logger::warning('Error fetching user', ['user' => $screen_name, 'message' => $e->getMessage()]);
1371 if (!is_object($user)) {
1379 * Replaces Twitter entities with Friendica-friendly links.
1381 * The Twitter API gives indices for each entity, which allows for fine-grained replacement.
1383 * First, we need to collect everything that needs to be replaced, what we will replace it with, and the start index.
1384 * Then we sort the indices decreasingly, and we replace from the end of the body to the start in order for the next
1385 * index to be correct even after the last replacement.
1387 * @param string $body
1388 * @param stdClass $status
1390 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1392 function twitter_expand_entities($body, stdClass $status)
1395 $contains_urls = false;
1399 $replacementList = [];
1401 foreach ($status->entities->hashtags AS $hashtag) {
1402 $replace = '#[url=' . DI::baseUrl()->get() . '/search?tag=' . $hashtag->text . ']' . $hashtag->text . '[/url]';
1403 $taglist['#' . $hashtag->text] = ['#', $hashtag->text, ''];
1405 $replacementList[$hashtag->indices[0]] = [
1406 'replace' => $replace,
1407 'length' => $hashtag->indices[1] - $hashtag->indices[0],
1411 foreach ($status->entities->user_mentions AS $mention) {
1412 $replace = '@[url=https://twitter.com/' . rawurlencode($mention->screen_name) . ']' . $mention->screen_name . '[/url]';
1413 $taglist['@' . $mention->screen_name] = ['@', $mention->screen_name, 'https://twitter.com/' . rawurlencode($mention->screen_name)];
1415 $replacementList[$mention->indices[0]] = [
1416 'replace' => $replace,
1417 'length' => $mention->indices[1] - $mention->indices[0],
1421 foreach ($status->entities->urls ?? [] as $url) {
1422 $plain = str_replace($url->url, '', $plain);
1424 if ($url->url && $url->expanded_url && $url->display_url) {
1425 // Quote tweet, we just remove the quoted tweet URL from the body, the share block will be added later.
1426 if (!empty($status->quoted_status) && isset($status->quoted_status_id_str)
1427 && substr($url->expanded_url, -strlen($status->quoted_status_id_str)) == $status->quoted_status_id_str
1429 $replacementList[$url->indices[0]] = [
1431 'length' => $url->indices[1] - $url->indices[0],
1436 $contains_urls = true;
1438 $expanded_url = $url->expanded_url;
1440 // Quickfix: Workaround for URL with '[' and ']' in it
1441 if (strpos($expanded_url, '[') || strpos($expanded_url, ']')) {
1442 $expanded_url = $url->url;
1445 $replacementList[$url->indices[0]] = [
1446 'replace' => '[url=' . $expanded_url . ']' . $url->display_url . '[/url]',
1447 'length' => $url->indices[1] - $url->indices[0],
1452 krsort($replacementList);
1454 foreach ($replacementList as $startIndex => $parameters) {
1455 $body = Strings::substringReplace($body, $parameters['replace'], $startIndex, $parameters['length']);
1458 $body = trim($body);
1460 return ['body' => trim($body), 'plain' => trim($plain), 'taglist' => $taglist, 'urls' => $contains_urls];
1464 * Store entity attachments
1466 * @param integer $uriid
1467 * @param object $post Twitter object with the post
1469 function twitter_store_attachments(int $uriid, $post)
1471 if (!empty($post->extended_entities->media)) {
1472 foreach ($post->extended_entities->media AS $medium) {
1473 switch ($medium->type) {
1475 $attachment = ['uri-id' => $uriid, 'type' => Post\Media::IMAGE];
1477 $attachment['url'] = $medium->media_url_https . '?name=large';
1478 $attachment['width'] = $medium->sizes->large->w;
1479 $attachment['height'] = $medium->sizes->large->h;
1481 if ($medium->sizes->small->w != $attachment['width']) {
1482 $attachment['preview'] = $medium->media_url_https . '?name=small';
1483 $attachment['preview-width'] = $medium->sizes->small->w;
1484 $attachment['preview-height'] = $medium->sizes->small->h;
1487 $attachment['name'] = $medium->display_url ?? null;
1488 $attachment['description'] = $medium->ext_alt_text ?? null;
1489 Logger::debug('Photo attachment', ['attachment' => $attachment]);
1490 Post\Media::insert($attachment);
1493 case 'animated_gif':
1494 $attachment = ['uri-id' => $uriid, 'type' => Post\Media::VIDEO];
1495 if (is_array($medium->video_info->variants)) {
1497 // We take the video with the highest bitrate
1498 foreach ($medium->video_info->variants AS $variant) {
1499 if (($variant->content_type == 'video/mp4') && ($variant->bitrate >= $bitrate)) {
1500 $attachment['url'] = $variant->url;
1501 $bitrate = $variant->bitrate;
1506 $attachment['name'] = $medium->display_url ?? null;
1507 $attachment['preview'] = $medium->media_url_https . ':small';
1508 $attachment['preview-width'] = $medium->sizes->small->w;
1509 $attachment['preview-height'] = $medium->sizes->small->h;
1510 $attachment['description'] = $medium->ext_alt_text ?? null;
1511 Logger::debug('Video attachment', ['attachment' => $attachment]);
1512 Post\Media::insert($attachment);
1515 Logger::notice('Unknown media type', ['medium' => $medium]);
1520 if (!empty($post->entities->urls)) {
1521 foreach ($post->entities->urls as $url) {
1522 $attachment = ['uri-id' => $uriid, 'type' => Post\Media::UNKNOWN, 'url' => $url->expanded_url, 'name' => $url->display_url];
1523 Logger::debug('Attached link', ['attachment' => $attachment]);
1524 Post\Media::insert($attachment);
1530 * @brief Fetch media entities and add media links to the body
1532 * @param object $post Twitter object with the post
1533 * @param array $postarray Array of the item that is about to be posted
1534 * @param integer $uriid URI Id used to store tags. -1 = don't store tags for this post.
1536 function twitter_media_entities($post, array &$postarray, int $uriid = -1)
1538 // There are no media entities? So we quit.
1539 if (empty($post->extended_entities->media)) {
1543 // This is a pure media post, first search for all media urls
1545 foreach ($post->extended_entities->media AS $medium) {
1546 if (!isset($media[$medium->url])) {
1547 $media[$medium->url] = '';
1549 switch ($medium->type) {
1551 if (!empty($medium->ext_alt_text)) {
1552 Logger::info('Got text description', ['alt_text' => $medium->ext_alt_text]);
1553 $media[$medium->url] .= "\n[img=" . $medium->media_url_https .']' . $medium->ext_alt_text . '[/img]';
1555 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
1558 $postarray['object-type'] = Activity\ObjectType::IMAGE;
1559 $postarray['post-type'] = Item::PT_IMAGE;
1562 // Currently deactivated, since this causes the video to be display before the content
1563 // We have to figure out a better way for declaring the post type and the display style.
1564 //$postarray['post-type'] = Item::PT_VIDEO;
1565 case 'animated_gif':
1566 if (!empty($medium->ext_alt_text)) {
1567 Logger::info('Got text description', ['alt_text' => $medium->ext_alt_text]);
1568 $media[$medium->url] .= "\n[img=" . $medium->media_url_https .']' . $medium->ext_alt_text . '[/img]';
1570 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
1573 $postarray['object-type'] = Activity\ObjectType::VIDEO;
1574 if (is_array($medium->video_info->variants)) {
1576 // We take the video with the highest bitrate
1577 foreach ($medium->video_info->variants AS $variant) {
1578 if (($variant->content_type == 'video/mp4') && ($variant->bitrate >= $bitrate)) {
1579 $media[$medium->url] = "\n[video]" . $variant->url . '[/video]';
1580 $bitrate = $variant->bitrate;
1589 foreach ($media AS $key => $value) {
1590 $postarray['body'] = str_replace($key, '', $postarray['body']);
1595 // Now we replace the media urls.
1596 foreach ($media AS $key => $value) {
1597 $postarray['body'] = str_replace($key, "\n" . $value . "\n", $postarray['body']);
1602 * Undocumented function
1605 * @param integer $uid User ID
1606 * @param object $post Incoming Twitter post
1607 * @param array $self
1608 * @param bool $create_user Should users be created?
1609 * @param bool $only_existing_contact Only import existing contacts if set to "true"
1610 * @param bool $noquote
1611 * @param integer $uriid URI Id used to store tags. 0 = create a new one; -1 = don't store tags for this post.
1612 * @return array item array
1614 function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $only_existing_contact, $noquote, int $uriid = 0)
1617 $postarray['network'] = Protocol::TWITTER;
1618 $postarray['uid'] = $uid;
1619 $postarray['wall'] = 0;
1620 $postarray['uri'] = "twitter::" . $post->id_str;
1621 $postarray['protocol'] = Conversation::PARCEL_TWITTER;
1622 $postarray['source'] = json_encode($post);
1623 $postarray['direction'] = Conversation::PULL;
1625 if (empty($uriid)) {
1626 $uriid = $postarray['uri-id'] = ItemURI::insert(['uri' => $postarray['uri']]);
1629 // Don't import our own comments
1630 if (Post::exists(['extid' => $postarray['uri'], 'uid' => $uid])) {
1631 Logger::info('Item found', ['extid' => $postarray['uri']]);
1637 if ($post->in_reply_to_status_id_str != "") {
1638 $thr_parent = "twitter::" . $post->in_reply_to_status_id_str;
1640 $item = Post::selectFirst(['uri'], ['uri' => $thr_parent, 'uid' => $uid]);
1641 if (!DBA::isResult($item)) {
1642 $item = Post::selectFirst(['uri'], ['extid' => $thr_parent, 'uid' => $uid]);
1645 if (DBA::isResult($item)) {
1646 $postarray['thr-parent'] = $item['uri'];
1647 $postarray['object-type'] = Activity\ObjectType::COMMENT;
1649 $postarray['object-type'] = Activity\ObjectType::NOTE;
1653 $own_id = DI::pConfig()->get($uid, 'twitter', 'own_id');
1655 if ($post->user->id_str == $own_id) {
1656 $self = Contact::selectFirst(['id', 'name', 'url', 'photo'], ['self' => true, 'uid' => $uid]);
1657 if (DBA::isResult($self)) {
1658 $contactid = $self['id'];
1660 $postarray['owner-name'] = $self['name'];
1661 $postarray['owner-link'] = $self['url'];
1662 $postarray['owner-avatar'] = $self['photo'];
1664 Logger::error('No self contact found', ['uid' => $uid]);
1668 // Don't create accounts of people who just comment something
1669 $create_user = false;
1671 $postarray['object-type'] = Activity\ObjectType::NOTE;
1674 if ($contactid == 0) {
1675 $contactid = twitter_fetch_contact($uid, $post->user, $create_user);
1677 $postarray['owner-name'] = $post->user->name;
1678 $postarray['owner-link'] = "https://twitter.com/" . $post->user->screen_name;
1679 $postarray['owner-avatar'] = twitter_fix_avatar($post->user->profile_image_url_https);
1682 if (($contactid == 0) && !$only_existing_contact) {
1683 $contactid = $self['id'];
1684 } elseif ($contactid <= 0) {
1685 Logger::info('Contact ID is zero or less than zero.');
1689 $postarray['contact-id'] = $contactid;
1691 $postarray['verb'] = Activity::POST;
1692 $postarray['author-name'] = $postarray['owner-name'];
1693 $postarray['author-link'] = $postarray['owner-link'];
1694 $postarray['author-avatar'] = $postarray['owner-avatar'];
1695 $postarray['plink'] = "https://twitter.com/" . $post->user->screen_name . "/status/" . $post->id_str;
1696 $postarray['app'] = strip_tags($post->source);
1698 if ($post->user->protected) {
1699 $postarray['private'] = Item::PRIVATE;
1700 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1702 $postarray['private'] = Item::UNLISTED;
1703 $postarray['allow_cid'] = '';
1706 if (!empty($post->full_text)) {
1707 $postarray['body'] = $post->full_text;
1709 $postarray['body'] = $post->text;
1712 // When the post contains links then use the correct object type
1713 if (count($post->entities->urls) > 0) {
1714 $postarray['object-type'] = Activity\ObjectType::BOOKMARK;
1717 // Search for media links
1718 twitter_media_entities($post, $postarray, $uriid);
1720 $converted = twitter_expand_entities($postarray['body'], $post);
1722 // When the post contains external links then images or videos are just "decorations".
1723 if (!empty($converted['urls'])) {
1724 $postarray['post-type'] = Item::PT_NOTE;
1727 $postarray['body'] = $converted['body'];
1728 $postarray['created'] = DateTimeFormat::utc($post->created_at);
1729 $postarray['edited'] = DateTimeFormat::utc($post->created_at);
1732 twitter_store_tags($uriid, $converted['taglist']);
1733 twitter_store_attachments($uriid, $post);
1736 if (!empty($post->place->name)) {
1737 $postarray["location"] = $post->place->name;
1739 if (!empty($post->place->full_name)) {
1740 $postarray["location"] = $post->place->full_name;
1742 if (!empty($post->geo->coordinates)) {
1743 $postarray["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
1745 if (!empty($post->coordinates->coordinates)) {
1746 $postarray["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
1748 if (!empty($post->retweeted_status)) {
1749 $retweet = twitter_createpost($a, $uid, $post->retweeted_status, $self, false, false, $noquote);
1751 if (empty($retweet['body'])) {
1756 // Store the original tweet
1757 Item::insert($retweet);
1759 // CHange the other post into a reshare activity
1760 $postarray['verb'] = Activity::ANNOUNCE;
1761 $postarray['gravity'] = GRAVITY_ACTIVITY;
1762 $postarray['object-type'] = Activity\ObjectType::NOTE;
1764 $postarray['thr-parent'] = $retweet['uri'];
1766 $retweet['source'] = $postarray['source'];
1767 $retweet['direction'] = $postarray['direction'];
1768 $retweet['private'] = $postarray['private'];
1769 $retweet['allow_cid'] = $postarray['allow_cid'];
1770 $retweet['contact-id'] = $postarray['contact-id'];
1771 $retweet['owner-name'] = $postarray['owner-name'];
1772 $retweet['owner-link'] = $postarray['owner-link'];
1773 $retweet['owner-avatar'] = $postarray['owner-avatar'];
1775 $postarray = $retweet;
1779 if (!empty($post->quoted_status)) {
1781 // To avoid recursive share blocks we just provide the link to avoid removing quote context.
1782 $postarray['body'] .= "\n\nhttps://twitter.com/" . $post->quoted_status->user->screen_name . "/status/" . $post->quoted_status->id_str;
1784 $quoted = twitter_createpost($a, 0, $post->quoted_status, $self, false, false, true);
1785 if (!empty($quoted['body'])) {
1786 Item::insert($quoted);
1787 $post = Post::selectFirst(['guid', 'uri-id'], ['uri' => $quoted['uri'], 'uid' => 0]);
1788 Logger::info('Stored quoted post', ['uid' => $uid, 'uri-id' => $uriid, 'post' => $post]);
1790 $postarray['body'] .= "\n" . BBCode::getShareOpeningTag(
1791 $quoted['author-name'],
1792 $quoted['author-link'],
1793 $quoted['author-avatar'],
1799 $postarray['body'] .= $quoted['body'] . '[/share]';
1801 // Quoted post author is blocked/ignored, so we just provide the link to avoid removing quote context.
1802 $postarray['body'] .= "\n\nhttps://twitter.com/" . $post->quoted_status->user->screen_name . "/status/" . $post->quoted_status->id_str;
1811 * Store tags and mentions
1813 * @param integer $uriid
1814 * @param array $taglist
1816 function twitter_store_tags(int $uriid, array $taglist)
1818 foreach ($taglist as $tag) {
1819 Tag::storeByHash($uriid, $tag[0], $tag[1], $tag[2]);
1823 function twitter_fetchparentposts(App $a, $uid, $post, TwitterOAuth $connection, array $self)
1825 Logger::info('Fetching parent posts', ['user' => $uid, 'post' => $post->id_str]);
1829 while (!empty($post->in_reply_to_status_id_str)) {
1831 $post = twitter_statuses_show($post->in_reply_to_status_id_str, $connection);
1832 } catch (TwitterOAuthException $e) {
1833 Logger::warning('Error fetching parent post', ['uid' => $uid, 'post' => $post->id_str, 'message' => $e->getMessage()]);
1838 Logger::info("twitter_fetchparentposts: Can't fetch post");
1842 if (empty($post->id_str)) {
1843 Logger::info("twitter_fetchparentposts: This is not a post", ['post' => $post]);
1847 if (Post::exists(['uri' => 'twitter::' . $post->id_str, 'uid' => $uid])) {
1854 Logger::log("twitter_fetchparentposts: Fetching " . count($posts) . " parents", Logger::DEBUG);
1856 $posts = array_reverse($posts);
1858 if (!empty($posts)) {
1859 foreach ($posts as $post) {
1860 $postarray = twitter_createpost($a, $uid, $post, $self, false, !DI::pConfig()->get($uid, 'twitter', 'create_user'), false);
1862 if (empty($postarray['body'])) {
1866 $item = Item::insert($postarray);
1868 $postarray["id"] = $item;
1870 Logger::log('twitter_fetchparentpost: User ' . $self["nick"] . ' posted parent timeline item ' . $item);
1875 function twitter_fetchhometimeline(App $a, $uid)
1877 $ckey = DI::config()->get('twitter', 'consumerkey');
1878 $csecret = DI::config()->get('twitter', 'consumersecret');
1879 $otoken = DI::pConfig()->get($uid, 'twitter', 'oauthtoken');
1880 $osecret = DI::pConfig()->get($uid, 'twitter', 'oauthsecret');
1881 $create_user = DI::pConfig()->get($uid, 'twitter', 'create_user');
1882 $mirror_posts = DI::pConfig()->get($uid, 'twitter', 'mirror_posts');
1884 Logger::info('Fetching timeline', ['uid' => $uid]);
1886 $application_name = DI::config()->get('twitter', 'application_name');
1888 if ($application_name == "") {
1889 $application_name = DI::baseUrl()->getHostname();
1892 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1895 $own_contact = twitter_fetch_own_contact($a, $uid);
1896 } catch (TwitterOAuthException $e) {
1897 Logger::warning('Error fetching own contact', ['uid' => $uid, 'message' => $e->getMessage()]);
1901 $contact = Contact::selectFirst(['nick'], ['id' => $own_contact, 'uid' => $uid]);
1902 if (DBA::isResult($contact)) {
1903 $own_id = $contact['nick'];
1905 Logger::warning('Own twitter contact not found', ['uid' => $uid]);
1909 $self = User::getOwnerDataById($uid);
1910 if ($self === false) {
1911 Logger::warning('Own contact not found', ['uid' => $uid]);
1915 $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended", "include_ext_alt_text" => true];
1916 //$parameters["count"] = 200;
1917 // Fetching timeline
1918 $lastid = DI::pConfig()->get($uid, 'twitter', 'lasthometimelineid');
1920 $first_time = ($lastid == "");
1922 if ($lastid != "") {
1923 $parameters["since_id"] = $lastid;
1927 $items = $connection->get('statuses/home_timeline', $parameters);
1928 } catch (TwitterOAuthException $e) {
1929 Logger::warning('Error fetching home timeline', ['uid' => $uid, 'message' => $e->getMessage()]);
1933 if (!is_array($items)) {
1934 Logger::warning('home timeline is no array', ['items' => $items]);
1938 if (empty($items)) {
1939 Logger::notice('No new timeline content', ['uid' => $uid]);
1943 $posts = array_reverse($items);
1945 Logger::notice('Processing timeline', ['lastid' => $lastid, 'uid' => $uid, 'count' => count($posts)]);
1947 if (count($posts)) {
1948 foreach ($posts as $post) {
1949 if ($post->id_str > $lastid) {
1950 $lastid = $post->id_str;
1951 DI::pConfig()->set($uid, 'twitter', 'lasthometimelineid', $lastid);
1958 if (stristr($post->source, $application_name) && $post->user->screen_name == $own_id) {
1959 Logger::info("Skip previously sent post");
1963 if ($mirror_posts && $post->user->screen_name == $own_id && $post->in_reply_to_status_id_str == "") {
1964 Logger::info("Skip post that will be mirrored");
1968 if ($post->in_reply_to_status_id_str != "") {
1969 twitter_fetchparentposts($a, $uid, $post, $connection, $self);
1972 Logger::log('Preparing post ' . $post->id_str . ' for user ' . $uid, Logger::DEBUG);
1974 $postarray = twitter_createpost($a, $uid, $post, $self, $create_user, true, false);
1976 if (empty($postarray['body']) || trim($postarray['body']) == "") {
1977 Logger::log('Empty body for post ' . $post->id_str . ' and user ' . $uid, Logger::DEBUG);
1983 if (empty($postarray['thr-parent'])) {
1984 $contact = DBA::selectFirst('contact', [], ['id' => $postarray['contact-id'], 'self' => false]);
1985 if (DBA::isResult($contact) && Item::isRemoteSelf($contact, $postarray)) {
1986 $notify = PRIORITY_MEDIUM;
1990 $item = Item::insert($postarray, $notify);
1991 $postarray["id"] = $item;
1993 Logger::log('User ' . $uid . ' posted home timeline item ' . $item);
1996 DI::pConfig()->set($uid, 'twitter', 'lasthometimelineid', $lastid);
1998 Logger::log('Last timeline ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
2000 // Fetching mentions
2001 $lastid = DI::pConfig()->get($uid, 'twitter', 'lastmentionid');
2003 $first_time = ($lastid == "");
2005 if ($lastid != "") {
2006 $parameters["since_id"] = $lastid;
2010 $items = $connection->get('statuses/mentions_timeline', $parameters);
2011 } catch (TwitterOAuthException $e) {
2012 Logger::warning('Error fetching mentions', ['uid' => $uid, 'message' => $e->getMessage()]);
2016 if (!is_array($items)) {
2017 Logger::warning("mentions are no arrays", ['items' => $items]);
2021 $posts = array_reverse($items);
2023 Logger::log("Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", Logger::DEBUG);
2025 if (count($posts)) {
2026 foreach ($posts as $post) {
2027 if ($post->id_str > $lastid) {
2028 $lastid = $post->id_str;
2035 if ($post->in_reply_to_status_id_str != "") {
2036 twitter_fetchparentposts($a, $uid, $post, $connection, $self);
2039 $postarray = twitter_createpost($a, $uid, $post, $self, false, !$create_user, false);
2041 if (empty($postarray['body'])) {
2045 $item = Item::insert($postarray);
2047 Logger::log('User ' . $uid . ' posted mention timeline item ' . $item);
2051 DI::pConfig()->set($uid, 'twitter', 'lastmentionid', $lastid);
2053 Logger::log('Last mentions ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
2056 function twitter_fetch_own_contact(App $a, $uid)
2058 $ckey = DI::config()->get('twitter', 'consumerkey');
2059 $csecret = DI::config()->get('twitter', 'consumersecret');
2060 $otoken = DI::pConfig()->get($uid, 'twitter', 'oauthtoken');
2061 $osecret = DI::pConfig()->get($uid, 'twitter', 'oauthsecret');
2063 $own_id = DI::pConfig()->get($uid, 'twitter', 'own_id');
2067 if ($own_id == "") {
2068 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
2070 // Fetching user data
2071 // get() may throw TwitterOAuthException, but we will catch it later
2072 $user = $connection->get('account/verify_credentials');
2073 if (empty($user->id_str)) {
2077 DI::pConfig()->set($uid, 'twitter', 'own_id', $user->id_str);
2079 $contact_id = twitter_fetch_contact($uid, $user, true);
2081 $contact = Contact::selectFirst(['id'], ['uid' => $uid, 'alias' => 'twitter::' . $own_id]);
2082 if (DBA::isResult($contact)) {
2083 $contact_id = $contact['id'];
2085 DI::pConfig()->delete($uid, 'twitter', 'own_id');
2092 function twitter_is_retweet(App $a, $uid, $body)
2094 $body = trim($body);
2096 // Skip if it isn't a pure repeated messages
2097 // Does it start with a share?
2098 if (strpos($body, "[share") > 0) {
2102 // Does it end with a share?
2103 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
2107 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
2108 // Skip if there is no shared message in there
2109 if ($body == $attributes) {
2114 preg_match("/link='(.*?)'/ism", $attributes, $matches);
2115 if (!empty($matches[1])) {
2116 $link = $matches[1];
2119 preg_match('/link="(.*?)"/ism', $attributes, $matches);
2120 if (!empty($matches[1])) {
2121 $link = $matches[1];
2124 $id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link);
2128 return twitter_retweet($uid, $id);
2131 function twitter_retweet(int $uid, int $id, int $item_id = 0)
2133 Logger::info('Retweeting', ['user' => $uid, 'id' => $id]);
2135 $result = twitter_api_post('statuses/retweet', $id, $uid);
2137 Logger::info('Retweeted', ['user' => $uid, 'id' => $id, 'result' => $result]);
2139 if (!empty($item_id) && !empty($result->id_str)) {
2140 Logger::notice('Update extid', ['id' => $item_id, 'extid' => $result->id_str]);
2141 Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $item_id]);
2144 return !isset($result->errors);
2147 function twitter_update_mentions($body)
2149 $URLSearchString = "^\[\]";
2150 $return = preg_replace_callback(
2151 "/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2152 function ($matches) {
2153 if (strpos($matches[1], 'twitter.com')) {
2154 $return = '@' . substr($matches[1], strrpos($matches[1], '/') + 1);
2156 $return = $matches[2] . ' (' . $matches[1] . ')';
2167 function twitter_convert_share(array $attributes, array $author_contact, $content, $is_quote_share)
2169 if (empty($author_contact)) {
2170 return $content . "\n\n" . $attributes['link'];
2173 if (!empty($author_contact['network']) && ($author_contact['network'] == Protocol::TWITTER)) {
2174 $mention = '@' . $author_contact['nick'];
2176 $mention = $author_contact['addr'];
2179 return ($is_quote_share ? "\n\n" : '' ) . 'RT ' . $mention . ': ' . $content . "\n\n" . $attributes['link'];