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