"Remote-self" is now working for Twitter as well
[friendica-addons.git/.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 .htconfig.php or use the admin panel.
52  *
53  *     $a->config['twitter']['consumerkey'] = 'your consumer_key here';
54  *     $a->config['twitter']['consumersecret'] = 'your consumer_secret here';
55  *
56  *     To activate the addon itself add it to the $a->config['system']['addon']
57  *     setting. After this, your user can configure their Twitter account settings
58  *     from "Settings -> Addon Settings".
59  *
60  *     Requirements: PHP5, curl
61  */
62
63 use Abraham\TwitterOAuth\TwitterOAuth;
64 use Friendica\App;
65 use Friendica\Content\OEmbed;
66 use Friendica\Content\Text\Plaintext;
67 use Friendica\Core\Addon;
68 use Friendica\Core\Config;
69 use Friendica\Core\L10n;
70 use Friendica\Core\PConfig;
71 use Friendica\Core\Worker;
72 use Friendica\Model\GContact;
73 use Friendica\Model\Group;
74 use Friendica\Model\Item;
75 use Friendica\Model\ItemContent;
76 use Friendica\Model\Photo;
77 use Friendica\Model\Queue;
78 use Friendica\Model\User;
79 use Friendica\Object\Image;
80 use Friendica\Util\DateTimeFormat;
81 use Friendica\Util\Network;
82 use Friendica\Database\DBM;
83
84 require_once 'boot.php';
85 require_once 'include/dba.php';
86 require_once 'include/enotify.php';
87 require_once 'include/text.php';
88
89 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
90
91 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
92
93 function twitter_install()
94 {
95         //  we need some hooks, for the configuration and for sending tweets
96         Addon::registerHook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings');
97         Addon::registerHook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
98         Addon::registerHook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
99         Addon::registerHook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
100         Addon::registerHook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
101         Addon::registerHook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
102         Addon::registerHook('queue_predeliver', 'addon/twitter/twitter.php', 'twitter_queue_hook');
103         Addon::registerHook('follow', 'addon/twitter/twitter.php', 'twitter_follow');
104         Addon::registerHook('expire', 'addon/twitter/twitter.php', 'twitter_expire');
105         Addon::registerHook('prepare_body', 'addon/twitter/twitter.php', 'twitter_prepare_body');
106         Addon::registerHook('check_item_notification', 'addon/twitter/twitter.php', 'twitter_check_item_notification');
107         logger("installed twitter");
108 }
109
110 function twitter_uninstall()
111 {
112         Addon::unregisterHook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings');
113         Addon::unregisterHook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
114         Addon::unregisterHook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
115         Addon::unregisterHook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
116         Addon::unregisterHook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
117         Addon::unregisterHook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
118         Addon::unregisterHook('queue_predeliver', 'addon/twitter/twitter.php', 'twitter_queue_hook');
119         Addon::unregisterHook('follow', 'addon/twitter/twitter.php', 'twitter_follow');
120         Addon::unregisterHook('expire', 'addon/twitter/twitter.php', 'twitter_expire');
121         Addon::unregisterHook('prepare_body', 'addon/twitter/twitter.php', 'twitter_prepare_body');
122         Addon::unregisterHook('check_item_notification', 'addon/twitter/twitter.php', 'twitter_check_item_notification');
123
124         // old setting - remove only
125         Addon::unregisterHook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
126         Addon::unregisterHook('addon_settings', 'addon/twitter/twitter.php', 'twitter_settings');
127         Addon::unregisterHook('addon_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
128 }
129
130 function twitter_check_item_notification(App $a, &$notification_data)
131 {
132         $own_id = PConfig::get($notification_data["uid"], 'twitter', 'own_id');
133
134         $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
135                         intval($notification_data["uid"]),
136                         dbesc("twitter::".$own_id)
137         );
138
139         if ($own_user) {
140                 $notification_data["profiles"][] = $own_user[0]["url"];
141         }
142 }
143
144 function twitter_follow(App $a, &$contact)
145 {
146         logger("twitter_follow: Check if contact is twitter contact. " . $contact["url"], LOGGER_DEBUG);
147
148         if (!strstr($contact["url"], "://twitter.com") && !strstr($contact["url"], "@twitter.com")) {
149                 return;
150         }
151
152         // contact seems to be a twitter contact, so continue
153         $nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $contact["url"]);
154         $nickname = str_replace("@twitter.com", "", $nickname);
155
156         $uid = $a->user["uid"];
157
158         $ckey = Config::get('twitter', 'consumerkey');
159         $csecret = Config::get('twitter', 'consumersecret');
160         $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
161         $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
162
163         // If the addon is not configured (general or for this user) quit here
164         if (empty($ckey) || empty($csecret) || empty($otoken) || empty($osecret)) {
165                 $contact = false;
166                 return;
167         }
168
169         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
170         $connection->post('friendships/create', ['screen_name' => $nickname]);
171
172         twitter_fetchuser($a, $uid, $nickname);
173
174         $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
175                 FROM `contact` WHERE `uid` = %d AND `nick` = '%s'",
176                                 intval($uid),
177                                 dbesc($nickname));
178         if (count($r)) {
179                 $contact["contact"] = $r[0];
180         }
181 }
182
183 function twitter_jot_nets(App $a, &$b)
184 {
185         if (!local_user()) {
186                 return;
187         }
188
189         $tw_post = PConfig::get(local_user(), 'twitter', 'post');
190         if (intval($tw_post) == 1) {
191                 $tw_defpost = PConfig::get(local_user(), 'twitter', 'post_by_default');
192                 $selected = ((intval($tw_defpost) == 1) ? ' checked="checked" ' : '');
193                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="twitter_enable"' . $selected . ' value="1" /> '
194                         . L10n::t('Post to Twitter') . '</div>';
195         }
196 }
197
198 function twitter_settings_post(App $a, $post)
199 {
200         if (!local_user()) {
201                 return;
202         }
203         // don't check twitter settings if twitter submit button is not clicked
204         if (empty($_POST['twitter-disconnect']) && empty($_POST['twitter-submit'])) {
205                 return;
206         }
207
208         if (!empty($_POST['twitter-disconnect'])) {
209                 /*               * *
210                  * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
211                  * from the user configuration
212                  */
213                 PConfig::delete(local_user(), 'twitter', 'consumerkey');
214                 PConfig::delete(local_user(), 'twitter', 'consumersecret');
215                 PConfig::delete(local_user(), 'twitter', 'oauthtoken');
216                 PConfig::delete(local_user(), 'twitter', 'oauthsecret');
217                 PConfig::delete(local_user(), 'twitter', 'post');
218                 PConfig::delete(local_user(), 'twitter', 'post_by_default');
219                 PConfig::delete(local_user(), 'twitter', 'lastid');
220                 PConfig::delete(local_user(), 'twitter', 'mirror_posts');
221                 PConfig::delete(local_user(), 'twitter', 'import');
222                 PConfig::delete(local_user(), 'twitter', 'create_user');
223                 PConfig::delete(local_user(), 'twitter', 'own_id');
224         } else {
225                 if (isset($_POST['twitter-pin'])) {
226                         //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
227                         logger('got a Twitter PIN');
228                         $ckey    = Config::get('twitter', 'consumerkey');
229                         $csecret = Config::get('twitter', 'consumersecret');
230                         //  the token and secret for which the PIN was generated were hidden in the settings
231                         //  form as token and token2, we need a new connection to Twitter using these token
232                         //  and secret to request a Access Token with the PIN
233                         try {
234                                 if (empty($_POST['twitter-pin'])) {
235                                         throw new Exception(L10n::t('You submitted an empty PIN, please Sign In with Twitter again to get a new one.'));
236                                 }
237
238                                 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
239                                 $token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_POST['twitter-pin']]);
240                                 //  ok, now that we have the Access Token, save them in the user config
241                                 PConfig::set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
242                                 PConfig::set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
243                                 PConfig::set(local_user(), 'twitter', 'post', 1);
244                         } catch(Exception $e) {
245                                 info($e->getMessage());
246                         }
247                         //  reload the Addon Settings page, if we don't do it see Bug #42
248                         goaway('settings/connectors');
249                 } else {
250                         //  if no PIN is supplied in the POST variables, the user has changed the setting
251                         //  to post a tweet for every new __public__ posting to the wall
252                         PConfig::set(local_user(), 'twitter', 'post', intval($_POST['twitter-enable']));
253                         PConfig::set(local_user(), 'twitter', 'post_by_default', intval($_POST['twitter-default']));
254                         PConfig::set(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror']));
255                         PConfig::set(local_user(), 'twitter', 'import', intval($_POST['twitter-import']));
256                         PConfig::set(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user']));
257
258                         if (!intval($_POST['twitter-mirror'])) {
259                                 PConfig::delete(local_user(), 'twitter', 'lastid');
260                         }
261
262                         info(L10n::t('Twitter settings updated.') . EOL);
263                 }
264         }
265 }
266
267 function twitter_settings(App $a, &$s)
268 {
269         if (!local_user()) {
270                 return;
271         }
272         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
273         /*       * *
274          * 1) Check that we have global consumer key & secret
275          * 2) If no OAuthtoken & stuff is present, generate button to get some
276          * 3) Checkbox for "Send public notices (280 chars only)
277          */
278         $ckey    = Config::get('twitter', 'consumerkey');
279         $csecret = Config::get('twitter', 'consumersecret');
280         $otoken  = PConfig::get(local_user(), 'twitter', 'oauthtoken');
281         $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret');
282
283         $enabled            = intval(PConfig::get(local_user(), 'twitter', 'post'));
284         $defenabled         = intval(PConfig::get(local_user(), 'twitter', 'post_by_default'));
285         $mirrorenabled      = intval(PConfig::get(local_user(), 'twitter', 'mirror_posts'));
286         $importenabled      = intval(PConfig::get(local_user(), 'twitter', 'import'));
287         $create_userenabled = intval(PConfig::get(local_user(), 'twitter', 'create_user'));
288
289         $css = (($enabled) ? '' : '-disabled');
290
291         $s .= '<span id="settings_twitter_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
292         $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
293         $s .= '</span>';
294         $s .= '<div id="settings_twitter_expanded" class="settings-block" style="display: none;">';
295         $s .= '<span class="fakelink" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
296         $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
297         $s .= '</span>';
298
299         if ((!$ckey) && (!$csecret)) {
300                 /* no global consumer keys
301                  * display warning and skip personal config
302                  */
303                 $s .= '<p>' . L10n::t('No consumer key pair for Twitter found. Please contact your site administrator.') . '</p>';
304         } else {
305                 // ok we have a consumer key pair now look into the OAuth stuff
306                 if ((!$otoken) && (!$osecret)) {
307                         /* the user has not yet connected the account to twitter...
308                          * get a temporary OAuth key/secret pair and display a button with
309                          * which the user can request a PIN to connect the account to a
310                          * account at Twitter.
311                          */
312                         $connection = new TwitterOAuth($ckey, $csecret);
313                         $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
314
315                         $s .= '<p>' . L10n::t('At this Friendica instance the Twitter addon was enabled but you have not yet connected your account to your Twitter account. To do so click the button below to get a PIN from Twitter which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to Twitter.') . '</p>';
316                         $s .= '<a href="' . $connection->url('oauth/authorize', ['oauth_token' => $result['oauth_token']]) . '" target="_twitter"><img src="addon/twitter/lighter.png" alt="' . L10n::t('Log in with Twitter') . '"></a>';
317                         $s .= '<div id="twitter-pin-wrapper">';
318                         $s .= '<label id="twitter-pin-label" for="twitter-pin">' . L10n::t('Copy the PIN from Twitter here') . '</label>';
319                         $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
320                         $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result['oauth_token'] . '" />';
321                         $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result['oauth_token_secret'] . '" />';
322                         $s .= '</div><div class="clear"></div>';
323                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
324                 } else {
325                         /*                       * *
326                          *  we have an OAuth key / secret pair for the user
327                          *  so let's give a chance to disable the postings to Twitter
328                          */
329                         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
330                         $details = $connection->get('account/verify_credentials');
331
332                         $field_checkbox = get_markup_template('field_checkbox.tpl');
333
334                         $s .= '<div id="twitter-info" >
335                                 <p>' . L10n::t('Currently connected to: ') . '<a href="https://twitter.com/' . $details->screen_name . '" target="_twitter">' . $details->screen_name . '</a>
336                                         <button type="submit" name="twitter-disconnect" value="1">' . L10n::t('Disconnect') . '</button>
337                                 </p>
338                                 <p id="twitter-info-block">
339                                         <a href="https://twitter.com/' . $details->screen_name . '" target="_twitter"><img id="twitter-avatar" src="' . $details->profile_image_url . '" /></a>
340                                         <em>' . $details->description . '</em>
341                                 </p>
342                         </div>';
343                         $s .= '<div class="clear"></div>';
344
345                         $s .= replace_macros($field_checkbox, [
346                                 '$field' => ['twitter-enable', L10n::t('Allow posting to Twitter'), $enabled, L10n::t('If enabled all your <strong>public</strong> postings can be posted to the associated Twitter account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.')]
347                         ]);
348                         if ($a->user['hidewall']) {
349                                 $s .= '<p>' . L10n::t('<strong>Note</strong>: Due to your privacy settings (<em>Hide your profile details from unknown viewers?</em>) the link potentially included in public postings relayed to Twitter will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') . '</p>';
350                         }
351                         $s .= replace_macros($field_checkbox, [
352                                 '$field' => ['twitter-default', L10n::t('Send public postings to Twitter by default'), $defenabled, '']
353                         ]);
354                         $s .= replace_macros($field_checkbox, [
355                                 '$field' => ['twitter-mirror', L10n::t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '']
356                         ]);
357                         $s .= replace_macros($field_checkbox, [
358                                 '$field' => ['twitter-import', L10n::t('Import the remote timeline'), $importenabled, '']
359                         ]);
360                         $s .= replace_macros($field_checkbox, [
361                                 '$field' => ['twitter-create_user', L10n::t('Automatically create contacts'), $create_userenabled, '']
362                         ]);
363
364                         $s .= '<div class="clear"></div>';
365                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
366                 }
367         }
368         $s .= '</div><div class="clear"></div>';
369 }
370
371 function twitter_post_local(App $a, &$b)
372 {
373         if ($b['edit']) {
374                 return;
375         }
376
377         if (!local_user() || (local_user() != $b['uid'])) {
378                 return;
379         }
380
381         $twitter_post = intval(PConfig::get(local_user(), 'twitter', 'post'));
382         $twitter_enable = (($twitter_post && x($_REQUEST, 'twitter_enable')) ? intval($_REQUEST['twitter_enable']) : 0);
383
384         // if API is used, default to the chosen settings
385         if ($b['api_source'] && intval(PConfig::get(local_user(), 'twitter', 'post_by_default'))) {
386                 $twitter_enable = 1;
387         }
388
389         if (!$twitter_enable) {
390                 return;
391         }
392
393         if (strlen($b['postopts'])) {
394                 $b['postopts'] .= ',';
395         }
396
397         $b['postopts'] .= 'twitter';
398 }
399
400 function twitter_action(App $a, $uid, $pid, $action)
401 {
402         $ckey = Config::get('twitter', 'consumerkey');
403         $csecret = Config::get('twitter', 'consumersecret');
404         $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
405         $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
406
407         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
408
409         $post = ['id' => $pid];
410
411         logger("twitter_action '" . $action . "' ID: " . $pid . " data: " . print_r($post, true), LOGGER_DATA);
412
413         switch ($action) {
414                 case "delete":
415                         // To-Do: $result = $connection->post('statuses/destroy', $post);
416                         break;
417                 case "like":
418                         $result = $connection->post('favorites/create', $post);
419                         break;
420                 case "unlike":
421                         $result = $connection->post('favorites/destroy', $post);
422                         break;
423         }
424         logger("twitter_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG);
425 }
426
427 function twitter_post_hook(App $a, &$b)
428 {
429         // Post to Twitter
430         if (!PConfig::get($b["uid"], 'twitter', 'import')
431                 && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
432                 return;
433         }
434
435         if ($b['parent'] != $b['id']) {
436                 logger("twitter_post_hook: parameter " . print_r($b, true), LOGGER_DATA);
437
438                 // Looking if its a reply to a twitter post
439                 if ((substr($b["parent-uri"], 0, 9) != "twitter::")
440                         && (substr($b["extid"], 0, 9) != "twitter::")
441                         && (substr($b["thr-parent"], 0, 9) != "twitter::"))
442                 {
443                         logger("twitter_post_hook: no twitter post " . $b["parent"]);
444                         return;
445                 }
446
447                 $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
448                         dbesc($b["thr-parent"]),
449                         intval($b["uid"]));
450
451                 if (!count($r)) {
452                         logger("twitter_post_hook: no parent found " . $b["thr-parent"]);
453                         return;
454                 } else {
455                         $iscomment = true;
456                         $orig_post = $r[0];
457                 }
458
459
460                 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
461                 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
462                 $nicknameplain = "@" . $nicknameplain;
463
464                 logger("twitter_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], LOGGER_DEBUG);
465                 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
466                         $b["body"] = $nickname . " " . $b["body"];
467                 }
468
469                 logger("twitter_post_hook: parent found " . print_r($orig_post, true), LOGGER_DATA);
470         } else {
471                 $iscomment = false;
472
473                 if ($b['private'] || !strstr($b['postopts'], 'twitter')) {
474                         return;
475                 }
476
477                 // Dont't post if the post doesn't belong to us.
478                 // This is a check for forum postings
479                 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
480                 if ($b['contact-id'] != $self['id']) {
481                         return;
482                 }
483         }
484
485         if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
486                 twitter_action($a, $b["uid"], substr($orig_post["uri"], 9), "delete");
487         }
488
489         if ($b['verb'] == ACTIVITY_LIKE) {
490                 logger("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), LOGGER_DEBUG);
491                 if ($b['deleted']) {
492                         twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike");
493                 } else {
494                         twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "like");
495                 }
496
497                 return;
498         }
499
500         if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
501                 return;
502         }
503
504         // if post comes from twitter don't send it back
505         if ($b['extid'] == NETWORK_TWITTER) {
506                 return;
507         }
508
509         if ($b['app'] == "Twitter") {
510                 return;
511         }
512
513         logger('twitter post invoked');
514
515         PConfig::load($b['uid'], 'twitter');
516
517         $ckey    = Config::get('twitter', 'consumerkey');
518         $csecret = Config::get('twitter', 'consumersecret');
519         $otoken  = PConfig::get($b['uid'], 'twitter', 'oauthtoken');
520         $osecret = PConfig::get($b['uid'], 'twitter', 'oauthsecret');
521
522         if ($ckey && $csecret && $otoken && $osecret) {
523                 logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
524
525                 // If it's a repeated message from twitter then do a native retweet and exit
526                 if (twitter_is_retweet($a, $b['uid'], $b['body'])) {
527                         return;
528                 }
529
530                 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
531
532                 // Set the timeout for upload to 30 seconds
533                 $connection->setTimeouts(10, 30);
534
535                 $max_char = 280;
536                 $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 8);
537                 $msg = $msgarr["text"];
538
539                 if (($msg == "") && isset($msgarr["title"])) {
540                         $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
541                 }
542
543                 $image = "";
544
545                 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
546                         $msg .= "\n" . $msgarr["url"];
547                         $url_added = true;
548                 } else {
549                         $url_added = false;
550                 }
551
552                 if (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
553                         $image = $msgarr["image"];
554                 }
555
556                 if (empty($msg)) {
557                         return;
558                 }
559
560                 // and now tweet it :-)
561                 $post = [];
562
563                 if (!empty($image)) {
564                         try {
565                                 $img_str = Network::fetchUrl($image);
566
567                                 $tempfile = tempnam(get_temppath(), 'cache');
568                                 file_put_contents($tempfile, $img_str);
569
570                                 $media = $connection->upload('media/upload', ['media' => $tempfile]);
571
572                                 unlink($tempfile);
573
574                                 $post['media_ids'] = $media->media_id_string;
575                         } catch (Exception $e) {
576                                 logger('Exception when trying to send to Twitter: ' . $e->getMessage());
577
578                                 // Workaround: Remove the picture link so that the post can be reposted without it
579                                 // When there is another url already added, a second url would be superfluous.
580                                 if (!$url_added) {
581                                         $msg .= "\n" . $image;
582                                 }
583
584                                 $image = "";
585                         }
586                 }
587
588                 $post['status'] = $msg;
589
590                 if ($iscomment) {
591                         $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
592                 }
593
594                 $url = 'statuses/update';
595                 $result = $connection->post($url, $post);
596                 logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG);
597
598                 if ($result->source) {
599                         Config::set("twitter", "application_name", strip_tags($result->source));
600                 }
601
602                 if ($result->errors) {
603                         logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
604
605                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
606                         if (count($r)) {
607                                 $a->contact = $r[0]["id"];
608                         }
609
610                         $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $post]);
611
612                         Queue::add($a->contact, NETWORK_TWITTER, $s);
613                         notice(L10n::t('Twitter post failed. Queued for retry.') . EOL);
614                 } elseif ($iscomment) {
615                         logger('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']);
616                         Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]);
617                 }
618         }
619 }
620
621 function twitter_addon_admin_post(App $a)
622 {
623         $consumerkey    = x($_POST, 'consumerkey')    ? notags(trim($_POST['consumerkey']))    : '';
624         $consumersecret = x($_POST, 'consumersecret') ? notags(trim($_POST['consumersecret'])) : '';
625         Config::set('twitter', 'consumerkey', $consumerkey);
626         Config::set('twitter', 'consumersecret', $consumersecret);
627         info(L10n::t('Settings updated.') . EOL);
628 }
629
630 function twitter_addon_admin(App $a, &$o)
631 {
632         $t = get_markup_template("admin.tpl", "addon/twitter/");
633
634         $o = replace_macros($t, [
635                 '$submit' => L10n::t('Save Settings'),
636                 // name, label, value, help, [extra values]
637                 '$consumerkey' => ['consumerkey', L10n::t('Consumer key'), Config::get('twitter', 'consumerkey'), ''],
638                 '$consumersecret' => ['consumersecret', L10n::t('Consumer secret'), Config::get('twitter', 'consumersecret'), ''],
639         ]);
640 }
641
642 function twitter_cron(App $a, $b)
643 {
644         $last = Config::get('twitter', 'last_poll');
645
646         $poll_interval = intval(Config::get('twitter', 'poll_interval'));
647         if (!$poll_interval) {
648                 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
649         }
650
651         if ($last) {
652                 $next = $last + ($poll_interval * 60);
653                 if ($next > time()) {
654                         logger('twitter: poll intervall not reached');
655                         return;
656                 }
657         }
658         logger('twitter: cron_start');
659
660         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1'");
661         if (count($r)) {
662                 foreach ($r as $rr) {
663                         logger('twitter: fetching for user ' . $rr['uid']);
664                         Worker::add(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 1, (int) $rr['uid']);
665                 }
666         }
667
668         $abandon_days = intval(Config::get('system', 'account_abandon_days'));
669         if ($abandon_days < 1) {
670                 $abandon_days = 0;
671         }
672
673         $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
674
675         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1'");
676         if (count($r)) {
677                 foreach ($r as $rr) {
678                         if ($abandon_days != 0) {
679                                 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
680                                 if (!count($user)) {
681                                         logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
682                                         continue;
683                                 }
684                         }
685
686                         logger('twitter: importing timeline from user ' . $rr['uid']);
687                         Worker::add(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 2, (int) $rr['uid']);
688                         /*
689                           // To-Do
690                           // check for new contacts once a day
691                           $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
692                           if($last_contact_check)
693                           $next_contact_check = $last_contact_check + 86400;
694                           else
695                           $next_contact_check = 0;
696
697                           if($next_contact_check <= time()) {
698                           pumpio_getallusers($a, $rr["uid"]);
699                           PConfig::set($rr['uid'],'pumpio','contact_check',time());
700                           }
701                          */
702                 }
703         }
704
705         logger('twitter: cron_end');
706
707         Config::set('twitter', 'last_poll', time());
708 }
709
710 function twitter_expire(App $a, $b)
711 {
712         $days = Config::get('twitter', 'expire');
713
714         if ($days == 0) {
715                 return;
716         }
717
718         if (method_exists('dba', 'delete')) {
719                 $r = dba::select('item', ['id'], ['deleted' => true, 'network' => NETWORK_TWITTER]);
720                 while ($row = dba::fetch($r)) {
721                         dba::delete('item', ['id' => $row['id']]);
722                 }
723                 dba::close($r);
724         } else {
725                 $r = q("DELETE FROM `item` WHERE `deleted` AND `network` = '%s'", dbesc(NETWORK_TWITTER));
726         }
727
728         require_once "include/items.php";
729
730         logger('twitter_expire: expire_start');
731
732         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
733         if (count($r)) {
734                 foreach ($r as $rr) {
735                         logger('twitter_expire: user ' . $rr['uid']);
736                         Item::expire($rr['uid'], $days, NETWORK_TWITTER, true);
737                 }
738         }
739
740         logger('twitter_expire: expire_end');
741 }
742
743 function twitter_prepare_body(App $a, &$b)
744 {
745         if ($b["item"]["network"] != NETWORK_TWITTER) {
746                 return;
747         }
748
749         if ($b["preview"]) {
750                 $max_char = 280;
751                 $item = $b["item"];
752                 $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
753
754                 $r = q("SELECT `author-link` FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
755                         dbesc($item["thr-parent"]),
756                         intval(local_user()));
757
758                 if (count($r)) {
759                         $orig_post = $r[0];
760
761                         $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
762                         $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
763                         $nicknameplain = "@" . $nicknameplain;
764
765                         if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
766                                 $item["body"] = $nickname . " " . $item["body"];
767                         }
768                 }
769
770                 $msgarr = ItemContent::getPlaintextPost($item, $max_char, true, 8);
771                 $msg = $msgarr["text"];
772
773                 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
774                         $msg .= " " . $msgarr["url"];
775                 }
776
777                 if (isset($msgarr["image"])) {
778                         $msg .= " " . $msgarr["image"];
779                 }
780
781                 $b['html'] = nl2br(htmlspecialchars($msg));
782         }
783 }
784
785 /**
786  * @brief Build the item array for the mirrored post
787  *
788  * @param App $a Application class
789  * @param integer $uid User id
790  * @param object $post Twitter object with the post
791  *
792  * @return array item data to be posted
793  */
794 function twitter_do_mirrorpost(App $a, $uid, $post)
795 {
796         $datarray["type"] = "wall";
797         $datarray["api_source"] = true;
798         $datarray["profile_uid"] = $uid;
799         $datarray["extid"] = NETWORK_TWITTER;
800         $datarray['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_TWITTER . ":" . $post->id);
801         $datarray['object'] = json_encode($post);
802         $datarray["title"] = "";
803
804         if (is_object($post->retweeted_status)) {
805                 // We don't support nested shares, so we mustn't show quotes as shares on retweets
806                 $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true);
807
808                 $datarray['body'] = "\n" . share_header(
809                         $item['author-name'],
810                         $item['author-link'],
811                         $item['author-avatar'],
812                         "",
813                         $item['created'],
814                         $item['plink']
815                 );
816
817                 $datarray['body'] .= $item['body'] . '[/share]';
818         } else {
819                 $item = twitter_createpost($a, $uid, $post, ['id' => 0], false, false, false);
820
821                 $datarray['body'] = $item['body'];
822         }
823
824         $datarray["source"] = $item['app'];
825         $datarray["verb"] = $item['verb'];
826
827         if (isset($item["location"])) {
828                 $datarray["location"] = $item["location"];
829         }
830
831         if (isset($item["coord"])) {
832                 $datarray["coord"] = $item["coord"];
833         }
834
835         return $datarray;
836 }
837
838 function twitter_fetchtimeline(App $a, $uid)
839 {
840         $ckey    = Config::get('twitter', 'consumerkey');
841         $csecret = Config::get('twitter', 'consumersecret');
842         $otoken  = PConfig::get($uid, 'twitter', 'oauthtoken');
843         $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
844         $lastid  = PConfig::get($uid, 'twitter', 'lastid');
845
846         $application_name = Config::get('twitter', 'application_name');
847
848         if ($application_name == "") {
849                 $application_name = $a->get_hostname();
850         }
851
852         $has_picture = false;
853
854         require_once 'mod/item.php';
855         require_once 'include/items.php';
856         require_once 'mod/share.php';
857
858         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
859
860         $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
861
862         $first_time = ($lastid == "");
863
864         if ($lastid != "") {
865                 $parameters["since_id"] = $lastid;
866         }
867
868         $items = $connection->get('statuses/user_timeline', $parameters);
869
870         if (!is_array($items)) {
871                 return;
872         }
873
874         $posts = array_reverse($items);
875
876         if (count($posts)) {
877                 foreach ($posts as $post) {
878                         if ($post->id_str > $lastid) {
879                                 $lastid = $post->id_str;
880                                 PConfig::set($uid, 'twitter', 'lastid', $lastid);
881                         }
882
883                         if ($first_time) {
884                                 continue;
885                         }
886
887                         if (!stristr($post->source, $application_name)) {
888                                 $_SESSION["authenticated"] = true;
889                                 $_SESSION["uid"] = $uid;
890
891                                 $_REQUEST = twitter_do_mirrorpost($a, $uid, $post);
892
893                                 logger('twitter: posting for user ' . $uid);
894
895                                 item_post($a);
896                         }
897                 }
898         }
899         PConfig::set($uid, 'twitter', 'lastid', $lastid);
900 }
901
902 function twitter_queue_hook(App $a, &$b)
903 {
904         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
905                 dbesc(NETWORK_TWITTER)
906         );
907         if (!count($qi)) {
908                 return;
909         }
910
911         foreach ($qi as $x) {
912                 if ($x['network'] !== NETWORK_TWITTER) {
913                         continue;
914                 }
915
916                 logger('twitter_queue: run');
917
918                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
919                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
920                         intval($x['cid'])
921                 );
922                 if (!count($r)) {
923                         continue;
924                 }
925
926                 $user = $r[0];
927
928                 $ckey    = Config::get('twitter', 'consumerkey');
929                 $csecret = Config::get('twitter', 'consumersecret');
930                 $otoken  = PConfig::get($user['uid'], 'twitter', 'oauthtoken');
931                 $osecret = PConfig::get($user['uid'], 'twitter', 'oauthsecret');
932
933                 $success = false;
934
935                 if ($ckey && $csecret && $otoken && $osecret) {
936                         logger('twitter_queue: able to post');
937
938                         $z = unserialize($x['content']);
939
940                         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
941                         $result = $connection->post($z['url'], $z['post']);
942
943                         logger('twitter_queue: post result: ' . print_r($result, true), LOGGER_DEBUG);
944
945                         if ($result->errors) {
946                                 logger('twitter_queue: Send to Twitter failed: "' . print_r($result->errors, true) . '"');
947                         } else {
948                                 $success = true;
949                                 Queue::removeItem($x['id']);
950                         }
951                 } else {
952                         logger("twitter_queue: Error getting tokens for user " . $user['uid']);
953                 }
954
955                 if (!$success) {
956                         logger('twitter_queue: delayed');
957                         Queue::updateTime($x['id']);
958                 }
959         }
960 }
961
962 function twitter_fix_avatar($avatar)
963 {
964         $new_avatar = str_replace("_normal.", ".", $avatar);
965
966         $info = Image::getInfoFromURL($new_avatar);
967         if (!$info) {
968                 $new_avatar = $avatar;
969         }
970
971         return $new_avatar;
972 }
973
974 function twitter_fetch_contact($uid, $contact, $create_user)
975 {
976         if ($contact->id_str == "") {
977                 return -1;
978         }
979
980         $avatar = twitter_fix_avatar($contact->profile_image_url_https);
981
982         GContact::update(["url" => "https://twitter.com/" . $contact->screen_name,
983                 "network" => NETWORK_TWITTER, "photo" => $avatar, "hide" => true,
984                 "name" => $contact->name, "nick" => $contact->screen_name,
985                 "location" => $contact->location, "about" => $contact->description,
986                 "addr" => $contact->screen_name . "@twitter.com", "generation" => 2]);
987
988         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
989                 intval($uid),
990                 dbesc("twitter::" . $contact->id_str));
991
992         if (!count($r) && !$create_user) {
993                 return 0;
994         }
995
996         if (count($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
997                 logger("twitter_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", LOGGER_DEBUG);
998                 return -1;
999         }
1000
1001         if (!count($r)) {
1002                 // create contact record
1003                 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1004                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1005                                         `location`, `about`, `writable`, `blocked`, `readonly`, `pending`)
1006                                         VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1007                         intval($uid),
1008                         dbesc(DateTimeFormat::utcNow()),
1009                         dbesc("https://twitter.com/" . $contact->screen_name),
1010                         dbesc(normalise_link("https://twitter.com/" . $contact->screen_name)),
1011                         dbesc($contact->screen_name."@twitter.com"),
1012                         dbesc("twitter::" . $contact->id_str),
1013                         dbesc(''),
1014                         dbesc("twitter::" . $contact->id_str),
1015                         dbesc($contact->name),
1016                         dbesc($contact->screen_name),
1017                         dbesc($avatar),
1018                         dbesc(NETWORK_TWITTER),
1019                         intval(CONTACT_IS_FRIEND),
1020                         intval(1),
1021                         dbesc($contact->location),
1022                         dbesc($contact->description),
1023                         intval(1)
1024                 );
1025
1026                 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
1027                         dbesc("twitter::".$contact->id_str),
1028                         intval($uid)
1029                 );
1030
1031                 if (!count($r)) {
1032                         return false;
1033                 }
1034
1035                 $contact_id = $r[0]['id'];
1036
1037                 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1038
1039                 $photos = Photo::importProfilePhoto($avatar, $uid, $contact_id, true);
1040
1041                 if ($photos) {
1042                         q("UPDATE `contact` SET `photo` = '%s',
1043                                                 `thumb` = '%s',
1044                                                 `micro` = '%s',
1045                                                 `name-date` = '%s',
1046                                                 `uri-date` = '%s',
1047                                                         `avatar-date` = '%s'
1048                                         WHERE `id` = %d",
1049                                 dbesc($photos[0]),
1050                                 dbesc($photos[1]),
1051                                 dbesc($photos[2]),
1052                                 dbesc(DateTimeFormat::utcNow()),
1053                                 dbesc(DateTimeFormat::utcNow()),
1054                                 dbesc(DateTimeFormat::utcNow()),
1055                                 intval($contact_id)
1056                         );
1057                 }
1058         } else {
1059                 // update profile photos once every two weeks as we have no notification of when they change.
1060                 //$update_photo = (($r[0]['avatar-date'] < DateTimeFormat::convert('now -2 days', '', '', )) ? true : false);
1061                 $update_photo = ($r[0]['avatar-date'] < DateTimeFormat::utc('now -12 hours'));
1062
1063                 // check that we have all the photos, this has been known to fail on occasion
1064                 if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1065                         logger("twitter_fetch_contact: Updating contact " . $contact->screen_name, LOGGER_DEBUG);
1066
1067                         $photos = Photo::importProfilePhoto($avatar, $uid, $r[0]['id'], true);
1068
1069                         if ($photos) {
1070                                 q("UPDATE `contact` SET `photo` = '%s',
1071                                                         `thumb` = '%s',
1072                                                         `micro` = '%s',
1073                                                         `name-date` = '%s',
1074                                                         `uri-date` = '%s',
1075                                                         `avatar-date` = '%s',
1076                                                         `url` = '%s',
1077                                                         `nurl` = '%s',
1078                                                         `addr` = '%s',
1079                                                         `name` = '%s',
1080                                                         `nick` = '%s',
1081                                                         `location` = '%s',
1082                                                         `about` = '%s'
1083                                                 WHERE `id` = %d",
1084                                         dbesc($photos[0]),
1085                                         dbesc($photos[1]),
1086                                         dbesc($photos[2]),
1087                                         dbesc(DateTimeFormat::utcNow()),
1088                                         dbesc(DateTimeFormat::utcNow()),
1089                                         dbesc(DateTimeFormat::utcNow()),
1090                                         dbesc("https://twitter.com/".$contact->screen_name),
1091                                         dbesc(normalise_link("https://twitter.com/".$contact->screen_name)),
1092                                         dbesc($contact->screen_name."@twitter.com"),
1093                                         dbesc($contact->name),
1094                                         dbesc($contact->screen_name),
1095                                         dbesc($contact->location),
1096                                         dbesc($contact->description),
1097                                         intval($r[0]['id'])
1098                                 );
1099                         }
1100                 }
1101         }
1102
1103         return $r[0]["id"];
1104 }
1105
1106 function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1107 {
1108         $ckey = Config::get('twitter', 'consumerkey');
1109         $csecret = Config::get('twitter', 'consumersecret');
1110         $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1111         $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1112
1113         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1114                 intval($uid));
1115
1116         if (count($r)) {
1117                 $self = $r[0];
1118         } else {
1119                 return;
1120         }
1121
1122         $parameters = [];
1123
1124         if ($screen_name != "") {
1125                 $parameters["screen_name"] = $screen_name;
1126         }
1127
1128         if ($user_id != "") {
1129                 $parameters["user_id"] = $user_id;
1130         }
1131
1132         // Fetching user data
1133         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1134         $user = $connection->get('users/show', $parameters);
1135
1136         if (!is_object($user)) {
1137                 return;
1138         }
1139
1140         $contact_id = twitter_fetch_contact($uid, $user, true);
1141
1142         return $contact_id;
1143 }
1144
1145 function twitter_expand_entities(App $a, $body, $item, $picture)
1146 {
1147         $plain = $body;
1148
1149         $tags_arr = [];
1150
1151         foreach ($item->entities->hashtags AS $hashtag) {
1152                 $url = "#[url=" . $a->get_baseurl() . "/search?tag=" . rawurlencode($hashtag->text) . "]" . $hashtag->text . "[/url]";
1153                 $tags_arr["#" . $hashtag->text] = $url;
1154                 $body = str_replace("#" . $hashtag->text, $url, $body);
1155         }
1156
1157         foreach ($item->entities->user_mentions AS $mention) {
1158                 $url = "@[url=https://twitter.com/" . rawurlencode($mention->screen_name) . "]" . $mention->screen_name . "[/url]";
1159                 $tags_arr["@" . $mention->screen_name] = $url;
1160                 $body = str_replace("@" . $mention->screen_name, $url, $body);
1161         }
1162
1163         if (isset($item->entities->urls)) {
1164                 $type = "";
1165                 $footerurl = "";
1166                 $footerlink = "";
1167                 $footer = "";
1168
1169                 foreach ($item->entities->urls as $url) {
1170                         $plain = str_replace($url->url, '', $plain);
1171
1172                         if ($url->url && $url->expanded_url && $url->display_url) {
1173                                 $expanded_url = Network::finalUrl($url->expanded_url);
1174
1175                                 $oembed_data = OEmbed::fetchURL($expanded_url);
1176
1177                                 // Quickfix: Workaround for URL with "[" and "]" in it
1178                                 if (strpos($expanded_url, "[") || strpos($expanded_url, "]")) {
1179                                         $expanded_url = $url->url;
1180                                 }
1181
1182                                 if ($type == "") {
1183                                         $type = $oembed_data->type;
1184                                 }
1185
1186                                 if ($oembed_data->type == "video") {
1187                                         //$body = str_replace($url->url,
1188                                         //              "[video]".$expanded_url."[/video]", $body);
1189                                         //$dontincludemedia = true;
1190                                         $type = $oembed_data->type;
1191                                         $footerurl = $expanded_url;
1192                                         $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1193
1194                                         $body = str_replace($url->url, $footerlink, $body);
1195                                         //} elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia) {
1196                                 } elseif (($oembed_data->type == "photo") && isset($oembed_data->url)) {
1197                                         $body = str_replace($url->url, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1198                                         //$dontincludemedia = true;
1199                                 } elseif ($oembed_data->type != "link") {
1200                                         $body = str_replace($url->url, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1201                                 } else {
1202                                         $img_str = Network::fetchUrl($expanded_url, true, $redirects, 4);
1203
1204                                         $tempfile = tempnam(get_temppath(), "cache");
1205                                         file_put_contents($tempfile, $img_str);
1206                                         $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1207                                         unlink($tempfile);
1208
1209                                         if (substr($mime, 0, 6) == "image/") {
1210                                                 $type = "photo";
1211                                                 $body = str_replace($url->url, "[img]" . $expanded_url . "[/img]", $body);
1212                                                 //$dontincludemedia = true;
1213                                         } else {
1214                                                 $type = $oembed_data->type;
1215                                                 $footerurl = $expanded_url;
1216                                                 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1217
1218                                                 $body = str_replace($url->url, $footerlink, $body);
1219                                         }
1220                                 }
1221                         }
1222                 }
1223
1224                 if ($footerurl != "") {
1225                         $footer = add_page_info($footerurl, false, $picture);
1226                 }
1227
1228                 if (($footerlink != "") && (trim($footer) != "")) {
1229                         $removedlink = trim(str_replace($footerlink, "", $body));
1230
1231                         if (($removedlink == "") || strstr($body, $removedlink)) {
1232                                 $body = $removedlink;
1233                         }
1234
1235                         $body .= $footer;
1236                 }
1237
1238                 if (($footer == "") && ($picture != "")) {
1239                         $body .= "\n\n[img]" . $picture . "[/img]\n";
1240                 } elseif (($footer == "") && ($picture == "")) {
1241                         $body = add_page_info_to_body($body);
1242                 }
1243         }
1244
1245         // it seems as if the entities aren't always covering all mentions. So the rest will be checked here
1246         $tags = get_tags($body);
1247
1248         if (count($tags)) {
1249                 foreach ($tags as $tag) {
1250                         if (strstr(trim($tag), " ")) {
1251                                 continue;
1252                         }
1253
1254                         if (strpos($tag, '#') === 0) {
1255                                 if (strpos($tag, '[url=')) {
1256                                         continue;
1257                                 }
1258
1259                                 // don't link tags that are already embedded in links
1260                                 if (preg_match('/\[(.*?)' . preg_quote($tag, '/') . '(.*?)\]/', $body)) {
1261                                         continue;
1262                                 }
1263                                 if (preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag, '/') . '(.*?)\)/', $body)) {
1264                                         continue;
1265                                 }
1266
1267                                 $basetag = str_replace('_', ' ', substr($tag, 1));
1268                                 $url = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1269                                 $body = str_replace($tag, $url, $body);
1270                                 $tags_arr["#" . $basetag] = $url;
1271                         } elseif (strpos($tag, '@') === 0) {
1272                                 if (strpos($tag, '[url=')) {
1273                                         continue;
1274                                 }
1275
1276                                 $basetag = substr($tag, 1);
1277                                 $url = '@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1278                                 $body = str_replace($tag, $url, $body);
1279                                 $tags_arr["@" . $basetag] = $url;
1280                         }
1281                 }
1282         }
1283
1284         $tags = implode($tags_arr, ",");
1285
1286         return ["body" => $body, "tags" => $tags, "plain" => $plain];
1287 }
1288
1289 /**
1290  * @brief Fetch media entities and add media links to the body
1291  *
1292  * @param object $post Twitter object with the post
1293  * @param array $postarray Array of the item that is about to be posted
1294  *
1295  * @return $picture string Image URL or empty string
1296  */
1297 function twitter_media_entities($post, &$postarray)
1298 {
1299         // There are no media entities? So we quit.
1300         if (!is_array($post->extended_entities->media)) {
1301                 return "";
1302         }
1303
1304         // When the post links to an external page, we only take one picture.
1305         // We only do this when there is exactly one media.
1306         if ((count($post->entities->urls) > 0) && (count($post->extended_entities->media) == 1)) {
1307                 $picture = "";
1308                 foreach ($post->extended_entities->media AS $medium) {
1309                         if (isset($medium->media_url_https)) {
1310                                 $picture = $medium->media_url_https;
1311                                 $postarray['body'] = str_replace($medium->url, "", $postarray['body']);
1312                         }
1313                 }
1314                 return $picture;
1315         }
1316
1317         // This is a pure media post, first search for all media urls
1318         $media = [];
1319         foreach ($post->extended_entities->media AS $medium) {
1320                 switch ($medium->type) {
1321                         case 'photo':
1322                                 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . "[/img]";
1323                                 $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
1324                                 break;
1325                         case 'video':
1326                         case 'animated_gif':
1327                                 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . "[/img]";
1328                                 $postarray['object-type'] = ACTIVITY_OBJ_VIDEO;
1329                                 if (is_array($medium->video_info->variants)) {
1330                                         $bitrate = 0;
1331                                         // We take the video with the highest bitrate
1332                                         foreach ($medium->video_info->variants AS $variant) {
1333                                                 if (($variant->content_type == "video/mp4") && ($variant->bitrate >= $bitrate)) {
1334                                                         $media[$medium->url] = "\n[video]" . $variant->url . "[/video]";
1335                                                         $bitrate = $variant->bitrate;
1336                                                 }
1337                                         }
1338                                 }
1339                                 break;
1340                         // The following code will only be activated for test reasons
1341                         //default:
1342                         //      $postarray['body'] .= print_r($medium, true);
1343                 }
1344         }
1345
1346         // Now we replace the media urls.
1347         foreach ($media AS $key => $value) {
1348                 $postarray['body'] = str_replace($key, "\n" . $value . "\n", $postarray['body']);
1349         }
1350         return "";
1351 }
1352
1353 function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact, $noquote)
1354 {
1355         $postarray = [];
1356         $postarray['network'] = NETWORK_TWITTER;
1357         $postarray['gravity'] = 0;
1358         $postarray['uid'] = $uid;
1359         $postarray['wall'] = 0;
1360         $postarray['uri'] = "twitter::" . $post->id_str;
1361         $postarray['object'] = json_encode($post);
1362
1363         // Don't import our own comments
1364         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1365                 dbesc($postarray['uri']),
1366                 intval($uid)
1367         );
1368
1369         if (count($r)) {
1370                 logger("Item with extid " . $postarray['uri'] . " found.", LOGGER_DEBUG);
1371                 return [];
1372         }
1373
1374         $contactid = 0;
1375
1376         if ($post->in_reply_to_status_id_str != "") {
1377                 $parent = "twitter::" . $post->in_reply_to_status_id_str;
1378
1379                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1380                         dbesc($parent),
1381                         intval($uid)
1382                 );
1383                 if (count($r)) {
1384                         $postarray['thr-parent'] = $r[0]["uri"];
1385                         $postarray['parent-uri'] = $r[0]["parent-uri"];
1386                         $postarray['parent'] = $r[0]["parent"];
1387                         $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1388                 } else {
1389                         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1390                                 dbesc($parent),
1391                                 intval($uid)
1392                         );
1393                         if (count($r)) {
1394                                 $postarray['thr-parent'] = $r[0]['uri'];
1395                                 $postarray['parent-uri'] = $r[0]['parent-uri'];
1396                                 $postarray['parent'] = $r[0]['parent'];
1397                                 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1398                         } else {
1399                                 $postarray['thr-parent'] = $postarray['uri'];
1400                                 $postarray['parent-uri'] = $postarray['uri'];
1401                                 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1402                         }
1403                 }
1404
1405                 // Is it me?
1406                 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1407
1408                 if ($post->user->id_str == $own_id) {
1409                         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1410                                 intval($uid));
1411
1412                         if (count($r)) {
1413                                 $contactid = $r[0]["id"];
1414
1415                                 $postarray['owner-name']   = $r[0]["name"];
1416                                 $postarray['owner-link']   = $r[0]["url"];
1417                                 $postarray['owner-avatar'] = $r[0]["photo"];
1418                         } else {
1419                                 logger("No self contact for user " . $uid, LOGGER_DEBUG);
1420                                 return [];
1421                         }
1422                 }
1423                 // Don't create accounts of people who just comment something
1424                 $create_user = false;
1425         } else {
1426                 $postarray['parent-uri'] = $postarray['uri'];
1427                 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1428         }
1429
1430         if ($contactid == 0) {
1431                 $contactid = twitter_fetch_contact($uid, $post->user, $create_user);
1432
1433                 $postarray['owner-name'] = $post->user->name;
1434                 $postarray['owner-link'] = "https://twitter.com/" . $post->user->screen_name;
1435                 $postarray['owner-avatar'] = twitter_fix_avatar($post->user->profile_image_url_https);
1436         }
1437
1438         if (($contactid == 0) && !$only_existing_contact) {
1439                 $contactid = $self['id'];
1440         } elseif ($contactid <= 0) {
1441                 logger("Contact ID is zero or less than zero.", LOGGER_DEBUG);
1442                 return [];
1443         }
1444
1445         $postarray['contact-id'] = $contactid;
1446
1447         $postarray['verb'] = ACTIVITY_POST;
1448         $postarray['author-name'] = $postarray['owner-name'];
1449         $postarray['author-link'] = $postarray['owner-link'];
1450         $postarray['author-avatar'] = $postarray['owner-avatar'];
1451         $postarray['plink'] = "https://twitter.com/" . $post->user->screen_name . "/status/" . $post->id_str;
1452         $postarray['app'] = strip_tags($post->source);
1453
1454         if ($post->user->protected) {
1455                 $postarray['private'] = 1;
1456                 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1457         }
1458
1459         if (is_string($post->full_text)) {
1460                 $postarray['body'] = $post->full_text;
1461         } else {
1462                 $postarray['body'] = $post->text;
1463         }
1464
1465         // When the post contains links then use the correct object type
1466         if (count($post->entities->urls) > 0) {
1467                 $postarray['object-type'] = ACTIVITY_OBJ_BOOKMARK;
1468         }
1469
1470         // Search for media links
1471         $picture = twitter_media_entities($post, $postarray);
1472
1473         $converted = twitter_expand_entities($a, $postarray['body'], $post, $picture);
1474         $postarray['body'] = $converted["body"];
1475         $postarray['tag'] = $converted["tags"];
1476         $postarray['created'] = DateTimeFormat::utc($post->created_at);
1477         $postarray['edited'] = DateTimeFormat::utc($post->created_at);
1478
1479         $statustext = $converted["plain"];
1480
1481         if (is_string($post->place->name)) {
1482                 $postarray["location"] = $post->place->name;
1483         }
1484         if (is_string($post->place->full_name)) {
1485                 $postarray["location"] = $post->place->full_name;
1486         }
1487         if (is_array($post->geo->coordinates)) {
1488                 $postarray["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
1489         }
1490         if (is_array($post->coordinates->coordinates)) {
1491                 $postarray["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
1492         }
1493         if (is_object($post->retweeted_status)) {
1494                 $retweet = twitter_createpost($a, $uid, $post->retweeted_status, $self, false, false, $noquote);
1495
1496                 $retweet['object'] = $postarray['object'];
1497                 $retweet['private'] = $postarray['private'];
1498                 $retweet['allow_cid'] = $postarray['allow_cid'];
1499                 $retweet['contact-id'] = $postarray['contact-id'];
1500                 $retweet['owner-name'] = $postarray['owner-name'];
1501                 $retweet['owner-link'] = $postarray['owner-link'];
1502                 $retweet['owner-avatar'] = $postarray['owner-avatar'];
1503
1504                 $postarray = $retweet;
1505         }
1506
1507         if (is_object($post->quoted_status) && !$noquote) {
1508                 $quoted = twitter_createpost($a, $uid, $post->quoted_status, $self, false, false, true);
1509
1510                 $postarray['body'] = $statustext;
1511
1512                 $postarray['body'] .= "\n" . share_header(
1513                         $quoted['author-name'],
1514                         $quoted['author-link'],
1515                         $quoted['author-avatar'],
1516                         "",
1517                         $quoted['created'],
1518                         $quoted['plink']
1519                 );
1520
1521                 $postarray['body'] .= $quoted['body'] . '[/share]';
1522         }
1523
1524         return $postarray;
1525 }
1526
1527 function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray)
1528 {
1529         /// TODO: this whole function doesn't seem to work. Needs complete check
1530         $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1531                 intval($uid)
1532         );
1533
1534         if (!count($user)) {
1535                 return;
1536         }
1537
1538         // Is it me?
1539         if (link_compare($user[0]["url"], $postarray['author-link'])) {
1540                 return;
1541         }
1542
1543         $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1544                 intval($uid),
1545                 dbesc("twitter::".$own_id)
1546         );
1547
1548         if (!count($own_user)) {
1549                 return;
1550         }
1551
1552         // Is it me from twitter?
1553         if (link_compare($own_user[0]["url"], $postarray['author-link'])) {
1554                 return;
1555         }
1556
1557         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1558                 dbesc($postarray['parent-uri']),
1559                 intval($uid)
1560         );
1561
1562         if (count($myconv)) {
1563                 foreach ($myconv as $conv) {
1564                         // now if we find a match, it means we're in this conversation
1565                         if (!link_compare($conv['author-link'], $user[0]["url"]) && !link_compare($conv['author-link'], $own_user[0]["url"])) {
1566                                 continue;
1567                         }
1568
1569                         require_once 'include/enotify.php';
1570
1571                         $conv_parent = $conv['parent'];
1572
1573                         notification([
1574                                 'type' => NOTIFY_COMMENT,
1575                                 'notify_flags' => $user[0]['notify-flags'],
1576                                 'language' => $user[0]['language'],
1577                                 'to_name' => $user[0]['username'],
1578                                 'to_email' => $user[0]['email'],
1579                                 'uid' => $user[0]['uid'],
1580                                 'item' => $postarray,
1581                                 'link' => $a->get_baseurl() . '/display/' . urlencode(Item::getGuidById($top_item)),
1582                                 'source_name' => $postarray['author-name'],
1583                                 'source_link' => $postarray['author-link'],
1584                                 'source_photo' => $postarray['author-avatar'],
1585                                 'verb' => ACTIVITY_POST,
1586                                 'otype' => 'item',
1587                                 'parent' => $conv_parent,
1588                         ]);
1589
1590                         // only send one notification
1591                         break;
1592                 }
1593         }
1594 }
1595
1596 function twitter_fetchparentposts(App $a, $uid, $post, $connection, $self, $own_id)
1597 {
1598         logger("twitter_fetchparentposts: Fetching for user " . $uid . " and post " . $post->id_str, LOGGER_DEBUG);
1599
1600         $posts = [];
1601
1602         while ($post->in_reply_to_status_id_str != "") {
1603                 $parameters = ["trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str];
1604
1605                 $post = $connection->get('statuses/show', $parameters);
1606
1607                 if (!count($post)) {
1608                         logger("twitter_fetchparentposts: Can't fetch post " . $parameters->id, LOGGER_DEBUG);
1609                         break;
1610                 }
1611
1612                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1613                         dbesc("twitter::".$post->id_str),
1614                         intval($uid)
1615                 );
1616
1617                 if (count($r)) {
1618                         break;
1619                 }
1620
1621                 $posts[] = $post;
1622         }
1623
1624         logger("twitter_fetchparentposts: Fetching " . count($posts) . " parents", LOGGER_DEBUG);
1625
1626         $posts = array_reverse($posts);
1627
1628         if (count($posts)) {
1629                 foreach ($posts as $post) {
1630                         $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1631
1632                         if (trim($postarray['body']) == "") {
1633                                 continue;
1634                         }
1635
1636                         $item = Item::insert($postarray);
1637
1638                         if ($notify) {
1639                                 $item = $notify;
1640                         }
1641
1642                         $postarray["id"] = $item;
1643
1644                         logger('twitter_fetchparentpost: User ' . $self["nick"] . ' posted parent timeline item ' . $item);
1645
1646                         if ($item && !function_exists("check_item_notification")) {
1647                                 twitter_checknotification($a, $uid, $own_id, $item, $postarray);
1648                         }
1649                 }
1650         }
1651 }
1652
1653 function twitter_fetchhometimeline(App $a, $uid)
1654 {
1655         $ckey    = Config::get('twitter', 'consumerkey');
1656         $csecret = Config::get('twitter', 'consumersecret');
1657         $otoken  = PConfig::get($uid, 'twitter', 'oauthtoken');
1658         $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1659         $create_user = PConfig::get($uid, 'twitter', 'create_user');
1660         $mirror_posts = PConfig::get($uid, 'twitter', 'mirror_posts');
1661
1662         logger("twitter_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG);
1663
1664         $application_name = Config::get('twitter', 'application_name');
1665
1666         if ($application_name == "") {
1667                 $application_name = $a->get_hostname();
1668         }
1669
1670         require_once 'include/items.php';
1671
1672         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1673
1674         $own_contact = twitter_fetch_own_contact($a, $uid);
1675
1676         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1677                 intval($own_contact),
1678                 intval($uid));
1679
1680         if (count($r)) {
1681                 $own_id = $r[0]["nick"];
1682         } else {
1683                 logger("twitter_fetchhometimeline: Own twitter contact not found for user " . $uid, LOGGER_DEBUG);
1684                 return;
1685         }
1686
1687         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1688                 intval($uid));
1689
1690         if (count($r)) {
1691                 $self = $r[0];
1692         } else {
1693                 logger("twitter_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG);
1694                 return;
1695         }
1696
1697         $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1698                 intval($uid));
1699         if (!count($u)) {
1700                 logger("twitter_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG);
1701                 return;
1702         }
1703
1704         $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
1705         //$parameters["count"] = 200;
1706         // Fetching timeline
1707         $lastid = PConfig::get($uid, 'twitter', 'lasthometimelineid');
1708
1709         $first_time = ($lastid == "");
1710
1711         if ($lastid != "") {
1712                 $parameters["since_id"] = $lastid;
1713         }
1714
1715         $items = $connection->get('statuses/home_timeline', $parameters);
1716
1717         if (!is_array($items)) {
1718                 logger("twitter_fetchhometimeline: Error fetching home timeline: " . print_r($items, true), LOGGER_DEBUG);
1719                 return;
1720         }
1721
1722         $posts = array_reverse($items);
1723
1724         logger("twitter_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1725
1726         if (count($posts)) {
1727                 foreach ($posts as $post) {
1728                         if ($post->id_str > $lastid) {
1729                                 $lastid = $post->id_str;
1730                                 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1731                         }
1732
1733                         if ($first_time) {
1734                                 continue;
1735                         }
1736
1737                         if (stristr($post->source, $application_name) && $post->user->screen_name == $own_id) {
1738                                 logger("twitter_fetchhometimeline: Skip previously sended post", LOGGER_DEBUG);
1739                                 continue;
1740                         }
1741
1742                         if ($mirror_posts && $post->user->screen_name == $own_id && $post->in_reply_to_status_id_str == "") {
1743                                 logger("twitter_fetchhometimeline: Skip post that will be mirrored", LOGGER_DEBUG);
1744                                 continue;
1745                         }
1746
1747                         if ($post->in_reply_to_status_id_str != "") {
1748                                 twitter_fetchparentposts($a, $uid, $post, $connection, $self, $own_id);
1749                         }
1750
1751                         $postarray = twitter_createpost($a, $uid, $post, $self, $create_user, true, false);
1752
1753                         if (trim($postarray['body']) == "") {
1754                                 continue;
1755                         }
1756
1757                         $notify = false;
1758
1759                         if ($postarray['uri'] == $postarray['parent-uri']) {
1760                                 $contact = dba::selectFirst('contact', [], ['id' => $postarray['contact-id'], 'self' => false]);
1761                                 if (DBM::is_result($contact)) {
1762                                         $notify = Item::isRemoteSelf($contact, $postarray);
1763                                 }
1764                         }
1765
1766                         $item = Item::insert($postarray, false, $notify);
1767                         $postarray["id"] = $item;
1768
1769                         logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1770
1771                         if ($item && !function_exists("check_item_notification")) {
1772                                 twitter_checknotification($a, $uid, $own_id, $item, $postarray);
1773                         }
1774                 }
1775         }
1776         PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1777
1778         // Fetching mentions
1779         $lastid = PConfig::get($uid, 'twitter', 'lastmentionid');
1780
1781         $first_time = ($lastid == "");
1782
1783         if ($lastid != "") {
1784                 $parameters["since_id"] = $lastid;
1785         }
1786
1787         $items = $connection->get('statuses/mentions_timeline', $parameters);
1788
1789         if (!is_array($items)) {
1790                 logger("twitter_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG);
1791                 return;
1792         }
1793
1794         $posts = array_reverse($items);
1795
1796         logger("twitter_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1797
1798         if (count($posts)) {
1799                 foreach ($posts as $post) {
1800                         if ($post->id_str > $lastid) {
1801                                 $lastid = $post->id_str;
1802                         }
1803
1804                         if ($first_time) {
1805                                 continue;
1806                         }
1807
1808                         if ($post->in_reply_to_status_id_str != "") {
1809                                 twitter_fetchparentposts($a, $uid, $post, $connection, $self, $own_id);
1810                         }
1811
1812                         $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1813
1814                         if (trim($postarray['body']) == "") {
1815                                 continue;
1816                         }
1817
1818                         $item = Item::insert($postarray);
1819                         $postarray["id"] = $item;
1820
1821                         if ($item && function_exists("check_item_notification")) {
1822                                 check_item_notification($item, $uid, NOTIFY_TAGSELF);
1823                         }
1824
1825                         if (!isset($postarray["parent"]) || ($postarray["parent"] == 0)) {
1826                                 $postarray["parent"] = $item;
1827                         }
1828
1829                         logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1830
1831                         if ($item == 0) {
1832                                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1833                                         dbesc($postarray['uri']),
1834                                         intval($uid)
1835                                 );
1836                                 if (count($r)) {
1837                                         $item = $r[0]['id'];
1838                                         $parent_id = $r[0]['parent'];
1839                                 }
1840                         } else {
1841                                 $parent_id = $postarray['parent'];
1842                         }
1843
1844                         if (($item != 0) && !function_exists("check_item_notification")) {
1845                                 require_once 'include/enotify.php';
1846                                 notification([
1847                                         'type'         => NOTIFY_TAGSELF,
1848                                         'notify_flags' => $u[0]['notify-flags'],
1849                                         'language'     => $u[0]['language'],
1850                                         'to_name'      => $u[0]['username'],
1851                                         'to_email'     => $u[0]['email'],
1852                                         'uid'          => $u[0]['uid'],
1853                                         'item'         => $postarray,
1854                                         'link'         => $a->get_baseurl() . '/display/' . urlencode(Item::getGuidById($item)),
1855                                         'source_name'  => $postarray['author-name'],
1856                                         'source_link'  => $postarray['author-link'],
1857                                         'source_photo' => $postarray['author-avatar'],
1858                                         'verb'         => ACTIVITY_TAG,
1859                                         'otype'        => 'item',
1860                                         'parent'       => $parent_id
1861                                 ]);
1862                         }
1863                 }
1864         }
1865
1866         PConfig::set($uid, 'twitter', 'lastmentionid', $lastid);
1867 }
1868
1869 function twitter_fetch_own_contact(App $a, $uid)
1870 {
1871         $ckey    = Config::get('twitter', 'consumerkey');
1872         $csecret = Config::get('twitter', 'consumersecret');
1873         $otoken  = PConfig::get($uid, 'twitter', 'oauthtoken');
1874         $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1875
1876         $own_id = PConfig::get($uid, 'twitter', 'own_id');
1877
1878         $contact_id = 0;
1879
1880         if ($own_id == "") {
1881                 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1882
1883                 // Fetching user data
1884                 $user = $connection->get('account/verify_credentials');
1885
1886                 PConfig::set($uid, 'twitter', 'own_id', $user->id_str);
1887
1888                 $contact_id = twitter_fetch_contact($uid, $user, true);
1889         } else {
1890                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1891                         intval($uid),
1892                         dbesc("twitter::" . $own_id));
1893                 if (count($r)) {
1894                         $contact_id = $r[0]["id"];
1895                 } else {
1896                         PConfig::delete($uid, 'twitter', 'own_id');
1897                 }
1898         }
1899
1900         return $contact_id;
1901 }
1902
1903 function twitter_is_retweet(App $a, $uid, $body)
1904 {
1905         $body = trim($body);
1906
1907         // Skip if it isn't a pure repeated messages
1908         // Does it start with a share?
1909         if (strpos($body, "[share") > 0) {
1910                 return false;
1911         }
1912
1913         // Does it end with a share?
1914         if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1915                 return false;
1916         }
1917
1918         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1919         // Skip if there is no shared message in there
1920         if ($body == $attributes) {
1921                 return false;
1922         }
1923
1924         $link = "";
1925         preg_match("/link='(.*?)'/ism", $attributes, $matches);
1926         if ($matches[1] != "") {
1927                 $link = $matches[1];
1928         }
1929
1930         preg_match('/link="(.*?)"/ism', $attributes, $matches);
1931         if ($matches[1] != "") {
1932                 $link = $matches[1];
1933         }
1934
1935         $id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link);
1936         if ($id == $link) {
1937                 return false;
1938         }
1939
1940         logger('twitter_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG);
1941
1942         $ckey    = Config::get('twitter', 'consumerkey');
1943         $csecret = Config::get('twitter', 'consumersecret');
1944         $otoken  = PConfig::get($uid, 'twitter', 'oauthtoken');
1945         $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1946
1947         $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1948         $result = $connection->post('statuses/retweet/' . $id);
1949
1950         logger('twitter_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);
1951
1952         return !isset($result->errors);
1953 }