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