3 * Name: Twitter Connector
4 * Description: Bidirectional (posting, relaying and reading) connector for Twitter.
6 * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8 * Maintainer: Hypolite Petovan <https://friendica.mrpetovan.com/profile/hypolite>
10 * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel, Hypolite Petovan
11 * All rights reserved.
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.
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.
36 /* Twitter Addon for Friendica
38 * Author: Tobias Diekershoff
39 * tobias.diekershoff@gmx.net
41 * License:3-clause BSD license
44 * To use this addon you need a OAuth Consumer key pair (key & secret)
45 * you can get it from Twitter at https://twitter.com/apps
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.
51 * Add this key pair to your global .htconfig.php or use the admin panel.
53 * $a->config['twitter']['consumerkey'] = 'your consumer_key here';
54 * $a->config['twitter']['consumersecret'] = 'your consumer_secret here';
56 * To activate the addon itself add it to the $a->config['system']['addon']
57 * setting. After this, your user can configure their Twitter account settings
58 * from "Settings -> Addon Settings".
60 * Requirements: PHP5, curl
63 use Abraham\TwitterOAuth\TwitterOAuth;
64 use Abraham\TwitterOAuth\TwitterOAuthException;
66 use Friendica\Content\OEmbed;
67 use Friendica\Content\Text\Plaintext;
68 use Friendica\Core\Addon;
69 use Friendica\Core\Config;
70 use Friendica\Core\L10n;
71 use Friendica\Core\PConfig;
72 use Friendica\Core\Worker;
73 use Friendica\Model\GContact;
74 use Friendica\Model\Contact;
75 use Friendica\Model\Group;
76 use Friendica\Model\Item;
77 use Friendica\Model\ItemContent;
78 use Friendica\Model\Queue;
79 use Friendica\Model\User;
80 use Friendica\Object\Image;
81 use Friendica\Util\DateTimeFormat;
82 use Friendica\Util\Network;
83 use Friendica\Database\DBM;
85 require_once 'boot.php';
86 require_once 'include/dba.php';
87 require_once 'include/enotify.php';
88 require_once 'include/text.php';
90 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
92 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
94 function twitter_install()
96 // we need some hooks, for the configuration and for sending tweets
97 Addon::registerHook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings');
98 Addon::registerHook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
99 Addon::registerHook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
100 Addon::registerHook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
101 Addon::registerHook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
102 Addon::registerHook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
103 Addon::registerHook('queue_predeliver', 'addon/twitter/twitter.php', 'twitter_queue_hook');
104 Addon::registerHook('follow', 'addon/twitter/twitter.php', 'twitter_follow');
105 Addon::registerHook('expire', 'addon/twitter/twitter.php', 'twitter_expire');
106 Addon::registerHook('prepare_body', 'addon/twitter/twitter.php', 'twitter_prepare_body');
107 Addon::registerHook('check_item_notification', 'addon/twitter/twitter.php', 'twitter_check_item_notification');
108 logger("installed twitter");
111 function twitter_uninstall()
113 Addon::unregisterHook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings');
114 Addon::unregisterHook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
115 Addon::unregisterHook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
116 Addon::unregisterHook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
117 Addon::unregisterHook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
118 Addon::unregisterHook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
119 Addon::unregisterHook('queue_predeliver', 'addon/twitter/twitter.php', 'twitter_queue_hook');
120 Addon::unregisterHook('follow', 'addon/twitter/twitter.php', 'twitter_follow');
121 Addon::unregisterHook('expire', 'addon/twitter/twitter.php', 'twitter_expire');
122 Addon::unregisterHook('prepare_body', 'addon/twitter/twitter.php', 'twitter_prepare_body');
123 Addon::unregisterHook('check_item_notification', 'addon/twitter/twitter.php', 'twitter_check_item_notification');
125 // old setting - remove only
126 Addon::unregisterHook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
127 Addon::unregisterHook('addon_settings', 'addon/twitter/twitter.php', 'twitter_settings');
128 Addon::unregisterHook('addon_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
131 function twitter_check_item_notification(App $a, &$notification_data)
133 $own_id = PConfig::get($notification_data["uid"], 'twitter', 'own_id');
135 $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
136 intval($notification_data["uid"]),
137 dbesc("twitter::".$own_id)
141 $notification_data["profiles"][] = $own_user[0]["url"];
145 function twitter_follow(App $a, &$contact)
147 logger("twitter_follow: Check if contact is twitter contact. " . $contact["url"], LOGGER_DEBUG);
149 if (!strstr($contact["url"], "://twitter.com") && !strstr($contact["url"], "@twitter.com")) {
153 // contact seems to be a twitter contact, so continue
154 $nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $contact["url"]);
155 $nickname = str_replace("@twitter.com", "", $nickname);
157 $uid = $a->user["uid"];
159 $ckey = Config::get('twitter', 'consumerkey');
160 $csecret = Config::get('twitter', 'consumersecret');
161 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
162 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
164 // If the addon is not configured (general or for this user) quit here
165 if (empty($ckey) || empty($csecret) || empty($otoken) || empty($osecret)) {
170 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
171 $connection->post('friendships/create', ['screen_name' => $nickname]);
173 twitter_fetchuser($a, $uid, $nickname);
175 $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
176 FROM `contact` WHERE `uid` = %d AND `nick` = '%s'",
179 if (DBM::is_result($r)) {
180 $contact["contact"] = $r[0];
184 function twitter_jot_nets(App $a, &$b)
190 $tw_post = PConfig::get(local_user(), 'twitter', 'post');
191 if (intval($tw_post) == 1) {
192 $tw_defpost = PConfig::get(local_user(), 'twitter', 'post_by_default');
193 $selected = ((intval($tw_defpost) == 1) ? ' checked="checked" ' : '');
194 $b .= '<div class="profile-jot-net"><input type="checkbox" name="twitter_enable"' . $selected . ' value="1" /> '
195 . L10n::t('Post to Twitter') . '</div>';
199 function twitter_settings_post(App $a, $post)
204 // don't check twitter settings if twitter submit button is not clicked
205 if (empty($_POST['twitter-disconnect']) && empty($_POST['twitter-submit'])) {
209 if (!empty($_POST['twitter-disconnect'])) {
211 * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
212 * from the user configuration
214 PConfig::delete(local_user(), 'twitter', 'consumerkey');
215 PConfig::delete(local_user(), 'twitter', 'consumersecret');
216 PConfig::delete(local_user(), 'twitter', 'oauthtoken');
217 PConfig::delete(local_user(), 'twitter', 'oauthsecret');
218 PConfig::delete(local_user(), 'twitter', 'post');
219 PConfig::delete(local_user(), 'twitter', 'post_by_default');
220 PConfig::delete(local_user(), 'twitter', 'lastid');
221 PConfig::delete(local_user(), 'twitter', 'mirror_posts');
222 PConfig::delete(local_user(), 'twitter', 'import');
223 PConfig::delete(local_user(), 'twitter', 'create_user');
224 PConfig::delete(local_user(), 'twitter', 'own_id');
226 if (isset($_POST['twitter-pin'])) {
227 // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
228 logger('got a Twitter PIN');
229 $ckey = Config::get('twitter', 'consumerkey');
230 $csecret = Config::get('twitter', 'consumersecret');
231 // the token and secret for which the PIN was generated were hidden in the settings
232 // form as token and token2, we need a new connection to Twitter using these token
233 // and secret to request a Access Token with the PIN
235 if (empty($_POST['twitter-pin'])) {
236 throw new Exception(L10n::t('You submitted an empty PIN, please Sign In with Twitter again to get a new one.'));
239 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
240 $token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_POST['twitter-pin']]);
241 // ok, now that we have the Access Token, save them in the user config
242 PConfig::set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
243 PConfig::set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
244 PConfig::set(local_user(), 'twitter', 'post', 1);
245 } catch(Exception $e) {
246 info($e->getMessage());
247 } catch(TwitterOAuthException $e) {
248 info($e->getMessage());
250 // reload the Addon Settings page, if we don't do it see Bug #42
251 goaway('settings/connectors');
253 // if no PIN is supplied in the POST variables, the user has changed the setting
254 // to post a tweet for every new __public__ posting to the wall
255 PConfig::set(local_user(), 'twitter', 'post', intval($_POST['twitter-enable']));
256 PConfig::set(local_user(), 'twitter', 'post_by_default', intval($_POST['twitter-default']));
257 PConfig::set(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror']));
258 PConfig::set(local_user(), 'twitter', 'import', intval($_POST['twitter-import']));
259 PConfig::set(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user']));
261 if (!intval($_POST['twitter-mirror'])) {
262 PConfig::delete(local_user(), 'twitter', 'lastid');
265 info(L10n::t('Twitter settings updated.') . EOL);
270 function twitter_settings(App $a, &$s)
275 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
277 * 1) Check that we have global consumer key & secret
278 * 2) If no OAuthtoken & stuff is present, generate button to get some
279 * 3) Checkbox for "Send public notices (280 chars only)
281 $ckey = Config::get('twitter', 'consumerkey');
282 $csecret = Config::get('twitter', 'consumersecret');
283 $otoken = PConfig::get(local_user(), 'twitter', 'oauthtoken');
284 $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret');
286 $enabled = intval(PConfig::get(local_user(), 'twitter', 'post'));
287 $defenabled = intval(PConfig::get(local_user(), 'twitter', 'post_by_default'));
288 $mirrorenabled = intval(PConfig::get(local_user(), 'twitter', 'mirror_posts'));
289 $importenabled = intval(PConfig::get(local_user(), 'twitter', 'import'));
290 $create_userenabled = intval(PConfig::get(local_user(), 'twitter', 'create_user'));
292 $css = (($enabled) ? '' : '-disabled');
294 $s .= '<span id="settings_twitter_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
295 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
297 $s .= '<div id="settings_twitter_expanded" class="settings-block" style="display: none;">';
298 $s .= '<span class="fakelink" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
299 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
302 if ((!$ckey) && (!$csecret)) {
303 /* no global consumer keys
304 * display warning and skip personal config
306 $s .= '<p>' . L10n::t('No consumer key pair for Twitter found. Please contact your site administrator.') . '</p>';
308 // ok we have a consumer key pair now look into the OAuth stuff
309 if ((!$otoken) && (!$osecret)) {
310 /* the user has not yet connected the account to twitter...
311 * get a temporary OAuth key/secret pair and display a button with
312 * which the user can request a PIN to connect the account to a
313 * account at Twitter.
315 $connection = new TwitterOAuth($ckey, $csecret);
317 $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
318 $s .= '<p>' . L10n::t('At this Friendica instance the Twitter addon was enabled but you have not yet connected your account to your Twitter account. To do so click the button below to get a PIN from Twitter which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to Twitter.') . '</p>';
319 $s .= '<a href="' . $connection->url('oauth/authorize', ['oauth_token' => $result['oauth_token']]) . '" target="_twitter"><img src="addon/twitter/lighter.png" alt="' . L10n::t('Log in with Twitter') . '"></a>';
320 $s .= '<div id="twitter-pin-wrapper">';
321 $s .= '<label id="twitter-pin-label" for="twitter-pin">' . L10n::t('Copy the PIN from Twitter here') . '</label>';
322 $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
323 $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result['oauth_token'] . '" />';
324 $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result['oauth_token_secret'] . '" />';
325 $s .= '</div><div class="clear"></div>';
326 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
327 } catch (TwitterOAuthException $e) {
328 $s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
332 * we have an OAuth key / secret pair for the user
333 * so let's give a chance to disable the postings to Twitter
335 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
337 $details = $connection->get('account/verify_credentials');
339 $field_checkbox = get_markup_template('field_checkbox.tpl');
341 $s .= '<div id="twitter-info" >
342 <p>' . L10n::t('Currently connected to: ') . '<a href="https://twitter.com/' . $details->screen_name . '" target="_twitter">' . $details->screen_name . '</a>
343 <button type="submit" name="twitter-disconnect" value="1">' . L10n::t('Disconnect') . '</button>
345 <p id="twitter-info-block">
346 <a href="https://twitter.com/' . $details->screen_name . '" target="_twitter"><img id="twitter-avatar" src="' . $details->profile_image_url . '" /></a>
347 <em>' . $details->description . '</em>
350 $s .= '<div class="clear"></div>';
352 $s .= replace_macros($field_checkbox, [
353 '$field' => ['twitter-enable', L10n::t('Allow posting to Twitter'), $enabled, L10n::t('If enabled all your <strong>public</strong> postings can be posted to the associated Twitter account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.')]
355 if ($a->user['hidewall']) {
356 $s .= '<p>' . L10n::t('<strong>Note</strong>: Due to your privacy settings (<em>Hide your profile details from unknown viewers?</em>) the link potentially included in public postings relayed to Twitter will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') . '</p>';
358 $s .= replace_macros($field_checkbox, [
359 '$field' => ['twitter-default', L10n::t('Send public postings to Twitter by default'), $defenabled, '']
361 $s .= replace_macros($field_checkbox, [
362 '$field' => ['twitter-mirror', L10n::t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '']
364 $s .= replace_macros($field_checkbox, [
365 '$field' => ['twitter-import', L10n::t('Import the remote timeline'), $importenabled, '']
367 $s .= replace_macros($field_checkbox, [
368 '$field' => ['twitter-create_user', L10n::t('Automatically create contacts'), $create_userenabled, L10n::t('This will automatically create a contact in Friendica as soon as you receive a message from an existing contact via the Twitter network. If you do not enable this, you need to manually add those Twitter contacts in Friendica from whom you would like to see posts here. However if enabled, you cannot merely remove a twitter contact from the Friendica contact list, as it will recreate this contact when they post again.')]
370 $s .= '<div class="clear"></div>';
371 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
372 } catch (TwitterOAuthException $e) {
373 $s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
377 $s .= '</div><div class="clear"></div>';
380 function twitter_post_local(App $a, &$b)
386 if (!local_user() || (local_user() != $b['uid'])) {
390 $twitter_post = intval(PConfig::get(local_user(), 'twitter', 'post'));
391 $twitter_enable = (($twitter_post && x($_REQUEST, 'twitter_enable')) ? intval($_REQUEST['twitter_enable']) : 0);
393 // if API is used, default to the chosen settings
394 if ($b['api_source'] && intval(PConfig::get(local_user(), 'twitter', 'post_by_default'))) {
398 if (!$twitter_enable) {
402 if (strlen($b['postopts'])) {
403 $b['postopts'] .= ',';
406 $b['postopts'] .= 'twitter';
409 function twitter_action(App $a, $uid, $pid, $action)
411 $ckey = Config::get('twitter', 'consumerkey');
412 $csecret = Config::get('twitter', 'consumersecret');
413 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
414 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
416 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
418 $post = ['id' => $pid];
420 logger("twitter_action '" . $action . "' ID: " . $pid . " data: " . print_r($post, true), LOGGER_DATA);
424 // To-Do: $result = $connection->post('statuses/destroy', $post);
427 $result = $connection->post('favorites/create', $post);
430 $result = $connection->post('favorites/destroy', $post);
433 logger("twitter_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG);
436 function twitter_post_hook(App $a, &$b)
439 if (!PConfig::get($b["uid"], 'twitter', 'import')
440 && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
444 if ($b['parent'] != $b['id']) {
445 logger("twitter_post_hook: parameter " . print_r($b, true), LOGGER_DATA);
447 // Looking if its a reply to a twitter post
448 if ((substr($b["parent-uri"], 0, 9) != "twitter::")
449 && (substr($b["extid"], 0, 9) != "twitter::")
450 && (substr($b["thr-parent"], 0, 9) != "twitter::"))
452 logger("twitter_post_hook: no twitter post " . $b["parent"]);
456 $condition = ['uri' => $b["thr-parent"], 'uid' => $b["uid"]];
457 $orig_post = Item::selectFirst([], $condition);
458 if (!DBM::is_result($orig_post)) {
459 logger("twitter_post_hook: no parent found " . $b["thr-parent"]);
466 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
467 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
468 $nicknameplain = "@" . $nicknameplain;
470 logger("twitter_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], LOGGER_DEBUG);
471 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
472 $b["body"] = $nickname . " " . $b["body"];
475 logger("twitter_post_hook: parent found " . print_r($orig_post, true), LOGGER_DATA);
479 if ($b['private'] || !strstr($b['postopts'], 'twitter')) {
483 // Dont't post if the post doesn't belong to us.
484 // This is a check for forum postings
485 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
486 if ($b['contact-id'] != $self['id']) {
491 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
492 twitter_action($a, $b["uid"], substr($orig_post["uri"], 9), "delete");
495 if ($b['verb'] == ACTIVITY_LIKE) {
496 logger("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), LOGGER_DEBUG);
498 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike");
500 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "like");
506 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
510 // if post comes from twitter don't send it back
511 if ($b['extid'] == NETWORK_TWITTER) {
515 if ($b['app'] == "Twitter") {
519 logger('twitter post invoked');
521 PConfig::load($b['uid'], 'twitter');
523 $ckey = Config::get('twitter', 'consumerkey');
524 $csecret = Config::get('twitter', 'consumersecret');
525 $otoken = PConfig::get($b['uid'], 'twitter', 'oauthtoken');
526 $osecret = PConfig::get($b['uid'], 'twitter', 'oauthsecret');
528 if ($ckey && $csecret && $otoken && $osecret) {
529 logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
531 // If it's a repeated message from twitter then do a native retweet and exit
532 if (twitter_is_retweet($a, $b['uid'], $b['body'])) {
536 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
538 // Set the timeout for upload to 30 seconds
539 $connection->setTimeouts(10, 30);
542 $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 8);
543 $msg = $msgarr["text"];
545 if (($msg == "") && isset($msgarr["title"])) {
546 $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
551 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
552 $msg .= "\n" . $msgarr["url"];
558 if (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
559 $image = $msgarr["image"];
566 // and now tweet it :-)
569 if (!empty($image)) {
571 $img_str = Network::fetchUrl($image);
573 $tempfile = tempnam(get_temppath(), 'cache');
574 file_put_contents($tempfile, $img_str);
576 $media = $connection->upload('media/upload', ['media' => $tempfile]);
580 $post['media_ids'] = $media->media_id_string;
581 } catch (Exception $e) {
582 logger('Exception when trying to send to Twitter: ' . $e->getMessage());
584 // Workaround: Remove the picture link so that the post can be reposted without it
585 // When there is another url already added, a second url would be superfluous.
587 $msg .= "\n" . $image;
594 $post['status'] = $msg;
597 $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
600 $url = 'statuses/update';
601 $result = $connection->post($url, $post);
602 logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG);
604 if ($result->source) {
605 Config::set("twitter", "application_name", strip_tags($result->source));
608 if ($result->errors) {
609 logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
611 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
612 if (DBM::is_result($r)) {
613 $a->contact = $r[0]["id"];
616 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $post]);
618 Queue::add($a->contact, NETWORK_TWITTER, $s);
619 notice(L10n::t('Twitter post failed. Queued for retry.') . EOL);
620 } elseif ($iscomment) {
621 logger('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']);
622 Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]);
627 function twitter_addon_admin_post(App $a)
629 $consumerkey = x($_POST, 'consumerkey') ? notags(trim($_POST['consumerkey'])) : '';
630 $consumersecret = x($_POST, 'consumersecret') ? notags(trim($_POST['consumersecret'])) : '';
631 Config::set('twitter', 'consumerkey', $consumerkey);
632 Config::set('twitter', 'consumersecret', $consumersecret);
633 info(L10n::t('Settings updated.') . EOL);
636 function twitter_addon_admin(App $a, &$o)
638 $t = get_markup_template("admin.tpl", "addon/twitter/");
640 $o = replace_macros($t, [
641 '$submit' => L10n::t('Save Settings'),
642 // name, label, value, help, [extra values]
643 '$consumerkey' => ['consumerkey', L10n::t('Consumer key'), Config::get('twitter', 'consumerkey'), ''],
644 '$consumersecret' => ['consumersecret', L10n::t('Consumer secret'), Config::get('twitter', 'consumersecret'), ''],
648 function twitter_cron(App $a, $b)
650 $last = Config::get('twitter', 'last_poll');
652 $poll_interval = intval(Config::get('twitter', 'poll_interval'));
653 if (!$poll_interval) {
654 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
658 $next = $last + ($poll_interval * 60);
659 if ($next > time()) {
660 logger('twitter: poll intervall not reached');
664 logger('twitter: cron_start');
666 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1'");
667 if (DBM::is_result($r)) {
668 foreach ($r as $rr) {
669 logger('twitter: fetching for user ' . $rr['uid']);
670 Worker::add(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 1, (int) $rr['uid']);
674 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
675 if ($abandon_days < 1) {
679 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
681 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1'");
682 if (DBM::is_result($r)) {
683 foreach ($r as $rr) {
684 if ($abandon_days != 0) {
685 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
686 if (!DBM::is_result($user)) {
687 logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
692 logger('twitter: importing timeline from user ' . $rr['uid']);
693 Worker::add(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 2, (int) $rr['uid']);
696 // check for new contacts once a day
697 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
698 if($last_contact_check)
699 $next_contact_check = $last_contact_check + 86400;
701 $next_contact_check = 0;
703 if($next_contact_check <= time()) {
704 pumpio_getallusers($a, $rr["uid"]);
705 PConfig::set($rr['uid'],'pumpio','contact_check',time());
711 logger('twitter: cron_end');
713 Config::set('twitter', 'last_poll', time());
716 function twitter_expire(App $a, $b)
718 $days = Config::get('twitter', 'expire');
724 $r = dba::select('item', ['id'], ['deleted' => true, 'network' => NETWORK_TWITTER]);
725 while ($row = dba::fetch($r)) {
726 dba::delete('item', ['id' => $row['id']]);
730 require_once "include/items.php";
732 logger('twitter_expire: expire_start');
734 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
735 if (DBM::is_result($r)) {
736 foreach ($r as $rr) {
737 logger('twitter_expire: user ' . $rr['uid']);
738 Item::expire($rr['uid'], $days, NETWORK_TWITTER, true);
742 logger('twitter_expire: expire_end');
745 function twitter_prepare_body(App $a, &$b)
747 if ($b["item"]["network"] != NETWORK_TWITTER) {
754 $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
756 $condition = ['uri' => $item["thr-parent"], 'uid' => local_user()];
757 $orig_post = Item::selectFirst(['author-link'], $condition);
758 if (DBM::is_result($orig_post)) {
759 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
760 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
761 $nicknameplain = "@" . $nicknameplain;
763 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
764 $item["body"] = $nickname . " " . $item["body"];
768 $msgarr = ItemContent::getPlaintextPost($item, $max_char, true, 8);
769 $msg = $msgarr["text"];
771 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
772 $msg .= " " . $msgarr["url"];
775 if (isset($msgarr["image"])) {
776 $msg .= " " . $msgarr["image"];
779 $b['html'] = nl2br(htmlspecialchars($msg));
784 * @brief Build the item array for the mirrored post
786 * @param App $a Application class
787 * @param integer $uid User id
788 * @param object $post Twitter object with the post
790 * @return array item data to be posted
792 function twitter_do_mirrorpost(App $a, $uid, $post)
794 $datarray["type"] = "wall";
795 $datarray["api_source"] = true;
796 $datarray["profile_uid"] = $uid;
797 $datarray["extid"] = NETWORK_TWITTER;
798 $datarray['message_id'] = Item::newURI($uid, NETWORK_TWITTER . ":" . $post->id);
799 // $datarray['object'] = json_encode($post); // Activate for debugging
800 $datarray["title"] = "";
802 if (is_object($post->retweeted_status)) {
803 // We don't support nested shares, so we mustn't show quotes as shares on retweets
804 $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true);
806 $datarray['body'] = "\n" . share_header(
807 $item['author-name'],
808 $item['author-link'],
809 $item['author-avatar'],
815 $datarray['body'] .= $item['body'] . '[/share]';
817 $item = twitter_createpost($a, $uid, $post, ['id' => 0], false, false, false);
819 $datarray['body'] = $item['body'];
822 $datarray["source"] = $item['app'];
823 $datarray["verb"] = $item['verb'];
825 if (isset($item["location"])) {
826 $datarray["location"] = $item["location"];
829 if (isset($item["coord"])) {
830 $datarray["coord"] = $item["coord"];
836 function twitter_fetchtimeline(App $a, $uid)
838 $ckey = Config::get('twitter', 'consumerkey');
839 $csecret = Config::get('twitter', 'consumersecret');
840 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
841 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
842 $lastid = PConfig::get($uid, 'twitter', 'lastid');
844 $application_name = Config::get('twitter', 'application_name');
846 if ($application_name == "") {
847 $application_name = $a->get_hostname();
850 $has_picture = false;
852 require_once 'mod/item.php';
853 require_once 'include/items.php';
854 require_once 'mod/share.php';
856 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
858 $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
860 $first_time = ($lastid == "");
863 $parameters["since_id"] = $lastid;
867 $items = $connection->get('statuses/user_timeline', $parameters);
868 } catch (TwitterOAuthException $e) {
869 logger('twitter_fetchtimeline: Error fetching timeline for user ' . $uid . ': ' . $e->getMessage());
873 if (!is_array($items)) {
877 $posts = array_reverse($items);
880 foreach ($posts as $post) {
881 if ($post->id_str > $lastid) {
882 $lastid = $post->id_str;
883 PConfig::set($uid, 'twitter', 'lastid', $lastid);
890 if (!stristr($post->source, $application_name)) {
891 $_SESSION["authenticated"] = true;
892 $_SESSION["uid"] = $uid;
894 $_REQUEST = twitter_do_mirrorpost($a, $uid, $post);
896 logger('twitter: posting for user ' . $uid);
902 PConfig::set($uid, 'twitter', 'lastid', $lastid);
905 function twitter_queue_hook(App $a, &$b)
907 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
908 dbesc(NETWORK_TWITTER)
910 if (!DBM::is_result($qi)) {
914 foreach ($qi as $x) {
915 if ($x['network'] !== NETWORK_TWITTER) {
919 logger('twitter_queue: run');
921 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
922 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
925 if (!DBM::is_result($r)) {
931 $ckey = Config::get('twitter', 'consumerkey');
932 $csecret = Config::get('twitter', 'consumersecret');
933 $otoken = PConfig::get($user['uid'], 'twitter', 'oauthtoken');
934 $osecret = PConfig::get($user['uid'], 'twitter', 'oauthsecret');
938 if ($ckey && $csecret && $otoken && $osecret) {
939 logger('twitter_queue: able to post');
941 $z = unserialize($x['content']);
943 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
944 $result = $connection->post($z['url'], $z['post']);
946 logger('twitter_queue: post result: ' . print_r($result, true), LOGGER_DEBUG);
948 if ($result->errors) {
949 logger('twitter_queue: Send to Twitter failed: "' . print_r($result->errors, true) . '"');
952 Queue::removeItem($x['id']);
955 logger("twitter_queue: Error getting tokens for user " . $user['uid']);
959 logger('twitter_queue: delayed');
960 Queue::updateTime($x['id']);
965 function twitter_fix_avatar($avatar)
967 $new_avatar = str_replace("_normal.", ".", $avatar);
969 $info = Image::getInfoFromURL($new_avatar);
971 $new_avatar = $avatar;
977 function twitter_fetch_contact($uid, $data, $create_user)
979 if ($data->id_str == "") {
983 $avatar = twitter_fix_avatar($data->profile_image_url_https);
984 $url = "https://twitter.com/" . $data->screen_name;
985 $addr = $data->screen_name . "@twitter.com";
987 GContact::update(["url" => $url, "network" => NETWORK_TWITTER,
988 "photo" => $avatar, "hide" => true,
989 "name" => $data->name, "nick" => $data->screen_name,
990 "location" => $data->location, "about" => $data->description,
991 "addr" => $addr, "generation" => 2]);
993 $fields = ['url' => $url, 'network' => NETWORK_TWITTER,
994 'name' => $data->name, 'nick' => $data->screen_name, 'addr' => $addr,
995 'location' => $data->location, 'about' => $data->description];
997 $cid = Contact::getIdForURL($url, 0, true, $fields);
999 dba::update('contact', $fields, ['id' => $cid]);
1000 Contact::updateAvatar($avatar, 0, $cid);
1003 $contact = dba::selectFirst('contact', [], ['uid' => $uid, 'alias' => "twitter::" . $data->id_str]);
1004 if (!DBM::is_result($contact) && !$create_user) {
1008 if (!DBM::is_result($contact)) {
1009 // create contact record
1010 $fields['uid'] = $uid;
1011 $fields['created'] = DateTimeFormat::utcNow();
1012 $fields['nurl'] = normalise_link($url);
1013 $fields['alias'] = 'twitter::' . $data->id_str;
1014 $fields['poll'] = 'twitter::' . $data->id_str;
1015 $fields['rel'] = CONTACT_IS_FRIEND;
1016 $fields['priority'] = 1;
1017 $fields['writable'] = true;
1018 $fields['blocked'] = false;
1019 $fields['readonly'] = false;
1020 $fields['pending'] = false;
1022 if (!dba::insert('contact', $fields)) {
1026 $contact_id = dba::lastInsertId();
1028 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1030 Contact::updateAvatar($avatar, $uid, $contact_id);
1032 if ($contact["readonly"] || $contact["blocked"]) {
1033 logger("twitter_fetch_contact: Contact '" . $contact["nick"] . "' is blocked or readonly.", LOGGER_DEBUG);
1037 $contact_id = $contact['id'];
1039 // update profile photos once every twelve hours as we have no notification of when they change.
1040 $update_photo = ($contact['avatar-date'] < DateTimeFormat::utc('now -12 hours'));
1042 // check that we have all the photos, this has been known to fail on occasion
1043 if (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']) || $update_photo) {
1044 logger("twitter_fetch_contact: Updating contact " . $data->screen_name, LOGGER_DEBUG);
1046 Contact::updateAvatar($avatar, $uid, $contact['id']);
1048 $fields['name-date'] = DateTimeFormat::utcNow();
1049 $fields['uri-date'] = DateTimeFormat::utcNow();
1051 dba::update('contact', $fields, ['id' => $contact['id']]);
1058 function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1060 $ckey = Config::get('twitter', 'consumerkey');
1061 $csecret = Config::get('twitter', 'consumersecret');
1062 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1063 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1065 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1068 if (DBM::is_result($r)) {
1076 if ($screen_name != "") {
1077 $parameters["screen_name"] = $screen_name;
1080 if ($user_id != "") {
1081 $parameters["user_id"] = $user_id;
1084 // Fetching user data
1085 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1087 $user = $connection->get('users/show', $parameters);
1088 } catch (TwitterOAuthException $e) {
1089 logger('twitter_fetchuser: Error fetching user ' . $uid . ': ' . $e->getMessage());
1093 if (!is_object($user)) {
1097 $contact_id = twitter_fetch_contact($uid, $user, true);
1102 function twitter_expand_entities(App $a, $body, $item, $picture)
1108 foreach ($item->entities->hashtags AS $hashtag) {
1109 $url = "#[url=" . $a->get_baseurl() . "/search?tag=" . rawurlencode($hashtag->text) . "]" . $hashtag->text . "[/url]";
1110 $tags_arr["#" . $hashtag->text] = $url;
1111 $body = str_replace("#" . $hashtag->text, $url, $body);
1114 foreach ($item->entities->user_mentions AS $mention) {
1115 $url = "@[url=https://twitter.com/" . rawurlencode($mention->screen_name) . "]" . $mention->screen_name . "[/url]";
1116 $tags_arr["@" . $mention->screen_name] = $url;
1117 $body = str_replace("@" . $mention->screen_name, $url, $body);
1120 if (isset($item->entities->urls)) {
1126 foreach ($item->entities->urls as $url) {
1127 $plain = str_replace($url->url, '', $plain);
1129 if ($url->url && $url->expanded_url && $url->display_url) {
1130 $expanded_url = Network::finalUrl($url->expanded_url);
1132 $oembed_data = OEmbed::fetchURL($expanded_url);
1134 // Quickfix: Workaround for URL with "[" and "]" in it
1135 if (strpos($expanded_url, "[") || strpos($expanded_url, "]")) {
1136 $expanded_url = $url->url;
1140 $type = $oembed_data->type;
1143 if ($oembed_data->type == "video") {
1144 //$body = str_replace($url->url,
1145 // "[video]".$expanded_url."[/video]", $body);
1146 //$dontincludemedia = true;
1147 $type = $oembed_data->type;
1148 $footerurl = $expanded_url;
1149 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1151 $body = str_replace($url->url, $footerlink, $body);
1152 //} elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia) {
1153 } elseif (($oembed_data->type == "photo") && isset($oembed_data->url)) {
1154 $body = str_replace($url->url, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1155 //$dontincludemedia = true;
1156 } elseif ($oembed_data->type != "link") {
1157 $body = str_replace($url->url, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1159 $img_str = Network::fetchUrl($expanded_url, true, $redirects, 4);
1161 $tempfile = tempnam(get_temppath(), "cache");
1162 file_put_contents($tempfile, $img_str);
1163 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1166 if (substr($mime, 0, 6) == "image/") {
1168 $body = str_replace($url->url, "[img]" . $expanded_url . "[/img]", $body);
1169 //$dontincludemedia = true;
1171 $type = $oembed_data->type;
1172 $footerurl = $expanded_url;
1173 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1175 $body = str_replace($url->url, $footerlink, $body);
1181 if ($footerurl != "") {
1182 $footer = add_page_info($footerurl, false, $picture);
1185 if (($footerlink != "") && (trim($footer) != "")) {
1186 $removedlink = trim(str_replace($footerlink, "", $body));
1188 if (($removedlink == "") || strstr($body, $removedlink)) {
1189 $body = $removedlink;
1195 if (($footer == "") && ($picture != "")) {
1196 $body .= "\n\n[img]" . $picture . "[/img]\n";
1197 } elseif (($footer == "") && ($picture == "")) {
1198 $body = add_page_info_to_body($body);
1202 // it seems as if the entities aren't always covering all mentions. So the rest will be checked here
1203 $tags = get_tags($body);
1206 foreach ($tags as $tag) {
1207 if (strstr(trim($tag), " ")) {
1211 if (strpos($tag, '#') === 0) {
1212 if (strpos($tag, '[url=')) {
1216 // don't link tags that are already embedded in links
1217 if (preg_match('/\[(.*?)' . preg_quote($tag, '/') . '(.*?)\]/', $body)) {
1220 if (preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag, '/') . '(.*?)\)/', $body)) {
1224 $basetag = str_replace('_', ' ', substr($tag, 1));
1225 $url = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1226 $body = str_replace($tag, $url, $body);
1227 $tags_arr["#" . $basetag] = $url;
1228 } elseif (strpos($tag, '@') === 0) {
1229 if (strpos($tag, '[url=')) {
1233 $basetag = substr($tag, 1);
1234 $url = '@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1235 $body = str_replace($tag, $url, $body);
1236 $tags_arr["@" . $basetag] = $url;
1241 $tags = implode($tags_arr, ",");
1243 return ["body" => $body, "tags" => $tags, "plain" => $plain];
1247 * @brief Fetch media entities and add media links to the body
1249 * @param object $post Twitter object with the post
1250 * @param array $postarray Array of the item that is about to be posted
1252 * @return $picture string Image URL or empty string
1254 function twitter_media_entities($post, &$postarray)
1256 // There are no media entities? So we quit.
1257 if (!is_array($post->extended_entities->media)) {
1261 // When the post links to an external page, we only take one picture.
1262 // We only do this when there is exactly one media.
1263 if ((count($post->entities->urls) > 0) && (count($post->extended_entities->media) == 1)) {
1265 foreach ($post->extended_entities->media AS $medium) {
1266 if (isset($medium->media_url_https)) {
1267 $picture = $medium->media_url_https;
1268 $postarray['body'] = str_replace($medium->url, "", $postarray['body']);
1274 // This is a pure media post, first search for all media urls
1276 foreach ($post->extended_entities->media AS $medium) {
1277 switch ($medium->type) {
1279 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . "[/img]";
1280 $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
1283 case 'animated_gif':
1284 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . "[/img]";
1285 $postarray['object-type'] = ACTIVITY_OBJ_VIDEO;
1286 if (is_array($medium->video_info->variants)) {
1288 // We take the video with the highest bitrate
1289 foreach ($medium->video_info->variants AS $variant) {
1290 if (($variant->content_type == "video/mp4") && ($variant->bitrate >= $bitrate)) {
1291 $media[$medium->url] = "\n[video]" . $variant->url . "[/video]";
1292 $bitrate = $variant->bitrate;
1297 // The following code will only be activated for test reasons
1299 // $postarray['body'] .= print_r($medium, true);
1303 // Now we replace the media urls.
1304 foreach ($media AS $key => $value) {
1305 $postarray['body'] = str_replace($key, "\n" . $value . "\n", $postarray['body']);
1310 function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact, $noquote)
1313 $postarray['network'] = NETWORK_TWITTER;
1314 $postarray['gravity'] = 0;
1315 $postarray['uid'] = $uid;
1316 $postarray['wall'] = 0;
1317 $postarray['uri'] = "twitter::" . $post->id_str;
1318 // $postarray['object'] = json_encode($post); // Activate for debugging
1320 // Don't import our own comments
1321 if (dba::exists('item', ['extid' => $postarray['uri'], 'uid' => $uid])) {
1322 logger("Item with extid " . $postarray['uri'] . " found.", LOGGER_DEBUG);
1328 if ($post->in_reply_to_status_id_str != "") {
1329 $parent = "twitter::" . $post->in_reply_to_status_id_str;
1331 $fields = ['uri', 'parent-uri', 'parent'];
1332 $parent_item = Item::selectFirst($fields, ['uri' => $parent, 'uid' => $uid]);
1333 if (!DBM::is_result($parent_item)) {
1334 $parent_item = Item::selectFirst($fields, ['extid' => $parent, 'uid' => $uid]);
1337 if (DBM::is_result($parent_item)) {
1338 $postarray['thr-parent'] = $parent_item['uri'];
1339 $postarray['parent-uri'] = $parent_item['parent-uri'];
1340 $postarray['parent'] = $parent_item['parent'];
1341 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1343 $postarray['thr-parent'] = $postarray['uri'];
1344 $postarray['parent-uri'] = $postarray['uri'];
1345 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1349 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1351 if ($post->user->id_str == $own_id) {
1352 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1355 if (DBM::is_result($r)) {
1356 $contactid = $r[0]["id"];
1358 $postarray['owner-name'] = $r[0]["name"];
1359 $postarray['owner-link'] = $r[0]["url"];
1360 $postarray['owner-avatar'] = $r[0]["photo"];
1362 logger("No self contact for user " . $uid, LOGGER_DEBUG);
1366 // Don't create accounts of people who just comment something
1367 $create_user = false;
1369 $postarray['parent-uri'] = $postarray['uri'];
1370 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1373 if ($contactid == 0) {
1374 $contactid = twitter_fetch_contact($uid, $post->user, $create_user);
1376 $postarray['owner-name'] = $post->user->name;
1377 $postarray['owner-link'] = "https://twitter.com/" . $post->user->screen_name;
1378 $postarray['owner-avatar'] = twitter_fix_avatar($post->user->profile_image_url_https);
1381 if (($contactid == 0) && !$only_existing_contact) {
1382 $contactid = $self['id'];
1383 } elseif ($contactid <= 0) {
1384 logger("Contact ID is zero or less than zero.", LOGGER_DEBUG);
1388 $postarray['contact-id'] = $contactid;
1390 $postarray['verb'] = ACTIVITY_POST;
1391 $postarray['author-name'] = $postarray['owner-name'];
1392 $postarray['author-link'] = $postarray['owner-link'];
1393 $postarray['author-avatar'] = $postarray['owner-avatar'];
1394 $postarray['plink'] = "https://twitter.com/" . $post->user->screen_name . "/status/" . $post->id_str;
1395 $postarray['app'] = strip_tags($post->source);
1397 if ($post->user->protected) {
1398 $postarray['private'] = 1;
1399 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1402 if (is_string($post->full_text)) {
1403 $postarray['body'] = $post->full_text;
1405 $postarray['body'] = $post->text;
1408 // When the post contains links then use the correct object type
1409 if (count($post->entities->urls) > 0) {
1410 $postarray['object-type'] = ACTIVITY_OBJ_BOOKMARK;
1413 // Search for media links
1414 $picture = twitter_media_entities($post, $postarray);
1416 $converted = twitter_expand_entities($a, $postarray['body'], $post, $picture);
1417 $postarray['body'] = $converted["body"];
1418 $postarray['tag'] = $converted["tags"];
1419 $postarray['created'] = DateTimeFormat::utc($post->created_at);
1420 $postarray['edited'] = DateTimeFormat::utc($post->created_at);
1422 $statustext = $converted["plain"];
1424 if (is_string($post->place->name)) {
1425 $postarray["location"] = $post->place->name;
1427 if (is_string($post->place->full_name)) {
1428 $postarray["location"] = $post->place->full_name;
1430 if (is_array($post->geo->coordinates)) {
1431 $postarray["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
1433 if (is_array($post->coordinates->coordinates)) {
1434 $postarray["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
1436 if (is_object($post->retweeted_status)) {
1437 $retweet = twitter_createpost($a, $uid, $post->retweeted_status, $self, false, false, $noquote);
1439 $retweet['object'] = $postarray['object'];
1440 $retweet['private'] = $postarray['private'];
1441 $retweet['allow_cid'] = $postarray['allow_cid'];
1442 $retweet['contact-id'] = $postarray['contact-id'];
1443 $retweet['owner-name'] = $postarray['owner-name'];
1444 $retweet['owner-link'] = $postarray['owner-link'];
1445 $retweet['owner-avatar'] = $postarray['owner-avatar'];
1447 $postarray = $retweet;
1450 if (is_object($post->quoted_status) && !$noquote) {
1451 $quoted = twitter_createpost($a, $uid, $post->quoted_status, $self, false, false, true);
1453 $postarray['body'] = $statustext;
1455 $postarray['body'] .= "\n" . share_header(
1456 $quoted['author-name'],
1457 $quoted['author-link'],
1458 $quoted['author-avatar'],
1464 $postarray['body'] .= $quoted['body'] . '[/share]';
1470 function twitter_fetchparentposts(App $a, $uid, $post, TwitterOAuth $connection, $self, $own_id)
1472 logger("twitter_fetchparentposts: Fetching for user " . $uid . " and post " . $post->id_str, LOGGER_DEBUG);
1476 while ($post->in_reply_to_status_id_str != "") {
1477 $parameters = ["trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str];
1480 $post = $connection->get('statuses/show', $parameters);
1481 } catch (TwitterOAuthException $e) {
1482 logger('twitter_fetchparentposts: Error fetching for user ' . $uid . ' and post ' . $post->id_str . ': ' . $e->getMessage());
1487 logger("twitter_fetchparentposts: Can't fetch post " . $parameters->id, LOGGER_DEBUG);
1491 if (dba::exists('item', ['uri' => 'twitter::' . $post->id_str, 'uid' => $uid])) {
1498 logger("twitter_fetchparentposts: Fetching " . count($posts) . " parents", LOGGER_DEBUG);
1500 $posts = array_reverse($posts);
1502 if (count($posts)) {
1503 foreach ($posts as $post) {
1504 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1506 if (trim($postarray['body']) == "") {
1510 $item = Item::insert($postarray);
1516 $postarray["id"] = $item;
1518 logger('twitter_fetchparentpost: User ' . $self["nick"] . ' posted parent timeline item ' . $item);
1523 function twitter_fetchhometimeline(App $a, $uid)
1525 $ckey = Config::get('twitter', 'consumerkey');
1526 $csecret = Config::get('twitter', 'consumersecret');
1527 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1528 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1529 $create_user = PConfig::get($uid, 'twitter', 'create_user');
1530 $mirror_posts = PConfig::get($uid, 'twitter', 'mirror_posts');
1532 logger("twitter_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG);
1534 $application_name = Config::get('twitter', 'application_name');
1536 if ($application_name == "") {
1537 $application_name = $a->get_hostname();
1540 require_once 'include/items.php';
1542 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1545 $own_contact = twitter_fetch_own_contact($a, $uid);
1546 } catch (TwitterOAuthException $e) {
1547 logger('twitter_fetchhometimeline: Error fetching own contact for user ' . $uid . ': ' . $e->getMessage());
1551 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1552 intval($own_contact),
1555 if (DBM::is_result($r)) {
1556 $own_id = $r[0]["nick"];
1558 logger("twitter_fetchhometimeline: Own twitter contact not found for user " . $uid, LOGGER_DEBUG);
1562 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1565 if (DBM::is_result($r)) {
1568 logger("twitter_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG);
1572 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1574 if (!DBM::is_result($u)) {
1575 logger("twitter_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG);
1579 $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
1580 //$parameters["count"] = 200;
1581 // Fetching timeline
1582 $lastid = PConfig::get($uid, 'twitter', 'lasthometimelineid');
1584 $first_time = ($lastid == "");
1586 if ($lastid != "") {
1587 $parameters["since_id"] = $lastid;
1591 $items = $connection->get('statuses/home_timeline', $parameters);
1592 } catch (TwitterOAuthException $e) {
1593 logger('twitter_fetchhometimeline: Error fetching home timeline: ' . $e->getMessage());
1597 if (!is_array($items)) {
1598 logger("twitter_fetchhometimeline: Error fetching home timeline: " . print_r($items, true), LOGGER_DEBUG);
1602 $posts = array_reverse($items);
1604 logger("twitter_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1606 if (count($posts)) {
1607 foreach ($posts as $post) {
1608 if ($post->id_str > $lastid) {
1609 $lastid = $post->id_str;
1610 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1617 if (stristr($post->source, $application_name) && $post->user->screen_name == $own_id) {
1618 logger("twitter_fetchhometimeline: Skip previously sended post", LOGGER_DEBUG);
1622 if ($mirror_posts && $post->user->screen_name == $own_id && $post->in_reply_to_status_id_str == "") {
1623 logger("twitter_fetchhometimeline: Skip post that will be mirrored", LOGGER_DEBUG);
1627 if ($post->in_reply_to_status_id_str != "") {
1628 twitter_fetchparentposts($a, $uid, $post, $connection, $self, $own_id);
1631 $postarray = twitter_createpost($a, $uid, $post, $self, $create_user, true, false);
1633 if (trim($postarray['body']) == "") {
1639 if ($postarray['uri'] == $postarray['parent-uri']) {
1640 $contact = dba::selectFirst('contact', [], ['id' => $postarray['contact-id'], 'self' => false]);
1641 if (DBM::is_result($contact)) {
1642 $notify = Item::isRemoteSelf($contact, $postarray);
1646 $item = Item::insert($postarray, false, $notify);
1647 $postarray["id"] = $item;
1649 logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1652 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1654 // Fetching mentions
1655 $lastid = PConfig::get($uid, 'twitter', 'lastmentionid');
1657 $first_time = ($lastid == "");
1659 if ($lastid != "") {
1660 $parameters["since_id"] = $lastid;
1664 $items = $connection->get('statuses/mentions_timeline', $parameters);
1665 } catch (TwitterOAuthException $e) {
1666 logger('twitter_fetchhometimeline: Error fetching mentions: ' . $e->getMessage());
1670 if (!is_array($items)) {
1671 logger("twitter_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG);
1675 $posts = array_reverse($items);
1677 logger("twitter_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1679 if (count($posts)) {
1680 foreach ($posts as $post) {
1681 if ($post->id_str > $lastid) {
1682 $lastid = $post->id_str;
1689 if ($post->in_reply_to_status_id_str != "") {
1690 twitter_fetchparentposts($a, $uid, $post, $connection, $self, $own_id);
1693 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1695 if (trim($postarray['body']) == "") {
1699 $item = Item::insert($postarray);
1701 logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1705 PConfig::set($uid, 'twitter', 'lastmentionid', $lastid);
1708 function twitter_fetch_own_contact(App $a, $uid)
1710 $ckey = Config::get('twitter', 'consumerkey');
1711 $csecret = Config::get('twitter', 'consumersecret');
1712 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1713 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1715 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1719 if ($own_id == "") {
1720 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1722 // Fetching user data
1723 // get() may throw TwitterOAuthException, but we will catch it later
1724 $user = $connection->get('account/verify_credentials');
1726 PConfig::set($uid, 'twitter', 'own_id', $user->id_str);
1728 $contact_id = twitter_fetch_contact($uid, $user, true);
1730 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1732 dbesc("twitter::" . $own_id));
1733 if (DBM::is_result($r)) {
1734 $contact_id = $r[0]["id"];
1736 PConfig::delete($uid, 'twitter', 'own_id');
1743 function twitter_is_retweet(App $a, $uid, $body)
1745 $body = trim($body);
1747 // Skip if it isn't a pure repeated messages
1748 // Does it start with a share?
1749 if (strpos($body, "[share") > 0) {
1753 // Does it end with a share?
1754 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1758 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1759 // Skip if there is no shared message in there
1760 if ($body == $attributes) {
1765 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1766 if ($matches[1] != "") {
1767 $link = $matches[1];
1770 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1771 if ($matches[1] != "") {
1772 $link = $matches[1];
1775 $id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link);
1780 logger('twitter_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG);
1782 $ckey = Config::get('twitter', 'consumerkey');
1783 $csecret = Config::get('twitter', 'consumersecret');
1784 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1785 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1787 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1788 $result = $connection->post('statuses/retweet/' . $id);
1790 logger('twitter_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);
1792 return !isset($result->errors);