]> git.mxchange.org Git - friendica-addons.git/blob - twitter/twitter.php
5e3a4b9c2c17308dc62c55fe6bef172766a62089
[friendica-addons.git] / twitter / twitter.php
1 <?php
2 /**
3  * Name: Twitter Connector
4  * Description: Bidirectional (posting, relaying and reading) connector for Twitter.
5  * Version: 1.1.0
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>
9  *
10  * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel, Hypolite Petovan
11  * All rights reserved.
12  *
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.
23  *
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.
34  *
35  */
36 /*   Twitter Addon for Friendica
37  *
38  *   Author: Tobias Diekershoff
39  *           tobias.diekershoff@gmx.net
40  *
41  *   License:3-clause BSD license
42  *
43  *   Configuration:
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
46  *
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.
50  *
51  *     Add this key pair to your global config/addon.config.php or use the admin panel.
52  *
53  *      'twitter' => [
54  *                  'consumerkey' => '',
55  *              'consumersecret' => '',
56  *      ],
57  *
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".
61  *
62  *     Requirements: PHP5, curl
63  */
64
65 use Abraham\TwitterOAuth\TwitterOAuth;
66 use Abraham\TwitterOAuth\TwitterOAuthException;
67 use Codebird\Codebird;
68 use Friendica\App;
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;
77 use Friendica\DI;
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\Core\Config\Util\ConfigFileLoader;
88 use Friendica\Core\System;
89 use Friendica\Util\DateTimeFormat;
90 use Friendica\Util\Images;
91 use Friendica\Util\Strings;
92
93 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
94
95 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
96
97 function twitter_install()
98 {
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('support_follow'         , __FILE__, 'twitter_support_follow');
109         Hook::register('follow'                 , __FILE__, 'twitter_follow');
110         Hook::register('unfollow'               , __FILE__, 'twitter_unfollow');
111         Hook::register('block'                  , __FILE__, 'twitter_block');
112         Hook::register('unblock'                , __FILE__, 'twitter_unblock');
113         Hook::register('expire'                 , __FILE__, 'twitter_expire');
114         Hook::register('prepare_body'           , __FILE__, 'twitter_prepare_body');
115         Hook::register('check_item_notification', __FILE__, 'twitter_check_item_notification');
116         Hook::register('probe_detect'           , __FILE__, 'twitter_probe_detect');
117         Hook::register('item_by_link'           , __FILE__, 'twitter_item_by_link');
118         Hook::register('parse_link'             , __FILE__, 'twitter_parse_link');
119         Logger::info('installed twitter');
120 }
121
122 // Hook functions
123
124 function twitter_load_config(App $a, ConfigFileLoader $loader)
125 {
126         $a->getConfigCache()->load($loader->loadAddonConfig('twitter'));
127 }
128
129 function twitter_check_item_notification(App $a, array &$notification_data)
130 {
131         $own_id = DI::pConfig()->get($notification_data['uid'], 'twitter', 'own_id');
132
133         $own_user = Contact::selectFirst(['url'], ['uid' => $notification_data['uid'], 'alias' => 'twitter::'.$own_id]);
134         if ($own_user) {
135                 $notification_data['profiles'][] = $own_user['url'];
136         }
137 }
138
139 function twitter_support_follow(App $a, array &$data)
140 {
141         if ($data['protocol'] == Protocol::TWITTER) {
142                 $data['result'] = true;
143         }
144 }
145
146 function twitter_follow(App $a, array &$contact)
147 {
148         Logger::info('Check if contact is twitter contact', ['url' => $contact['url']]);
149
150         if (!strstr($contact['url'], '://twitter.com') && !strstr($contact['url'], '@twitter.com')) {
151                 return;
152         }
153
154         // contact seems to be a twitter contact, so continue
155         $nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $contact['url']);
156         $nickname = str_replace('@twitter.com', '', $nickname);
157
158         $uid = $a->getLoggedInUserId();
159
160         if (!twitter_api_contact('friendships/create', ['network' => Protocol::TWITTER, 'nick' => $nickname], $uid)) {
161                 $contact = null;
162                 return;
163         }
164
165         $user = twitter_fetchuser($nickname);
166
167         $contact_id = twitter_fetch_contact($uid, $user, true);
168
169         $contact = Contact::getById($contact_id, ['name', 'nick', 'url', 'addr', 'batch', 'notify', 'poll', 'request', 'confirm', 'poco', 'photo', 'priority', 'network', 'alias', 'pubkey']);
170
171         if (DBA::isResult($contact)) {
172                 $contact['contact'] = $contact;
173         }
174 }
175
176 function twitter_unfollow(App $a, array &$hook_data)
177 {
178         $hook_data['result'] = twitter_api_contact('friendships/destroy', $hook_data['contact'], $hook_data['uid']);
179 }
180
181 function twitter_block(App $a, array &$hook_data)
182 {
183         $hook_data['result'] = twitter_api_contact('blocks/create', $hook_data['contact'], $hook_data['uid']);
184
185         if ($hook_data['result'] === true) {
186                 $cdata = Contact::getPublicAndUserContactID($hook_data['contact']['id'], $hook_data['uid']);
187                 Contact::remove($cdata['user']);
188         }
189 }
190
191 function twitter_unblock(App $a, array &$hook_data)
192 {
193         $hook_data['result'] = twitter_api_contact('blocks/destroy', $hook_data['contact'], $hook_data['uid']);
194 }
195
196 function twitter_api_contact(string $apiPath, array $contact, int $uid): ?bool
197 {
198         if ($contact['network'] !== Protocol::TWITTER) {
199                 return null;
200         }
201
202         return twitter_api_call($uid, $apiPath, ['screen_name' => $contact['nick']]);
203 }
204
205 function twitter_jot_nets(App $a, array &$jotnets_fields)
206 {
207         if (!local_user()) {
208                 return;
209         }
210
211         if (DI::pConfig()->get(local_user(), 'twitter', 'post')) {
212                 $jotnets_fields[] = [
213                         'type' => 'checkbox',
214                         'field' => [
215                                 'twitter_enable',
216                                 DI::l10n()->t('Post to Twitter'),
217                                 DI::pConfig()->get(local_user(), 'twitter', 'post_by_default')
218                         ]
219                 ];
220         }
221 }
222
223
224 function twitter_settings_post(App $a)
225 {
226         if (!local_user()) {
227                 return;
228         }
229         // don't check twitter settings if twitter submit button is not clicked
230         if (empty($_POST['twitter-disconnect']) && empty($_POST['twitter-submit'])) {
231                 return;
232         }
233
234         if (!empty($_POST['twitter-disconnect'])) {
235                 /*               * *
236                  * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
237                  * from the user configuration
238                  */
239                 DI::pConfig()->delete(local_user(), 'twitter', 'consumerkey');
240                 DI::pConfig()->delete(local_user(), 'twitter', 'consumersecret');
241                 DI::pConfig()->delete(local_user(), 'twitter', 'oauthtoken');
242                 DI::pConfig()->delete(local_user(), 'twitter', 'oauthsecret');
243                 DI::pConfig()->delete(local_user(), 'twitter', 'post');
244                 DI::pConfig()->delete(local_user(), 'twitter', 'post_by_default');
245                 DI::pConfig()->delete(local_user(), 'twitter', 'lastid');
246                 DI::pConfig()->delete(local_user(), 'twitter', 'mirror_posts');
247                 DI::pConfig()->delete(local_user(), 'twitter', 'import');
248                 DI::pConfig()->delete(local_user(), 'twitter', 'create_user');
249                 DI::pConfig()->delete(local_user(), 'twitter', 'own_id');
250         } else {
251                 if (isset($_POST['twitter-pin'])) {
252                         //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
253                         Logger::notice('got a Twitter PIN');
254                         $ckey    = DI::config()->get('twitter', 'consumerkey');
255                         $csecret = DI::config()->get('twitter', 'consumersecret');
256                         //  the token and secret for which the PIN was generated were hidden in the settings
257                         //  form as token and token2, we need a new connection to Twitter using these token
258                         //  and secret to request a Access Token with the PIN
259                         try {
260                                 if (empty($_POST['twitter-pin'])) {
261                                         throw new Exception(DI::l10n()->t('You submitted an empty PIN, please Sign In with Twitter again to get a new one.'));
262                                 }
263
264                                 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
265                                 $token = $connection->oauth('oauth/access_token', ['oauth_verifier' => $_POST['twitter-pin']]);
266                                 //  ok, now that we have the Access Token, save them in the user config
267                                 DI::pConfig()->set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
268                                 DI::pConfig()->set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
269                                 DI::pConfig()->set(local_user(), 'twitter', 'post', 1);
270                         } catch(Exception $e) {
271                                 notice($e->getMessage());
272                         } catch(TwitterOAuthException $e) {
273                                 notice($e->getMessage());
274                         }
275                 } else {
276                         //  if no PIN is supplied in the POST variables, the user has changed the setting
277                         //  to post a tweet for every new __public__ posting to the wall
278                         DI::pConfig()->set(local_user(), 'twitter', 'post', intval($_POST['twitter-enable']));
279                         DI::pConfig()->set(local_user(), 'twitter', 'post_by_default', intval($_POST['twitter-default']));
280                         DI::pConfig()->set(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror']));
281                         DI::pConfig()->set(local_user(), 'twitter', 'import', intval($_POST['twitter-import']));
282                         DI::pConfig()->set(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user']));
283
284                         if (!intval($_POST['twitter-mirror'])) {
285                                 DI::pConfig()->delete(local_user(), 'twitter', 'lastid');
286                         }
287                 }
288         }
289 }
290
291 function twitter_settings(App $a, array &$data)
292 {
293         if (!local_user()) {
294                 return;
295         }
296
297         $user = User::getById(local_user());
298
299         DI::page()->registerStylesheet(__DIR__ . '/twitter.css', 'all');
300
301         /*       * *
302          * 1) Check that we have global consumer key & secret
303          * 2) If no OAuthtoken & stuff is present, generate button to get some
304          * 3) Checkbox for "Send public notices (280 chars only)
305          */
306         $ckey    = DI::config()->get('twitter', 'consumerkey');
307         $csecret = DI::config()->get('twitter', 'consumersecret');
308         $otoken  = DI::pConfig()->get(local_user(), 'twitter', 'oauthtoken');
309         $osecret = DI::pConfig()->get(local_user(), 'twitter', 'oauthsecret');
310
311         $enabled            = intval(DI::pConfig()->get(local_user(), 'twitter', 'post'));
312         $defenabled         = intval(DI::pConfig()->get(local_user(), 'twitter', 'post_by_default'));
313         $mirrorenabled      = intval(DI::pConfig()->get(local_user(), 'twitter', 'mirror_posts'));
314         $importenabled      = intval(DI::pConfig()->get(local_user(), 'twitter', 'import'));
315         $create_userenabled = intval(DI::pConfig()->get(local_user(), 'twitter', 'create_user'));
316
317         // Hide the submit button by default
318         $submit = '';
319
320         if ((!$ckey) && (!$csecret)) {
321                 /* no global consumer keys
322                  * display warning and skip personal config
323                  */
324                 $html = '<p>' . DI::l10n()->t('No consumer key pair for Twitter found. Please contact your site administrator.') . '</p>';
325         } else {
326                 // ok we have a consumer key pair now look into the OAuth stuff
327                 if ((!$otoken) && (!$osecret)) {
328                         /* the user has not yet connected the account to twitter...
329                          * get a temporary OAuth key/secret pair and display a button with
330                          * which the user can request a PIN to connect the account to a
331                          * account at Twitter.
332                          */
333                         $connection = new TwitterOAuth($ckey, $csecret);
334                         try {
335                                 $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
336
337                                 $html = '<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>';
338                                 $html .= '<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>';
339                                 $html .= '<div id="twitter-pin-wrapper">';
340                                 $html .= '<label id="twitter-pin-label" for="twitter-pin">' . DI::l10n()->t('Copy the PIN from Twitter here') . '</label>';
341                                 $html .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
342                                 $html .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result['oauth_token'] . '" />';
343                                 $html .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result['oauth_token_secret'] . '" />';
344                                 $html .= '</div>';
345
346                                 $submit = null;
347                         } catch (TwitterOAuthException $e) {
348                                 $html = '<p>' . DI::l10n()->t('An error occured: ') . $e->getMessage() . '</p>';
349                         }
350                 } else {
351                         /*                       * *
352                          *  we have an OAuth key / secret pair for the user
353                          *  so let's give a chance to disable the postings to Twitter
354                          */
355                         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
356                         try {
357                                 $account = $connection->get('account/verify_credentials');
358                                 if (property_exists($account, 'screen_name') &&
359                                         property_exists($account, 'description') &&
360                                         property_exists($account, 'profile_image_url')
361                                 ) {
362                                         $connected = DI::l10n()->t('Currently connected to: <a href="https://twitter.com/%1$s" target="_twitter">%1$s</a>', $account->screen_name);
363                                 } else {
364                                         Logger::notice('Invalid twitter info (verify credentials).', ['auth' => TwitterOAuth::class]);
365                                 }
366
367                                 if ($user['hidewall']) {
368                                         $privacy_warning = 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.');
369                                 }
370
371                                 $t    = Renderer::getMarkupTemplate('connector_settings.tpl', 'addon/twitter/');
372                                 $html = Renderer::replaceMacros($t, [
373                                         '$l10n' => [
374                                                 'connected'       => $connected ?? '',
375                                                 'invalid'         => DI::l10n()->t('Invalid Twitter info'),
376                                                 'disconnect'      => DI::l10n()->t('Disconnect'),
377                                                 'privacy_warning' => $privacy_warning ?? '',
378                                         ],
379
380                                         '$account'     => $account,
381                                         '$enable'      => ['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.')],
382                                         '$default'     => ['twitter-default', DI::l10n()->t('Send public postings to Twitter by default'), $defenabled],
383                                         '$mirror'      => ['twitter-mirror', DI::l10n()->t('Mirror all posts from twitter that are no replies'), $mirrorenabled],
384                                         '$import'      => ['twitter-import', DI::l10n()->t('Import the remote timeline'), $importenabled],
385                                         '$create_user' => ['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.')],
386                                 ]);
387
388                                 // Enable the default submit button
389                                 $submit = null;
390                         } catch (TwitterOAuthException $e) {
391                                 $html = '<p>' . DI::l10n()->t('An error occured: ') . $e->getMessage() . '</p>';
392                         }
393                 }
394         }
395
396         $data = [
397                 'connector' => 'twitter',
398                 'title'     => DI::l10n()->t('Twitter Import/Export/Mirror'),
399                 'enabled'   => $enabled,
400                 'image'     => 'images/twitter.png',
401                 'html'      => $html,
402                 'submit'    => $submit ?? null,
403         ];
404 }
405
406 function twitter_hook_fork(App $a, array &$b)
407 {
408         DI::logger()->debug('twitter_hook_fork', $b);
409
410         if ($b['name'] != 'notifier_normal') {
411                 return;
412         }
413
414         $post = $b['data'];
415
416         // Deletion checks are done in twitter_delete_item()
417         if ($post['deleted']) {
418                 return;
419         }
420
421         // Editing is not supported by the addon
422         if ($post['created'] !== $post['edited']) {
423                 DI::logger()->info('Editing is not supported by the addon');
424                 $b['execute'] = false;
425                 return;
426         }
427
428         // if post comes from twitter don't send it back
429         if (($post['extid'] == Protocol::TWITTER) || twitter_get_id($post['extid'])) {
430                 DI::logger()->info('If post comes from twitter don\'t send it back');
431                 $b['execute'] = false;
432                 return;
433         }
434
435         if (substr($post['app'], 0, 7) == 'Twitter') {
436                 DI::logger()->info('No Twitter app');
437                 $b['execute'] = false;
438                 return;
439         }
440
441         if (DI::pConfig()->get($post['uid'], 'twitter', 'import')) {
442                 // Don't fork if it isn't a reply to a twitter post
443                 if (($post['parent'] != $post['id']) && !Post::exists(['id' => $post['parent'], 'network' => Protocol::TWITTER])) {
444                         Logger::notice('No twitter parent found', ['item' => $post['id']]);
445                         $b['execute'] = false;
446                         return;
447                 }
448         } else {
449                 // Comments are never exported when we don't import the twitter timeline
450                 if (!strstr($post['postopts'], 'twitter') || ($post['parent'] != $post['id']) || $post['private']) {
451                         DI::logger()->info('Comments are never exported when we don\'t import the twitter timeline');
452                         $b['execute'] = false;
453                         return;
454                 }
455     }
456 }
457
458 function twitter_post_local(App $a, array &$b)
459 {
460         if ($b['edit']) {
461                 return;
462         }
463
464         if (!local_user() || (local_user() != $b['uid'])) {
465                 return;
466         }
467
468         $twitter_post = intval(DI::pConfig()->get(local_user(), 'twitter', 'post'));
469         $twitter_enable = (($twitter_post && !empty($_REQUEST['twitter_enable'])) ? intval($_REQUEST['twitter_enable']) : 0);
470
471         // if API is used, default to the chosen settings
472         if ($b['api_source'] && intval(DI::pConfig()->get(local_user(), 'twitter', 'post_by_default'))) {
473                 $twitter_enable = 1;
474         }
475
476         if (!$twitter_enable) {
477                 return;
478         }
479
480         if (strlen($b['postopts'])) {
481                 $b['postopts'] .= ',';
482         }
483
484         $b['postopts'] .= 'twitter';
485 }
486
487 function twitter_probe_detect(App $a, array &$hookData)
488 {
489         // Don't overwrite an existing result
490         if (isset($hookData['result'])) {
491                 return;
492         }
493
494         // Avoid a lookup for the wrong network
495         if (!in_array($hookData['network'], ['', Protocol::TWITTER])) {
496                 return;
497         }
498
499         if (preg_match('=([^@]+)@(?:mobile\.)?twitter\.com$=i', $hookData['uri'], $matches)) {
500                 $nick = $matches[1];
501         } elseif (preg_match('=^https?://(?:mobile\.)?twitter\.com/(.+)=i', $hookData['uri'], $matches)) {
502                 if (strpos($matches[1], '/') !== false) {
503                         // Status case: https://twitter.com/<nick>/status/<status id>
504                         // Not a contact
505                         $hookData['result'] = false;
506                         return;
507                 }
508
509                 $nick = $matches[1];
510         } else {
511                 return;
512         }
513
514         $user = twitter_fetchuser($nick);
515
516         if ($user) {
517                 $hookData['result'] = twitter_user_to_contact($user);
518         }
519 }
520
521 function twitter_item_by_link(App $a, array &$hookData)
522 {
523         // Don't overwrite an existing result
524         if (isset($hookData['item_id'])) {
525                 return;
526         }
527
528         // Relevancy check
529         if (!preg_match('#^https?://(?:mobile\.|www\.)?twitter.com/[^/]+/status/(\d+).*#', $hookData['uri'], $matches)) {
530                 return;
531         }
532
533         // From now on, any early return should abort the whole chain since we've established it was a Twitter URL
534         $hookData['item_id'] = false;
535
536         // Node-level configuration check
537         if (empty(DI::config()->get('twitter', 'consumerkey')) || empty(DI::config()->get('twitter', 'consumersecret'))) {
538                 return;
539         }
540
541         // No anonymous import
542         if (!$hookData['uid']) {
543                 return;
544         }
545
546         if (
547                 empty(DI::pConfig()->get($hookData['uid'], 'twitter', 'oauthtoken'))
548                 || empty(DI::pConfig()->get($hookData['uid'], 'twitter', 'oauthsecret'))
549         ) {
550                 notice(DI::l10n()->t('Please connect a Twitter account in your Social Network settings to import Twitter posts.'));
551                 return;
552         }
553
554         $status = twitter_statuses_show($matches[1]);
555
556         if (empty($status->id_str)) {
557                 notice(DI::l10n()->t('Twitter post not found.'));
558                 return;
559         }
560
561         $item = twitter_createpost($a, $hookData['uid'], $status, [], true, false, false);
562         if (!empty($item)) {
563                 $hookData['item_id'] = Item::insert($item);
564         }
565 }
566
567 function twitter_api_post(string $apiPath, string $pid, int $uid): ?bool
568 {
569         if (empty($pid)) {
570                 return false;
571         }
572
573         return twitter_api_call($uid, $apiPath, ['id' => $pid]);
574 }
575
576 function twitter_api_call(int $uid, string $apiPath, array $parameters = []): ?bool
577 {
578         $ckey = DI::config()->get('twitter', 'consumerkey');
579         $csecret = DI::config()->get('twitter', 'consumersecret');
580         $otoken = DI::pConfig()->get($uid, 'twitter', 'oauthtoken');
581         $osecret = DI::pConfig()->get($uid, 'twitter', 'oauthsecret');
582
583         // If the addon is not configured (general or for this user) quit here
584         if (empty($ckey) || empty($csecret) || empty($otoken) || empty($osecret)) {
585                 return null;
586         }
587
588         try {
589                 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
590                 $result = $connection->post($apiPath, $parameters);
591
592                 if ($connection->getLastHttpCode() != 200) {
593                         throw new Exception($result->errors[0]->message ?? json_encode($result), $connection->getLastHttpCode());
594                 }
595
596                 if (!empty($result->errors)) {
597                         throw new Exception($result->errors[0]->message, $result->errors[0]->code);
598                 }
599
600                 Logger::info('[twitter] API call successful', ['apiPath' => $apiPath, 'parameters' => $parameters]);
601                 Logger::debug('[twitter] API call result', ['apiPath' => $apiPath, 'parameters' => $parameters, 'result' => $result]);
602
603                 return true;
604         } catch (TwitterOAuthException $twitterOAuthException) {
605                 Logger::warning('Unable to communicate with twitter', ['apiPath' => $apiPath, 'parameters' => $parameters, 'code' => $twitterOAuthException->getCode(), 'exception' => $twitterOAuthException]);
606                 return false;
607         } catch (Exception $e) {
608                 Logger::notice('[twitter] API call failed', ['apiPath' => $apiPath, 'parameters' => $parameters, 'code' => $e->getCode(), 'message' => $e->getMessage()]);
609                 return false;
610         }
611 }
612
613 function twitter_get_id(string $uri)
614 {
615         if ((substr($uri, 0, 9) != 'twitter::') || (strlen($uri) <= 9)) {
616                 return 0;
617         }
618
619         $id = substr($uri, 9);
620         if (!is_numeric($id)) {
621                 return 0;
622         }
623
624         return (int)$id;
625 }
626
627 function twitter_post_hook(App $a, array &$b)
628 {
629         DI::logger()->info('twitter_post_hook', $b);
630
631         if ($b['deleted']) {
632                 twitter_delete_item($b);
633                 return;
634         }
635
636         // Post to Twitter
637         if (!DI::pConfig()->get($b['uid'], 'twitter', 'import')
638                 && ($b['private'] || ($b['created'] !== $b['edited']))) {
639                 return;
640         }
641
642         $b['body'] = Post\Media::addAttachmentsToBody($b['uri-id'], $b['body']);
643
644         $thr_parent = null;
645
646         if ($b['parent'] != $b['id']) {
647                 Logger::debug('Got comment', ['item' => $b]);
648
649                 // Looking if its a reply to a twitter post
650                 if (!twitter_get_id($b['parent-uri']) &&
651                         !twitter_get_id($b['extid']) &&
652                         !twitter_get_id($b['thr-parent'])) {
653                         Logger::info('No twitter post', ['parent' => $b['parent']]);
654                         return;
655                 }
656
657                 $condition = ['uri' => $b['thr-parent'], 'uid' => $b['uid']];
658                 $thr_parent = Post::selectFirst(['uri', 'extid', 'author-link', 'author-nick', 'author-network'], $condition);
659                 if (!DBA::isResult($thr_parent)) {
660                         Logger::warning('No parent found', ['thr-parent' => $b['thr-parent']]);
661                         return;
662                 }
663
664                 if ($thr_parent['author-network'] == Protocol::TWITTER) {
665                         $nickname = '@[url=' . $thr_parent['author-link'] . ']' . $thr_parent['author-nick'] . '[/url]';
666                         $nicknameplain = '@' . $thr_parent['author-nick'];
667
668                         Logger::info('Comparing', ['nickname' => $nickname, 'nicknameplain' => $nicknameplain, 'body' => $b['body']]);
669                         if ((strpos($b['body'], $nickname) === false) && (strpos($b['body'], $nicknameplain) === false)) {
670                                 $b['body'] = $nickname . ' ' . $b['body'];
671                         }
672                 }
673
674                 Logger::debug('Parent found', ['parent' => $thr_parent]);
675         } else {
676                 if ($b['private'] || !strstr($b['postopts'], 'twitter')) {
677                         return;
678                 }
679
680                 // Dont't post if the post doesn't belong to us.
681                 // This is a check for forum postings
682                 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
683                 if ($b['contact-id'] != $self['id']) {
684                         return;
685                 }
686         }
687
688         if ($b['verb'] == Activity::LIKE) {
689                 Logger::info('Like', ['uid' => $b['uid'], 'id' => twitter_get_id($b['thr-parent'])]);
690
691                 twitter_api_post('favorites/create', twitter_get_id($b['thr-parent']), $b['uid']);
692
693                 return;
694         }
695
696         if ($b['verb'] == Activity::ANNOUNCE) {
697                 Logger::info('Retweet', ['uid' => $b['uid'], 'id' => twitter_get_id($b['thr-parent'])]);
698                 twitter_retweet($b['uid'], twitter_get_id($b['thr-parent']));
699                 return;
700         }
701
702         if ($b['created'] !== $b['edited']) {
703                 return;
704         }
705
706         // if post comes from twitter don't send it back
707         if (($b['extid'] == Protocol::TWITTER) || twitter_get_id($b['extid'])) {
708                 return;
709         }
710
711         if ($b['app'] == 'Twitter') {
712                 return;
713         }
714
715         Logger::notice('twitter post invoked', ['id' => $b['id'], 'guid' => $b['guid']]);
716
717         DI::pConfig()->load($b['uid'], 'twitter');
718
719         $ckey    = DI::config()->get('twitter', 'consumerkey');
720         $csecret = DI::config()->get('twitter', 'consumersecret');
721         $otoken  = DI::pConfig()->get($b['uid'], 'twitter', 'oauthtoken');
722         $osecret = DI::pConfig()->get($b['uid'], 'twitter', 'oauthsecret');
723
724         if ($ckey && $csecret && $otoken && $osecret) {
725                 Logger::info('We have customer key and oauth stuff, going to send.');
726
727                 // If it's a repeated message from twitter then do a native retweet and exit
728                 if (twitter_is_retweet($a, $b['uid'], $b['body'])) {
729                         return;
730                 }
731
732                 Codebird::setConsumerKey($ckey, $csecret);
733                 $cb = Codebird::getInstance();
734                 $cb->setToken($otoken, $osecret);
735
736                 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
737
738                 // Set the timeout for upload to 30 seconds
739                 $connection->setTimeouts(10, 30);
740
741                 $max_char = 280;
742
743                 // Handling non-native reshares
744                 $b['body'] = Friendica\Content\Text\BBCode::convertShare(
745                         $b['body'],
746                         function (array $attributes, array $author_contact, $content, $is_quote_share) {
747                                 return twitter_convert_share($attributes, $author_contact, $content, $is_quote_share);
748                         }
749                 );
750
751                 $b['body'] = twitter_update_mentions($b['body']);
752
753                 $msgarr = Plaintext::getPost($b, $max_char, true, BBCode::TWITTER);
754                 Logger::info('Got plaintext', ['id' => $b['id'], 'message' => $msgarr]);
755                 $msg = $msgarr['text'];
756
757                 if (($msg == '') && isset($msgarr['title'])) {
758                         $msg = Plaintext::shorten($msgarr['title'], $max_char - 50, $b['uid']);
759                 }
760
761                 // Add the link to the body if the type isn't a photo or there are more than 4 images in the post
762                 if (!empty($msgarr['url']) && (strpos($msg, $msgarr['url']) === false) && (($msgarr['type'] != 'photo') || empty($msgarr['images']) || (count($msgarr['images']) > 4))) {
763                         $msg .= "\n" . $msgarr['url'];
764                 }
765
766                 if (empty($msg)) {
767                         Logger::notice('Empty message', ['id' => $b['id']]);
768                         return;
769                 }
770
771                 // and now tweet it :-)
772                 $post = [];
773
774                 if (!empty($msgarr['images'])) {
775                         Logger::info('Got images', ['id' => $b['id'], 'images' => $msgarr['images']]);
776                         try {
777                                 $media_ids = [];
778                                 foreach ($msgarr['images'] as $image) {
779                                         if (count($media_ids) == 4) {
780                                                 continue;
781                                         }
782
783                                         $img_str = DI::httpClient()->fetch($image['url']);
784
785                                         $tempfile = tempnam(System::getTempPath(), 'cache');
786                                         file_put_contents($tempfile, $img_str);
787
788                                         Logger::info('Uploading', ['id' => $b['id'], 'image' => $image['url']]);
789                                         $media = $connection->upload('media/upload', ['media' => $tempfile]);
790
791                                         unlink($tempfile);
792
793                                         if (isset($media->media_id_string)) {
794                                                 $media_ids[] = $media->media_id_string;
795
796                                                 if (!empty($image['description'])) {
797                                                         $data = ['media_id' => $media->media_id_string,
798                                                                 'alt_text' => ['text' => substr($image['description'], 0, 420)]];
799                                                         $ret = $cb->media_metadata_create($data);
800                                                         Logger::info('Metadata create', ['id' => $b['id'], 'data' => $data, 'return' => $ret]);
801                                                 }
802                                         } else {
803                                                 Logger::error('Failed upload', ['id' => $b['id'], 'image' => $image['url'], 'return' => $media]);
804                                                 throw new Exception('Failed upload of ' . $image['url']);
805                                         }
806                                 }
807                                 $post['media_ids'] = implode(',', $media_ids);
808                                 if (empty($post['media_ids'])) {
809                                         unset($post['media_ids']);
810                                 }
811                         } catch (Exception $e) {
812                                 Logger::warning('Exception when trying to send to Twitter', ['id' => $b['id'], 'message' => $e->getMessage()]);
813                         }
814                 }
815
816                 $post['status'] = $msg;
817
818                 if ($thr_parent) {
819                         $post['in_reply_to_status_id'] = twitter_get_id($thr_parent['uri']);
820                 }
821
822                 $result = $connection->post('statuses/update', $post);
823                 Logger::info('twitter_post send', ['id' => $b['id'], 'result' => $result]);
824
825                 if (!empty($result->source)) {
826                         DI::config()->set('twitter', 'application_name', strip_tags($result->source));
827                 }
828
829                 if (!empty($result->errors)) {
830                         Logger::error('Send to Twitter failed', ['id' => $b['id'], 'error' => $result->errors]);
831                         Worker::defer();
832                 } elseif ($thr_parent) {
833                         Logger::notice('Post send, updating extid', ['id' => $b['id'], 'extid' => $result->id_str]);
834                         Item::update(['extid' => 'twitter::' . $result->id_str], ['id' => $b['id']]);
835                 }
836         }
837 }
838
839 function twitter_delete_item(array $item)
840 {
841         if (!$item['deleted']) {
842                 return;
843         }
844
845         if ($item['parent'] != $item['id']) {
846                 Logger::debug('Deleting comment/announce', ['item' => $item]);
847
848                 // Looking if it's a reply to a twitter post
849                 if (!twitter_get_id($item['parent-uri']) &&
850                         !twitter_get_id($item['extid']) &&
851                         !twitter_get_id($item['thr-parent'])) {
852                         Logger::info('No twitter post', ['parent' => $item['parent']]);
853                         return;
854                 }
855
856                 $condition = ['uri' => $item['thr-parent'], 'uid' => $item['uid']];
857                 $thr_parent = Post::selectFirst(['uri', 'extid', 'author-link', 'author-nick', 'author-network'], $condition);
858                 if (!DBA::isResult($thr_parent)) {
859                         Logger::warning('No parent found', ['thr-parent' => $item['thr-parent']]);
860                         return;
861                 }
862
863                 Logger::debug('Parent found', ['parent' => $thr_parent]);
864         } else {
865                 if (!strstr($item['extid'], 'twitter')) {
866                         DI::logger()->info('Not a Twitter post', ['extid' => $item['extid']]);
867                         return;
868                 }
869
870                 // Don't delete if the post doesn't belong to us.
871                 // This is a check for forum postings
872                 $self = DBA::selectFirst('contact', ['id'], ['uid' => $item['uid'], 'self' => true]);
873                 if ($item['contact-id'] != $self['id']) {
874                         DI::logger()->info('Don\'t delete if the post doesn\'t belong to the user', ['contact-id' => $item['contact-id'], 'self' => $self['id']]);
875                         return;
876                 }
877         }
878
879         /**
880          * @TODO Remaining caveat: Comments posted on Twitter and imported in Friendica do not trigger any Notifier task,
881          *       possibly because they are private to the user and don't require any remote deletion notifications sent.
882          *       Comments posted on Friendica and mirrored on Twitter trigger the Notifier task and the Twitter counter-part
883          *       will be deleted accordingly.
884          */
885         if ($item['verb'] == Activity::POST) {
886                 Logger::info('Delete post/comment', ['uid' => $item['uid'], 'id' => twitter_get_id($item['extid'])]);
887                 twitter_api_post('statuses/destroy', twitter_get_id($item['extid']), $item['uid']);
888                 return;
889         }
890
891         if ($item['verb'] == Activity::LIKE) {
892                 Logger::info('Unlike', ['uid' => $item['uid'], 'id' => twitter_get_id($item['thr-parent'])]);
893                 twitter_api_post('favorites/destroy', twitter_get_id($item['thr-parent']), $item['uid']);
894                 return;
895         }
896
897         if ($item['verb'] == Activity::ANNOUNCE && !empty($thr_parent['uri'])) {
898                 Logger::info('Unretweet', ['uid' => $item['uid'], 'extid' => $thr_parent['uri'], 'id' => twitter_get_id($thr_parent['uri'])]);
899                 twitter_api_post('statuses/unretweet', twitter_get_id($thr_parent['uri']), $item['uid']);
900                 return;
901         }
902 }
903
904 function twitter_addon_admin_post(App $a)
905 {
906         DI::config()->set('twitter', 'consumerkey', trim($_POST['consumerkey'] ?? ''));
907         DI::config()->set('twitter', 'consumersecret', trim($_POST['consumersecret'] ?? ''));
908 }
909
910 function twitter_addon_admin(App $a, string &$o)
911 {
912         $t = Renderer::getMarkupTemplate('admin.tpl', 'addon/twitter/');
913
914         $o = Renderer::replaceMacros($t, [
915                 '$submit' => DI::l10n()->t('Save Settings'),
916                 // name, label, value, help, [extra values]
917                 '$consumerkey' => ['consumerkey', DI::l10n()->t('Consumer key'), DI::config()->get('twitter', 'consumerkey'), ''],
918                 '$consumersecret' => ['consumersecret', DI::l10n()->t('Consumer secret'), DI::config()->get('twitter', 'consumersecret'), ''],
919         ]);
920 }
921
922 function twitter_cron(App $a)
923 {
924         $last = DI::config()->get('twitter', 'last_poll');
925
926         $poll_interval = intval(DI::config()->get('twitter', 'poll_interval'));
927         if (!$poll_interval) {
928                 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
929         }
930
931         if ($last) {
932                 $next = $last + ($poll_interval * 60);
933                 if ($next > time()) {
934                         Logger::notice('twitter: poll intervall not reached');
935                         return;
936                 }
937         }
938         Logger::notice('twitter: cron_start');
939
940         $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'twitter', 'k' => 'mirror_posts', 'v' => true]);
941         foreach ($pconfigs as $rr) {
942                 Logger::notice('Fetching', ['user' => $rr['uid']]);
943                 Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'addon/twitter/twitter_sync.php', 1, (int) $rr['uid']);
944         }
945
946         $abandon_days = intval(DI::config()->get('system', 'account_abandon_days'));
947         if ($abandon_days < 1) {
948                 $abandon_days = 0;
949         }
950
951         $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
952
953         $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'twitter', 'k' => 'import', 'v' => true]);
954         foreach ($pconfigs as $rr) {
955                 if ($abandon_days != 0) {
956                         if (!DBA::exists('user', ["`uid` = ? AND `login_date` >= ?", $rr['uid'], $abandon_limit])) {
957                                 Logger::notice('abandoned account: timeline from user will not be imported', ['user' => $rr['uid']]);
958                                 continue;
959                         }
960                 }
961
962                 Logger::notice('importing timeline', ['user' => $rr['uid']]);
963                 Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], 'addon/twitter/twitter_sync.php', 2, (int) $rr['uid']);
964                 /*
965                         // To-Do
966                         // check for new contacts once a day
967                         $last_contact_check = DI::pConfig()->get($rr['uid'],'pumpio','contact_check');
968                         if($last_contact_check)
969                         $next_contact_check = $last_contact_check + 86400;
970                         else
971                         $next_contact_check = 0;
972
973                         if($next_contact_check <= time()) {
974                         pumpio_getallusers($a, $rr["uid"]);
975                         DI::pConfig()->set($rr['uid'],'pumpio','contact_check',time());
976                         }
977                         */
978         }
979
980         Logger::notice('twitter: cron_end');
981
982         DI::config()->set('twitter', 'last_poll', time());
983 }
984
985 function twitter_expire(App $a)
986 {
987         $days = DI::config()->get('twitter', 'expire');
988
989         if ($days == 0) {
990                 return;
991         }
992
993         Logger::notice('Start deleting expired posts');
994
995         $r = Post::select(['id', 'guid'], ['deleted' => true, 'network' => Protocol::TWITTER]);
996         while ($row = Post::fetch($r)) {
997                 Logger::info('[twitter] Delete expired item', ['id' => $row['id'], 'guid' => $row['guid'], 'callstack' => \Friendica\Core\System::callstack()]);
998                 Item::markForDeletionById($row['id']);
999         }
1000         DBA::close($r);
1001
1002         Logger::notice('End deleting expired posts');
1003
1004         Logger::notice('Start expiry');
1005
1006         $pconfigs = DBA::selectToArray('pconfig', [], ['cat' => 'twitter', 'k' => 'import', 'v' => true]);
1007         foreach ($pconfigs as $rr) {
1008                 Logger::notice('twitter_expire', ['user' => $rr['uid']]);
1009                 Item::expire($rr['uid'], $days, Protocol::TWITTER, true);
1010         }
1011
1012         Logger::notice('End expiry');
1013 }
1014
1015 function twitter_prepare_body(App $a, array &$b)
1016 {
1017         if ($b['item']['network'] != Protocol::TWITTER) {
1018                 return;
1019         }
1020
1021         if ($b['preview']) {
1022                 $max_char = 280;
1023                 $item = $b['item'];
1024                 $item['plink'] = DI::baseUrl()->get() . '/display/' . $item['guid'];
1025
1026                 $condition = ['uri' => $item['thr-parent'], 'uid' => local_user()];
1027                 $orig_post = Post::selectFirst(['author-link'], $condition);
1028                 if (DBA::isResult($orig_post)) {
1029                         $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post['author-link']);
1030                         $nickname = '@[url=' . $orig_post['author-link'] . ']' . $nicknameplain . '[/url]';
1031                         $nicknameplain = '@' . $nicknameplain;
1032
1033                         if ((strpos($item['body'], $nickname) === false) && (strpos($item['body'], $nicknameplain) === false)) {
1034                                 $item['body'] = $nickname . ' ' . $item['body'];
1035                         }
1036                 }
1037
1038                 $msgarr = Plaintext::getPost($item, $max_char, true, BBCode::TWITTER);
1039                 $msg = $msgarr['text'];
1040
1041                 if (isset($msgarr['url']) && ($msgarr['type'] != 'photo')) {
1042                         $msg .= ' ' . $msgarr['url'];
1043                 }
1044
1045                 if (isset($msgarr['image'])) {
1046                         $msg .= ' ' . $msgarr['image'];
1047                 }
1048
1049                 $b['html'] = nl2br(htmlspecialchars($msg));
1050         }
1051 }
1052
1053 function twitter_statuses_show(string $id, TwitterOAuth $twitterOAuth = null)
1054 {
1055         if ($twitterOAuth === null) {
1056                 $ckey = DI::config()->get('twitter', 'consumerkey');
1057                 $csecret = DI::config()->get('twitter', 'consumersecret');
1058
1059                 if (empty($ckey) || empty($csecret)) {
1060                         return new stdClass();
1061                 }
1062
1063                 $twitterOAuth = new TwitterOAuth($ckey, $csecret);
1064         }
1065
1066         $parameters = ['trim_user' => false, 'tweet_mode' => 'extended', 'id' => $id, 'include_ext_alt_text' => true];
1067
1068         return $twitterOAuth->get('statuses/show', $parameters);
1069 }
1070
1071 /**
1072  * Parse Twitter status URLs since Twitter removed OEmbed
1073  *
1074  * @param App   $a
1075  * @param array $b Expected format:
1076  *                 [
1077  *                      'url' => [URL to parse],
1078  *                      'format' => 'json'|'',
1079  *                      'text' => Output parameter
1080  *                 ]
1081  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1082  */
1083 function twitter_parse_link(App $a, array &$b)
1084 {
1085         // Only handle Twitter status URLs
1086         if (!preg_match('#^https?://(?:mobile\.|www\.)?twitter.com/[^/]+/status/(\d+).*#', $b['url'], $matches)) {
1087                 return;
1088         }
1089
1090         $status = twitter_statuses_show($matches[1]);
1091
1092         if (empty($status->id)) {
1093                 return;
1094         }
1095
1096         $item = twitter_createpost($a, 0, $status, [], true, false, true);
1097
1098         if ($b['format'] == 'json') {
1099                 $images = [];
1100                 foreach ($status->extended_entities->media ?? [] as $media) {
1101                         if (!empty($media->media_url_https)) {
1102                                 $images[] = [
1103                                         'src'    => $media->media_url_https,
1104                                         'width'  => $media->sizes->thumb->w,
1105                                         'height' => $media->sizes->thumb->h,
1106                                 ];
1107                         }
1108                 }
1109
1110                 $b['text'] = [
1111                         'data' => [
1112                                 'type' => 'link',
1113                                 'url' => $item['plink'],
1114                                 'title' => DI::l10n()->t('%s on Twitter', $status->user->name),
1115                                 'text' => BBCode::toPlaintext($item['body'], false),
1116                                 'images' => $images,
1117                         ],
1118                         'contentType' => 'attachment',
1119                         'success' => true,
1120                 ];
1121         } else {
1122                 $b['text'] = BBCode::getShareOpeningTag(
1123                         $item['author-name'],
1124                         $item['author-link'],
1125                         $item['author-avatar'],
1126                         $item['plink'],
1127                         $item['created']
1128                 );
1129                 $b['text'] .= $item['body'] . '[/share]';
1130         }
1131 }
1132
1133
1134 /*********************
1135  *
1136  * General functions
1137  *
1138  *********************/
1139
1140
1141 /**
1142  * @brief Build the item array for the mirrored post
1143  *
1144  * @param App $a Application class
1145  * @param integer $uid User id
1146  * @param object $post Twitter object with the post
1147  *
1148  * @return array item data to be posted
1149  */
1150 function twitter_do_mirrorpost(App $a, int $uid, $post)
1151 {
1152         $datarray['uid'] = $uid;
1153         $datarray['extid'] = 'twitter::' . $post->id;
1154         $datarray['title'] = '';
1155
1156         if (!empty($post->retweeted_status)) {
1157                 // We don't support nested shares, so we mustn't show quotes as shares on retweets
1158                 $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true, -1);
1159
1160                 if (empty($item['body'])) {
1161                         return [];
1162                 }
1163
1164                 $datarray['body'] = "\n" . BBCode::getShareOpeningTag(
1165                         $item['author-name'],
1166                         $item['author-link'],
1167                         $item['author-avatar'],
1168                         $item['plink'],
1169                         $item['created']
1170                 );
1171
1172                 $datarray['body'] .= $item['body'] . '[/share]';
1173         } else {
1174                 $item = twitter_createpost($a, $uid, $post, ['id' => 0], false, false, false, -1);
1175
1176                 if (empty($item['body'])) {
1177                         return [];
1178                 }
1179
1180                 $datarray['body'] = $item['body'];
1181         }
1182
1183         $datarray['app'] = $item['app'];
1184         $datarray['verb'] = $item['verb'];
1185
1186         if (isset($item['location'])) {
1187                 $datarray['location'] = $item['location'];
1188         }
1189
1190         if (isset($item['coord'])) {
1191                 $datarray['coord'] = $item['coord'];
1192         }
1193
1194         return $datarray;
1195 }
1196
1197 function twitter_fetchtimeline(App $a, int $uid)
1198 {
1199         $ckey    = DI::config()->get('twitter', 'consumerkey');
1200         $csecret = DI::config()->get('twitter', 'consumersecret');
1201         $otoken  = DI::pConfig()->get($uid, 'twitter', 'oauthtoken');
1202         $osecret = DI::pConfig()->get($uid, 'twitter', 'oauthsecret');
1203         $lastid  = DI::pConfig()->get($uid, 'twitter', 'lastid');
1204
1205         $application_name = DI::config()->get('twitter', 'application_name');
1206
1207         if ($application_name == '') {
1208                 $application_name = DI::baseUrl()->getHostname();
1209         }
1210
1211         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1212
1213         // Ensure to have the own contact
1214         try {
1215                 twitter_fetch_own_contact($a, $uid);
1216         } catch (TwitterOAuthException $e) {
1217                 Logger::warning('Error fetching own contact', ['uid' => $uid, 'message' => $e->getMessage()]);
1218                 return;
1219         }
1220
1221         $parameters = [
1222                 'exclude_replies' => true,
1223                 'trim_user' => false,
1224                 'contributor_details' => true,
1225                 'include_rts' => true,
1226                 'tweet_mode' => 'extended',
1227                 'include_ext_alt_text' => true,
1228         ];
1229
1230         $first_time = ($lastid == '');
1231
1232         if ($lastid != '') {
1233                 $parameters['since_id'] = $lastid;
1234         }
1235
1236         try {
1237                 $items = $connection->get('statuses/user_timeline', $parameters);
1238         } catch (TwitterOAuthException $e) {
1239                 Logger::warning('Error fetching timeline', ['uid' => $uid, 'message' => $e->getMessage()]);
1240                 return;
1241         }
1242
1243         if (!is_array($items)) {
1244                 Logger::notice('No items', ['user' => $uid]);
1245                 return;
1246         }
1247
1248         $posts = array_reverse($items);
1249
1250         Logger::notice('Start processing posts', ['from' => $lastid, 'user' => $uid, 'count' => count($posts)]);
1251
1252         if (count($posts)) {
1253                 foreach ($posts as $post) {
1254                         if ($post->id_str > $lastid) {
1255                                 $lastid = $post->id_str;
1256                                 DI::pConfig()->set($uid, 'twitter', 'lastid', $lastid);
1257                         }
1258
1259                         if ($first_time) {
1260                                 continue;
1261                         }
1262
1263                         if (!stristr($post->source, $application_name)) {
1264                                 Logger::info('Preparing mirror post', ['twitter-id' => $post->id_str, 'uid' => $uid]);
1265
1266                                 $mirrorpost = twitter_do_mirrorpost($a, $uid, $post);
1267
1268                                 if (empty($mirrorpost['body'])) {
1269                                         continue;
1270                                 }
1271
1272                                 Logger::info('Posting mirror post', ['twitter-id' => $post->id_str, 'uid' => $uid]);
1273
1274                                 Post\Delayed::add($mirrorpost['extid'], $mirrorpost, PRIORITY_MEDIUM, Post\Delayed::UNPREPARED);
1275                         }
1276                 }
1277         }
1278         DI::pConfig()->set($uid, 'twitter', 'lastid', $lastid);
1279         Logger::info('Last ID for user ' . $uid . ' is now ' . $lastid);
1280 }
1281
1282 function twitter_fix_avatar($avatar)
1283 {
1284         $new_avatar = str_replace('_normal.', '_400x400.', $avatar);
1285
1286         $info = Images::getInfoFromURLCached($new_avatar);
1287         if (!$info) {
1288                 $new_avatar = $avatar;
1289         }
1290
1291         return $new_avatar;
1292 }
1293
1294 function twitter_get_relation($uid, $target, $contact = [])
1295 {
1296         if (isset($contact['rel'])) {
1297                 $relation = $contact['rel'];
1298         } else {
1299                 $relation = 0;
1300         }
1301
1302         $ckey = DI::config()->get('twitter', 'consumerkey');
1303         $csecret = DI::config()->get('twitter', 'consumersecret');
1304         $otoken = DI::pConfig()->get($uid, 'twitter', 'oauthtoken');
1305         $osecret = DI::pConfig()->get($uid, 'twitter', 'oauthsecret');
1306         $own_id = DI::pConfig()->get($uid, 'twitter', 'own_id');
1307
1308         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1309         $parameters = ['source_id' => $own_id, 'target_screen_name' => $target];
1310
1311         try {
1312                 $status = $connection->get('friendships/show', $parameters);
1313                 if ($connection->getLastHttpCode() !== 200) {
1314                         throw new Exception($status->errors[0]->message ?? 'HTTP response code ' . $connection->getLastHttpCode(), $status->errors[0]->code ?? $connection->getLastHttpCode());
1315                 }
1316
1317                 $following = $status->relationship->source->following;
1318                 $followed = $status->relationship->source->followed_by;
1319
1320                 if ($following && !$followed) {
1321                         $relation = Contact::SHARING;
1322                 } elseif (!$following && $followed) {
1323                         $relation = Contact::FOLLOWER;
1324                 } elseif ($following && $followed) {
1325                         $relation = Contact::FRIEND;
1326                 } elseif (!$following && !$followed) {
1327                         $relation = 0;
1328                 }
1329
1330                 Logger::info('Fetched friendship relation', ['user' => $uid, 'target' => $target, 'relation' => $relation]);
1331         } catch (Throwable $e) {
1332                 Logger::warning('Error fetching friendship status', ['uid' => $uid, 'target' => $target, 'message' => $e->getMessage()]);
1333         }
1334
1335         return $relation;
1336 }
1337
1338 /**
1339  * @param $data
1340  * @return array
1341  */
1342 function twitter_user_to_contact($data)
1343 {
1344         if (empty($data->id_str)) {
1345                 return [];
1346         }
1347
1348         $baseurl = 'https://twitter.com';
1349         $url = $baseurl . '/' . $data->screen_name;
1350         $addr = $data->screen_name . '@twitter.com';
1351
1352         $fields = [
1353                 'url'      => $url,
1354                 'nurl'     => Strings::normaliseLink($url),
1355                 'uri-id'   => ItemURI::getIdByURI($url),
1356                 'network'  => Protocol::TWITTER,
1357                 'alias'    => 'twitter::' . $data->id_str,
1358                 'baseurl'  => $baseurl,
1359                 'name'     => $data->name,
1360                 'nick'     => $data->screen_name,
1361                 'addr'     => $addr,
1362                 'location' => $data->location,
1363                 'about'    => $data->description,
1364                 'photo'    => twitter_fix_avatar($data->profile_image_url_https),
1365                 'header'   => $data->profile_banner_url ?? $data->profile_background_image_url_https,
1366         ];
1367
1368         return $fields;
1369 }
1370
1371 function twitter_get_contact($data, int $uid = 0)
1372 {
1373         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $uid, 'alias' => 'twitter::' . $data->id_str]);
1374         if (DBA::isResult($contact)) {
1375                 return $contact['id'];
1376         } else {
1377                 return twitter_fetch_contact($uid, $data, false);
1378         }
1379 }
1380
1381 function twitter_fetch_contact($uid, $data, $create_user)
1382 {
1383         $fields = twitter_user_to_contact($data);
1384
1385         if (empty($fields)) {
1386                 return -1;
1387         }
1388
1389         // photo comes from twitter_user_to_contact but shouldn't be saved directly in the contact row
1390         $avatar = $fields['photo'];
1391         unset($fields['photo']);
1392
1393         // Update the public contact
1394         $pcontact = DBA::selectFirst('contact', ['id'], ['uid' => 0, 'alias' => 'twitter::' . $data->id_str]);
1395         if (DBA::isResult($pcontact)) {
1396                 $cid = $pcontact['id'];
1397         } else {
1398                 $cid = Contact::getIdForURL($fields['url'], 0, false, $fields);
1399         }
1400
1401         if (!empty($cid)) {
1402                 Contact::update($fields, ['id' => $cid]);
1403                 Contact::updateAvatar($cid, $avatar);
1404         } else {
1405                 Logger::warning('No contact found', ['fields' => $fields]);
1406         }
1407
1408         $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'alias' => 'twitter::' . $data->id_str]);
1409         if (!DBA::isResult($contact) && empty($cid)) {
1410                 Logger::warning('User contact not found', ['uid' => $uid, 'twitter-id' => $data->id_str]);
1411                 return 0;
1412         } elseif (!$create_user) {
1413                 return $cid;
1414         }
1415
1416         if (!DBA::isResult($contact)) {
1417                 $relation = twitter_get_relation($uid, $data->screen_name);
1418
1419                 // create contact record
1420                 $fields['uid'] = $uid;
1421                 $fields['created'] = DateTimeFormat::utcNow();
1422                 $fields['poll'] = 'twitter::' . $data->id_str;
1423                 $fields['rel'] = $relation;
1424                 $fields['priority'] = 1;
1425                 $fields['writable'] = true;
1426                 $fields['blocked'] = false;
1427                 $fields['readonly'] = false;
1428                 $fields['pending'] = false;
1429
1430                 if (!Contact::insert($fields)) {
1431                         return false;
1432                 }
1433
1434                 $contact_id = DBA::lastInsertId();
1435
1436                 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1437         } else {
1438                 if ($contact['readonly'] || $contact['blocked']) {
1439                         Logger::notice('Contact is blocked or readonly.', ['nickname' => $contact['nick']]);
1440                         return -1;
1441                 }
1442
1443                 $contact_id = $contact['id'];
1444                 $update = false;
1445
1446                 // Update the contact relation once per day
1447                 if ($contact['updated'] < DateTimeFormat::utc('now -24 hours')) {
1448                         $fields['rel'] = twitter_get_relation($uid, $data->screen_name, $contact);
1449                         $update = true;
1450                 }
1451
1452                 if ($contact['name'] != $data->name) {
1453                         $fields['name-date'] = $fields['uri-date'] = DateTimeFormat::utcNow();
1454                         $update = true;
1455                 }
1456
1457                 if ($contact['nick'] != $data->screen_name) {
1458                         $fields['uri-date'] = DateTimeFormat::utcNow();
1459                         $update = true;
1460                 }
1461
1462                 if (($contact['location'] != $data->location) || ($contact['about'] != $data->description)) {
1463                         $update = true;
1464                 }
1465
1466                 if ($update) {
1467                         $fields['updated'] = DateTimeFormat::utcNow();
1468                         Contact::update($fields, ['id' => $contact['id']]);
1469                         Logger::info('Updated contact', ['id' => $contact['id'], 'nick' => $data->screen_name]);
1470                 }
1471         }
1472
1473         Contact::updateAvatar($contact_id, $avatar);
1474
1475         return $contact_id;
1476 }
1477
1478 /**
1479  * @param string $screen_name
1480  * @return stdClass|null
1481  * @throws Exception
1482  */
1483 function twitter_fetchuser($screen_name)
1484 {
1485         $ckey = DI::config()->get('twitter', 'consumerkey');
1486         $csecret = DI::config()->get('twitter', 'consumersecret');
1487
1488         try {
1489                 // Fetching user data
1490                 $connection = new TwitterOAuth($ckey, $csecret);
1491                 $parameters = ['screen_name' => $screen_name];
1492                 $user = $connection->get('users/show', $parameters);
1493         } catch (TwitterOAuthException $e) {
1494                 Logger::warning('Error fetching user', ['user' => $screen_name, 'message' => $e->getMessage()]);
1495                 return null;
1496         }
1497
1498         if (!is_object($user)) {
1499                 return null;
1500         }
1501
1502         return $user;
1503 }
1504
1505 /**
1506  * Replaces Twitter entities with Friendica-friendly links.
1507  *
1508  * The Twitter API gives indices for each entity, which allows for fine-grained replacement.
1509  *
1510  * First, we need to collect everything that needs to be replaced, what we will replace it with, and the start index.
1511  * Then we sort the indices decreasingly, and we replace from the end of the body to the start in order for the next
1512  * index to be correct even after the last replacement.
1513  *
1514  * @param string   $body
1515  * @param stdClass $status
1516  * @return array
1517  * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1518  */
1519 function twitter_expand_entities($body, stdClass $status)
1520 {
1521         $plain = $body;
1522         $contains_urls = false;
1523
1524         $taglist = [];
1525
1526         $replacementList = [];
1527
1528         foreach ($status->entities->hashtags AS $hashtag) {
1529                 $replace = '#[url=' . DI::baseUrl()->get() . '/search?tag=' . $hashtag->text . ']' . $hashtag->text . '[/url]';
1530                 $taglist['#' . $hashtag->text] = ['#', $hashtag->text, ''];
1531
1532                 $replacementList[$hashtag->indices[0]] = [
1533                         'replace' => $replace,
1534                         'length' => $hashtag->indices[1] - $hashtag->indices[0],
1535                 ];
1536         }
1537
1538         foreach ($status->entities->user_mentions AS $mention) {
1539                 $replace = '@[url=https://twitter.com/' . rawurlencode($mention->screen_name) . ']' . $mention->screen_name . '[/url]';
1540                 $taglist['@' . $mention->screen_name] = ['@', $mention->screen_name, 'https://twitter.com/' . rawurlencode($mention->screen_name)];
1541
1542                 $replacementList[$mention->indices[0]] = [
1543                         'replace' => $replace,
1544                         'length' => $mention->indices[1] - $mention->indices[0],
1545                 ];
1546         }
1547
1548         foreach ($status->entities->urls ?? [] as $url) {
1549                 $plain = str_replace($url->url, '', $plain);
1550
1551                 if ($url->url && $url->expanded_url && $url->display_url) {
1552                         // Quote tweet, we just remove the quoted tweet URL from the body, the share block will be added later.
1553                         if (!empty($status->quoted_status) && isset($status->quoted_status_id_str)
1554                                 && substr($url->expanded_url, -strlen($status->quoted_status_id_str)) == $status->quoted_status_id_str
1555                         ) {
1556                                 $replacementList[$url->indices[0]] = [
1557                                         'replace' => '',
1558                                         'length' => $url->indices[1] - $url->indices[0],
1559                                 ];
1560                                 continue;
1561                         }
1562
1563                         $contains_urls = true;
1564
1565                         $expanded_url = $url->expanded_url;
1566
1567                         // Quickfix: Workaround for URL with '[' and ']' in it
1568                         if (strpos($expanded_url, '[') || strpos($expanded_url, ']')) {
1569                                 $expanded_url = $url->url;
1570                         }
1571
1572                         $replacementList[$url->indices[0]] = [
1573                                 'replace' => '[url=' . $expanded_url . ']' . $url->display_url . '[/url]',
1574                                 'length' => $url->indices[1] - $url->indices[0],
1575                         ];
1576                 }
1577         }
1578
1579         krsort($replacementList);
1580
1581         foreach ($replacementList as $startIndex => $parameters) {
1582                 $body = Strings::substringReplace($body, $parameters['replace'], $startIndex, $parameters['length']);
1583         }
1584
1585         $body = trim($body);
1586
1587         return ['body' => trim($body), 'plain' => trim($plain), 'taglist' => $taglist, 'urls' => $contains_urls];
1588 }
1589
1590 /**
1591  * Store entity attachments
1592  *
1593  * @param integer $uriId
1594  * @param object $post Twitter object with the post
1595  */
1596 function twitter_store_attachments(int $uriId, $post)
1597 {
1598         if (!empty($post->extended_entities->media)) {
1599                 foreach ($post->extended_entities->media AS $medium) {
1600                         switch ($medium->type) {
1601                                 case 'photo':
1602                                         $attachment = ['uri-id' => $uriId, 'type' => Post\Media::IMAGE];
1603
1604                                         $attachment['url'] = $medium->media_url_https . '?name=large';
1605                                         $attachment['width'] = $medium->sizes->large->w;
1606                                         $attachment['height'] = $medium->sizes->large->h;
1607
1608                                         if ($medium->sizes->small->w != $attachment['width']) {
1609                                                 $attachment['preview'] = $medium->media_url_https . '?name=small';
1610                                                 $attachment['preview-width'] = $medium->sizes->small->w;
1611                                                 $attachment['preview-height'] = $medium->sizes->small->h;
1612                                         }
1613
1614                                         $attachment['name'] = $medium->display_url ?? null;
1615                                         $attachment['description'] = $medium->ext_alt_text ?? null;
1616                                         Logger::debug('Photo attachment', ['attachment' => $attachment]);
1617                                         Post\Media::insert($attachment);
1618                                         break;
1619                                 case 'video':
1620                                 case 'animated_gif':
1621                                         $attachment = ['uri-id' => $uriId, 'type' => Post\Media::VIDEO];
1622                                         if (is_array($medium->video_info->variants)) {
1623                                                 $bitrate = 0;
1624                                                 // We take the video with the highest bitrate
1625                                                 foreach ($medium->video_info->variants AS $variant) {
1626                                                         if (($variant->content_type == 'video/mp4') && ($variant->bitrate >= $bitrate)) {
1627                                                                 $attachment['url'] = $variant->url;
1628                                                                 $bitrate = $variant->bitrate;
1629                                                         }
1630                                                 }
1631                                         }
1632
1633                                         $attachment['name'] = $medium->display_url ?? null;
1634                                         $attachment['preview'] = $medium->media_url_https . ':small';
1635                                         $attachment['preview-width'] = $medium->sizes->small->w;
1636                                         $attachment['preview-height'] = $medium->sizes->small->h;
1637                                         $attachment['description'] = $medium->ext_alt_text ?? null;
1638                                         Logger::debug('Video attachment', ['attachment' => $attachment]);
1639                                         Post\Media::insert($attachment);
1640                                         break;
1641                                 default:
1642                                         Logger::notice('Unknown media type', ['medium' => $medium]);
1643                         }
1644                 }
1645         }
1646
1647         if (!empty($post->entities->urls)) {
1648                 foreach ($post->entities->urls as $url) {
1649                         $attachment = ['uri-id' => $uriId, 'type' => Post\Media::UNKNOWN, 'url' => $url->expanded_url, 'name' => $url->display_url];
1650                         Logger::debug('Attached link', ['attachment' => $attachment]);
1651                         Post\Media::insert($attachment);
1652                 }
1653         }
1654 }
1655
1656 /**
1657  * @brief Fetch media entities and add media links to the body
1658  *
1659  * @param object  $post      Twitter object with the post
1660  * @param array   $postarray Array of the item that is about to be posted
1661  * @param integer $uriId URI Id used to store tags. -1 = don't store tags for this post.
1662  */
1663 function twitter_media_entities($post, array &$postarray, int $uriId = -1)
1664 {
1665         // There are no media entities? So we quit.
1666         if (empty($post->extended_entities->media)) {
1667                 return;
1668         }
1669
1670         // This is a pure media post, first search for all media urls
1671         $media = [];
1672         foreach ($post->extended_entities->media AS $medium) {
1673                 if (!isset($media[$medium->url])) {
1674                         $media[$medium->url] = '';
1675                 }
1676                 switch ($medium->type) {
1677                         case 'photo':
1678                                 if (!empty($medium->ext_alt_text)) {
1679                                         Logger::info('Got text description', ['alt_text' => $medium->ext_alt_text]);
1680                                         $media[$medium->url] .= "\n[img=" . $medium->media_url_https .']' . $medium->ext_alt_text . '[/img]';
1681                                 } else {
1682                                         $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
1683                                 }
1684
1685                                 $postarray['object-type'] = Activity\ObjectType::IMAGE;
1686                                 $postarray['post-type'] = Item::PT_IMAGE;
1687                                 break;
1688                         case 'video':
1689                                 // Currently deactivated, since this causes the video to be display before the content
1690                                 // We have to figure out a better way for declaring the post type and the display style.
1691                                 //$postarray['post-type'] = Item::PT_VIDEO;
1692                         case 'animated_gif':
1693                                 if (!empty($medium->ext_alt_text)) {
1694                                         Logger::info('Got text description', ['alt_text' => $medium->ext_alt_text]);
1695                                         $media[$medium->url] .= "\n[img=" . $medium->media_url_https .']' . $medium->ext_alt_text . '[/img]';
1696                                 } else {
1697                                         $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
1698                                 }
1699
1700                                 $postarray['object-type'] = Activity\ObjectType::VIDEO;
1701                                 if (is_array($medium->video_info->variants)) {
1702                                         $bitrate = 0;
1703                                         // We take the video with the highest bitrate
1704                                         foreach ($medium->video_info->variants AS $variant) {
1705                                                 if (($variant->content_type == 'video/mp4') && ($variant->bitrate >= $bitrate)) {
1706                                                         $media[$medium->url] = "\n[video]" . $variant->url . '[/video]';
1707                                                         $bitrate = $variant->bitrate;
1708                                                 }
1709                                         }
1710                                 }
1711                                 break;
1712                 }
1713         }
1714
1715         if ($uriId != -1) {
1716                 foreach ($media AS $key => $value) {
1717                         $postarray['body'] = str_replace($key, '', $postarray['body']);
1718                 }
1719                 return;
1720         }
1721
1722         // Now we replace the media urls.
1723         foreach ($media AS $key => $value) {
1724                 $postarray['body'] = str_replace($key, "\n" . $value . "\n", $postarray['body']);
1725         }
1726 }
1727
1728 /**
1729  * Undocumented function
1730  *
1731  * @param App $a
1732  * @param integer $uid User ID
1733  * @param object $post Incoming Twitter post
1734  * @param array $self
1735  * @param bool $create_user Should users be created?
1736  * @param bool $only_existing_contact Only import existing contacts if set to "true"
1737  * @param bool $noquote
1738  * @param integer $uriId URI Id used to store tags. 0 = create a new one; -1 = don't store tags for this post.
1739  * @return array item array
1740  */
1741 function twitter_createpost(App $a, int $uid, $post, array $self, $create_user, bool $only_existing_contact, bool $noquote, int $uriId = 0): array
1742 {
1743         $postarray = [];
1744         $postarray['network'] = Protocol::TWITTER;
1745         $postarray['uid'] = $uid;
1746         $postarray['wall'] = 0;
1747         $postarray['uri'] = 'twitter::' . $post->id_str;
1748         $postarray['protocol'] = Conversation::PARCEL_TWITTER;
1749         $postarray['source'] = json_encode($post);
1750         $postarray['direction'] = Conversation::PULL;
1751
1752         if (empty($uriId)) {
1753                 $uriId = $postarray['uri-id'] = ItemURI::insert(['uri' => $postarray['uri']]);
1754         }
1755
1756         // Don't import our own comments
1757         if (Post::exists(['extid' => $postarray['uri'], 'uid' => $uid])) {
1758                 Logger::info('Item found', ['extid' => $postarray['uri']]);
1759                 return [];
1760         }
1761
1762         $contactid = 0;
1763
1764         if ($post->in_reply_to_status_id_str != '') {
1765                 $thr_parent = 'twitter::' . $post->in_reply_to_status_id_str;
1766
1767                 $item = Post::selectFirst(['uri'], ['uri' => $thr_parent, 'uid' => $uid]);
1768                 if (!DBA::isResult($item)) {
1769                         $item = Post::selectFirst(['uri'], ['extid' => $thr_parent, 'uid' => $uid, 'gravity' => GRAVITY_COMMENT]);
1770                 }
1771
1772                 if (DBA::isResult($item)) {
1773                         $postarray['thr-parent'] = $item['uri'];
1774                         $postarray['object-type'] = Activity\ObjectType::COMMENT;
1775                 } else {
1776                         $postarray['object-type'] = Activity\ObjectType::NOTE;
1777                 }
1778
1779                 // Is it me?
1780                 $own_id = DI::pConfig()->get($uid, 'twitter', 'own_id');
1781
1782                 if ($post->user->id_str == $own_id) {
1783                         $self = Contact::selectFirst(['id', 'name', 'url', 'photo'], ['self' => true, 'uid' => $uid]);
1784                         if (DBA::isResult($self)) {
1785                                 $contactid = $self['id'];
1786
1787                                 $postarray['owner-name']   = $self['name'];
1788                                 $postarray['owner-link']   = $self['url'];
1789                                 $postarray['owner-avatar'] = $self['photo'];
1790                         } else {
1791                                 Logger::error('No self contact found', ['uid' => $uid]);
1792                                 return [];
1793                         }
1794                 }
1795                 // Don't create accounts of people who just comment something
1796                 $create_user = false;
1797         } else {
1798                 $postarray['object-type'] = Activity\ObjectType::NOTE;
1799         }
1800
1801         if ($contactid == 0) {
1802                 $contactid = twitter_fetch_contact($uid, $post->user, $create_user);
1803
1804                 $postarray['owner-id']     = twitter_get_contact($post->user);
1805                 $postarray['owner-name']   = $post->user->name;
1806                 $postarray['owner-link']   = 'https://twitter.com/' . $post->user->screen_name;
1807                 $postarray['owner-avatar'] = twitter_fix_avatar($post->user->profile_image_url_https);
1808         }
1809
1810         if (($contactid == 0) && !$only_existing_contact) {
1811                 $contactid = $self['id'];
1812         } elseif ($contactid <= 0) {
1813                 Logger::info('Contact ID is zero or less than zero.');
1814                 return [];
1815         }
1816
1817         $postarray['contact-id']    = $contactid;
1818         $postarray['verb']          = Activity::POST;
1819         $postarray['author-id']     = $postarray['owner-id'];
1820         $postarray['author-name']   = $postarray['owner-name'];
1821         $postarray['author-link']   = $postarray['owner-link'];
1822         $postarray['author-avatar'] = $postarray['owner-avatar'];
1823         $postarray['plink']         = 'https://twitter.com/' . $post->user->screen_name . '/status/' . $post->id_str;
1824         $postarray['app']           = strip_tags($post->source);
1825
1826         if ($post->user->protected) {
1827                 $postarray['private']   = Item::PRIVATE;
1828                 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1829         } else {
1830                 $postarray['private']   = Item::UNLISTED;
1831                 $postarray['allow_cid'] = '';
1832         }
1833
1834         if (!empty($post->full_text)) {
1835                 $postarray['body'] = $post->full_text;
1836         } else {
1837                 $postarray['body'] = $post->text;
1838         }
1839
1840         // When the post contains links then use the correct object type
1841         if (count($post->entities->urls) > 0) {
1842                 $postarray['object-type'] = Activity\ObjectType::BOOKMARK;
1843         }
1844
1845         // Search for media links
1846         twitter_media_entities($post, $postarray, $uriId);
1847
1848         $converted = twitter_expand_entities($postarray['body'], $post);
1849
1850         // When the post contains external links then images or videos are just "decorations".
1851         if (!empty($converted['urls'])) {
1852                 $postarray['post-type'] = Item::PT_NOTE;
1853         }
1854
1855         $postarray['body'] = $converted['body'];
1856         $postarray['created'] = DateTimeFormat::utc($post->created_at);
1857         $postarray['edited'] = DateTimeFormat::utc($post->created_at);
1858
1859         if ($uriId > 0) {
1860                 twitter_store_tags($uriId, $converted['taglist']);
1861                 twitter_store_attachments($uriId, $post);
1862         }
1863
1864         if (!empty($post->place->name)) {
1865                 $postarray['location'] = $post->place->name;
1866         }
1867         if (!empty($post->place->full_name)) {
1868                 $postarray['location'] = $post->place->full_name;
1869         }
1870         if (!empty($post->geo->coordinates)) {
1871                 $postarray['coord'] = $post->geo->coordinates[0] . ' ' . $post->geo->coordinates[1];
1872         }
1873         if (!empty($post->coordinates->coordinates)) {
1874                 $postarray['coord'] = $post->coordinates->coordinates[1] . ' ' . $post->coordinates->coordinates[0];
1875         }
1876         if (!empty($post->retweeted_status)) {
1877                 $retweet = twitter_createpost($a, $uid, $post->retweeted_status, $self, false, false, $noquote);
1878
1879                 if (empty($retweet['body'])) {
1880                         return [];
1881                 }
1882
1883                 if (!$noquote) {
1884                         // Store the original tweet
1885                         Item::insert($retweet);
1886
1887                         // CHange the other post into a reshare activity
1888                         $postarray['verb'] = Activity::ANNOUNCE;
1889                         $postarray['gravity'] = GRAVITY_ACTIVITY;
1890                         $postarray['object-type'] = Activity\ObjectType::NOTE;
1891
1892                         $postarray['thr-parent'] = $retweet['uri'];
1893                 } else {
1894                         $retweet['source']       = $postarray['source'];
1895                         $retweet['direction']    = $postarray['direction'];
1896                         $retweet['private']      = $postarray['private'];
1897                         $retweet['allow_cid']    = $postarray['allow_cid'];
1898                         $retweet['contact-id']   = $postarray['contact-id'];
1899                         $retweet['owner-id']     = $postarray['owner-id'];
1900                         $retweet['owner-name']   = $postarray['owner-name'];
1901                         $retweet['owner-link']   = $postarray['owner-link'];
1902                         $retweet['owner-avatar'] = $postarray['owner-avatar'];
1903
1904                         $postarray = $retweet;
1905                 }
1906         }
1907
1908         if (!empty($post->quoted_status)) {
1909                 if ($noquote) {
1910                         // To avoid recursive share blocks we just provide the link to avoid removing quote context.
1911                         $postarray['body'] .= "\n\nhttps://twitter.com/" . $post->quoted_status->user->screen_name . "/status/" . $post->quoted_status->id_str;
1912                 } else {
1913                         $quoted = twitter_createpost($a, 0, $post->quoted_status, $self, false, false, true);
1914                         if (!empty($quoted['body'])) {
1915                                 Item::insert($quoted);
1916                                 $post = Post::selectFirst(['guid', 'uri-id'], ['uri' => $quoted['uri'], 'uid' => 0]);
1917                                 Logger::info('Stored quoted post', ['uid' => $uid, 'uri-id' => $uriId, 'post' => $post]);
1918
1919                                 $postarray['body'] .= "\n" . BBCode::getShareOpeningTag(
1920                                                 $quoted['author-name'],
1921                                                 $quoted['author-link'],
1922                                                 $quoted['author-avatar'],
1923                                                 $quoted['plink'],
1924                                                 $quoted['created'],
1925                                                 $post['guid'] ?? ''
1926                                         );
1927
1928                                 $postarray['body'] .= $quoted['body'] . '[/share]';
1929                         } else {
1930                                 // Quoted post author is blocked/ignored, so we just provide the link to avoid removing quote context.
1931                                 $postarray['body'] .= "\n\nhttps://twitter.com/" . $post->quoted_status->user->screen_name . '/status/' . $post->quoted_status->id_str;
1932                         }
1933                 }
1934         }
1935
1936         return $postarray;
1937 }
1938
1939 /**
1940  * Store tags and mentions
1941  *
1942  * @param integer $uriId
1943  * @param array $taglist
1944  * @return void
1945  */
1946 function twitter_store_tags(int $uriId, array $taglist)
1947 {
1948         foreach ($taglist as $tag) {
1949                 Tag::storeByHash($uriId, $tag[0], $tag[1], $tag[2]);
1950         }
1951 }
1952
1953 function twitter_fetchparentposts(App $a, int $uid, $post, TwitterOAuth $connection, array $self)
1954 {
1955         Logger::info('Fetching parent posts', ['user' => $uid, 'post' => $post->id_str]);
1956
1957         $posts = [];
1958
1959         while (!empty($post->in_reply_to_status_id_str)) {
1960                 try {
1961                         $post = twitter_statuses_show($post->in_reply_to_status_id_str, $connection);
1962                 } catch (TwitterOAuthException $e) {
1963                         Logger::warning('Error fetching parent post', ['uid' => $uid, 'post' => $post->id_str, 'message' => $e->getMessage()]);
1964                         break;
1965                 }
1966
1967                 if (empty($post)) {
1968                         Logger::info("twitter_fetchparentposts: Can't fetch post");
1969                         break;
1970                 }
1971
1972                 if (empty($post->id_str)) {
1973                         Logger::info('twitter_fetchparentposts: This is not a post', ['post' => $post]);
1974                         break;
1975                 }
1976
1977                 if (Post::exists(['uri' => 'twitter::' . $post->id_str, 'uid' => $uid])) {
1978                         break;
1979                 }
1980
1981                 $posts[] = $post;
1982         }
1983
1984         Logger::info('twitter_fetchparentposts: Fetching ' . count($posts) . ' parents');
1985
1986         $posts = array_reverse($posts);
1987
1988         if (!empty($posts)) {
1989                 foreach ($posts as $post) {
1990                         $postarray = twitter_createpost($a, $uid, $post, $self, false, !DI::pConfig()->get($uid, 'twitter', 'create_user'), false);
1991
1992                         if (empty($postarray['body'])) {
1993                                 continue;
1994                         }
1995
1996                         $item = Item::insert($postarray);
1997
1998                         $postarray['id'] = $item;
1999
2000                         Logger::notice('twitter_fetchparentpost: User ' . $self['nick'] . ' posted parent timeline item ' . $item);
2001                 }
2002         }
2003 }
2004
2005 function twitter_fetchhometimeline(App $a, int $uid)
2006 {
2007         $ckey    = DI::config()->get('twitter', 'consumerkey');
2008         $csecret = DI::config()->get('twitter', 'consumersecret');
2009         $otoken  = DI::pConfig()->get($uid, 'twitter', 'oauthtoken');
2010         $osecret = DI::pConfig()->get($uid, 'twitter', 'oauthsecret');
2011         $create_user = DI::pConfig()->get($uid, 'twitter', 'create_user');
2012         $mirror_posts = DI::pConfig()->get($uid, 'twitter', 'mirror_posts');
2013
2014         Logger::info('Fetching timeline', ['uid' => $uid]);
2015
2016         $application_name = DI::config()->get('twitter', 'application_name');
2017
2018         if ($application_name == '') {
2019                 $application_name = DI::baseUrl()->getHostname();
2020         }
2021
2022         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
2023
2024         try {
2025                 $own_contact = twitter_fetch_own_contact($a, $uid);
2026         } catch (TwitterOAuthException $e) {
2027                 Logger::warning('Error fetching own contact', ['uid' => $uid, 'message' => $e->getMessage()]);
2028                 return;
2029         }
2030
2031         $contact = Contact::selectFirst(['nick'], ['id' => $own_contact, 'uid' => $uid]);
2032         if (DBA::isResult($contact)) {
2033                 $own_id = $contact['nick'];
2034         } else {
2035                 Logger::warning('Own twitter contact not found', ['uid' => $uid]);
2036                 return;
2037         }
2038
2039         $self = User::getOwnerDataById($uid);
2040         if ($self === false) {
2041                 Logger::warning('Own contact not found', ['uid' => $uid]);
2042                 return;
2043         }
2044
2045         $parameters = [
2046                 'exclude_replies' => false,
2047                 'trim_user' => false,
2048                 'contributor_details' => true,
2049                 'include_rts' => true,
2050                 'tweet_mode' => 'extended',
2051                 'include_ext_alt_text' => true,
2052                 //'count' => 200,
2053         ];
2054
2055         // Fetching timeline
2056         $lastid = DI::pConfig()->get($uid, 'twitter', 'lasthometimelineid');
2057
2058         $first_time = ($lastid == '');
2059
2060         if ($lastid != '') {
2061                 $parameters['since_id'] = $lastid;
2062         }
2063
2064         try {
2065                 $items = $connection->get('statuses/home_timeline', $parameters);
2066         } catch (TwitterOAuthException $e) {
2067                 Logger::warning('Error fetching home timeline', ['uid' => $uid, 'message' => $e->getMessage()]);
2068                 return;
2069         }
2070
2071         if (!is_array($items)) {
2072                 Logger::warning('home timeline is no array', ['items' => $items]);
2073                 return;
2074         }
2075
2076         if (empty($items)) {
2077                 Logger::notice('No new timeline content', ['uid' => $uid]);
2078                 return;
2079         }
2080
2081         $posts = array_reverse($items);
2082
2083         Logger::notice('Processing timeline', ['lastid' => $lastid, 'uid' => $uid, 'count' => count($posts)]);
2084
2085         if (count($posts)) {
2086                 foreach ($posts as $post) {
2087                         if ($post->id_str > $lastid) {
2088                                 $lastid = $post->id_str;
2089                                 DI::pConfig()->set($uid, 'twitter', 'lasthometimelineid', $lastid);
2090                         }
2091
2092                         if ($first_time) {
2093                                 continue;
2094                         }
2095
2096                         if (stristr($post->source, $application_name) && $post->user->screen_name == $own_id) {
2097                                 Logger::info('Skip previously sent post');
2098                                 continue;
2099                         }
2100
2101                         if ($mirror_posts && $post->user->screen_name == $own_id && $post->in_reply_to_status_id_str == '') {
2102                                 Logger::info('Skip post that will be mirrored');
2103                                 continue;
2104                         }
2105
2106                         if ($post->in_reply_to_status_id_str != '') {
2107                                 twitter_fetchparentposts($a, $uid, $post, $connection, $self);
2108                         }
2109
2110                         Logger::info('Preparing post ' . $post->id_str . ' for user ' . $uid);
2111
2112                         $postarray = twitter_createpost($a, $uid, $post, $self, $create_user, true, false);
2113
2114                         if (empty($postarray['body']) || trim($postarray['body']) == '') {
2115                                 Logger::info('Empty body for post ' . $post->id_str . ' and user ' . $uid);
2116                                 continue;
2117                         }
2118
2119                         $notify = false;
2120
2121                         if (empty($postarray['thr-parent'])) {
2122                                 $contact = DBA::selectFirst('contact', [], ['id' => $postarray['contact-id'], 'self' => false]);
2123                                 if (DBA::isResult($contact) && Item::isRemoteSelf($contact, $postarray)) {
2124                                         $notify = PRIORITY_MEDIUM;
2125                                 }
2126                         }
2127
2128                         $item = Item::insert($postarray, $notify);
2129                         $postarray['id'] = $item;
2130
2131                         Logger::notice('User ' . $uid . ' posted home timeline item ' . $item);
2132                 }
2133         }
2134         DI::pConfig()->set($uid, 'twitter', 'lasthometimelineid', $lastid);
2135
2136         Logger::info('Last timeline ID for user ' . $uid . ' is now ' . $lastid);
2137
2138         // Fetching mentions
2139         $lastid = DI::pConfig()->get($uid, 'twitter', 'lastmentionid');
2140
2141         $first_time = ($lastid == '');
2142
2143         if ($lastid != '') {
2144                 $parameters['since_id'] = $lastid;
2145         }
2146
2147         try {
2148                 $items = $connection->get('statuses/mentions_timeline', $parameters);
2149         } catch (TwitterOAuthException $e) {
2150                 Logger::warning('Error fetching mentions', ['uid' => $uid, 'message' => $e->getMessage()]);
2151                 return;
2152         }
2153
2154         if (!is_array($items)) {
2155                 Logger::warning('mentions are no arrays', ['items' => $items]);
2156                 return;
2157         }
2158
2159         $posts = array_reverse($items);
2160
2161         Logger::info('Fetching mentions for user ' . $uid . ' ' . sizeof($posts) . ' items');
2162
2163         if (count($posts)) {
2164                 foreach ($posts as $post) {
2165                         if ($post->id_str > $lastid) {
2166                                 $lastid = $post->id_str;
2167                         }
2168
2169                         if ($first_time) {
2170                                 continue;
2171                         }
2172
2173                         if ($post->in_reply_to_status_id_str != '') {
2174                                 twitter_fetchparentposts($a, $uid, $post, $connection, $self);
2175                         }
2176
2177                         $postarray = twitter_createpost($a, $uid, $post, $self, false, !$create_user, false);
2178
2179                         if (empty($postarray['body'])) {
2180                                 continue;
2181                         }
2182
2183                         $item = Item::insert($postarray);
2184
2185                         Logger::notice('User ' . $uid . ' posted mention timeline item ' . $item);
2186                 }
2187         }
2188
2189         DI::pConfig()->set($uid, 'twitter', 'lastmentionid', $lastid);
2190
2191         Logger::info('Last mentions ID for user ' . $uid . ' is now ' . $lastid);
2192 }
2193
2194 function twitter_fetch_own_contact(App $a, int $uid)
2195 {
2196         $ckey    = DI::config()->get('twitter', 'consumerkey');
2197         $csecret = DI::config()->get('twitter', 'consumersecret');
2198         $otoken  = DI::pConfig()->get($uid, 'twitter', 'oauthtoken');
2199         $osecret = DI::pConfig()->get($uid, 'twitter', 'oauthsecret');
2200
2201         $own_id = DI::pConfig()->get($uid, 'twitter', 'own_id');
2202
2203         $contact_id = 0;
2204
2205         if ($own_id == '') {
2206                 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
2207
2208                 // Fetching user data
2209                 // get() may throw TwitterOAuthException, but we will catch it later
2210                 $user = $connection->get('account/verify_credentials');
2211                 if (empty($user->id_str)) {
2212                         return false;
2213                 }
2214
2215                 DI::pConfig()->set($uid, 'twitter', 'own_id', $user->id_str);
2216
2217                 $contact_id = twitter_fetch_contact($uid, $user, true);
2218         } else {
2219                 $contact = Contact::selectFirst(['id'], ['uid' => $uid, 'alias' => 'twitter::' . $own_id]);
2220                 if (DBA::isResult($contact)) {
2221                         $contact_id = $contact['id'];
2222                 } else {
2223                         DI::pConfig()->delete($uid, 'twitter', 'own_id');
2224                 }
2225         }
2226
2227         return $contact_id;
2228 }
2229
2230 function twitter_is_retweet(App $a, int $uid, string $body): bool
2231 {
2232         $body = trim($body);
2233
2234         // Skip if it isn't a pure repeated messages
2235         // Does it start with a share?
2236         if (strpos($body, '[share') > 0) {
2237                 return false;
2238         }
2239
2240         // Does it end with a share?
2241         if (strlen($body) > (strrpos($body, '[/share]') + 8)) {
2242                 return false;
2243         }
2244
2245         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
2246         // Skip if there is no shared message in there
2247         if ($body == $attributes) {
2248                 return false;
2249         }
2250
2251         $link = '';
2252         preg_match("/link='(.*?)'/ism", $attributes, $matches);
2253         if (!empty($matches[1])) {
2254                 $link = $matches[1];
2255         }
2256
2257         preg_match('/link="(.*?)"/ism', $attributes, $matches);
2258         if (!empty($matches[1])) {
2259                 $link = $matches[1];
2260         }
2261
2262         $id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link);
2263         if ($id == $link) {
2264                 return false;
2265         }
2266         return twitter_retweet($uid, $id);
2267 }
2268
2269 function twitter_retweet(int $uid, int $id, int $item_id = 0): bool
2270 {
2271         Logger::info('Retweeting', ['user' => $uid, 'id' => $id]);
2272
2273         $result = twitter_api_post('statuses/retweet', $id, $uid);
2274
2275         Logger::info('Retweeted', ['user' => $uid, 'id' => $id, 'result' => $result]);
2276
2277         if (!empty($item_id) && !empty($result->id_str)) {
2278                 Logger::notice('Update extid', ['id' => $item_id, 'extid' => $result->id_str]);
2279                 Item::update(['extid' => 'twitter::' . $result->id_str], ['id' => $item_id]);
2280         }
2281
2282         return !isset($result->errors);
2283 }
2284
2285 function twitter_update_mentions(string $body): string
2286 {
2287         $URLSearchString = '^\[\]';
2288         $return = preg_replace_callback(
2289                 "/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
2290                 function ($matches) {
2291                         if (strpos($matches[1], 'twitter.com')) {
2292                                 $return = '@' . substr($matches[1], strrpos($matches[1], '/') + 1);
2293                         } else {
2294                                 $return = $matches[2] . ' (' . $matches[1] . ')';
2295                         }
2296
2297                         return $return;
2298                 },
2299                 $body
2300         );
2301
2302         return $return;
2303 }
2304
2305 function twitter_convert_share(array $attributes, array $author_contact, string $content, bool $is_quote_share): string
2306 {
2307         if (empty($author_contact)) {
2308                 return $content . "\n\n" . $attributes['link'];
2309         }
2310
2311         if (!empty($author_contact['network']) && ($author_contact['network'] == Protocol::TWITTER)) {
2312                 $mention = '@' . $author_contact['nick'];
2313         } else {
2314                 $mention = $author_contact['addr'];
2315         }
2316
2317         return ($is_quote_share ? "\n\n" : '' ) . 'RT ' . $mention . ': ' . $content . "\n\n" . $attributes['link'];
2318 }