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