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 config/addon.config.php or use the admin panel.
54 * 'consumerkey' => '',
55 * 'consumersecret' => '',
58 * To activate the addon itself add it to the system.addon
59 * setting. After this, your user can configure their Twitter account settings
60 * from "Settings -> Addon Settings".
62 * Requirements: PHP5, curl
65 use Abraham\TwitterOAuth\TwitterOAuth;
66 use Abraham\TwitterOAuth\TwitterOAuthException;
68 use Friendica\Content\OEmbed;
69 use Friendica\Content\Text\BBCode;
70 use Friendica\Content\Text\Plaintext;
71 use Friendica\Core\Config;
72 use Friendica\Core\Hook;
73 use Friendica\Core\L10n;
74 use Friendica\Core\Logger;
75 use Friendica\Core\PConfig;
76 use Friendica\Core\Protocol;
77 use Friendica\Core\Renderer;
78 use Friendica\Core\Worker;
79 use Friendica\Database\DBA;
80 use Friendica\Model\Contact;
81 use Friendica\Model\Conversation;
82 use Friendica\Model\GContact;
83 use Friendica\Model\Group;
84 use Friendica\Model\Item;
85 use Friendica\Model\ItemContent;
86 use Friendica\Model\Queue;
87 use Friendica\Model\User;
88 use Friendica\Object\Image;
89 use Friendica\Util\Config\ConfigFileLoader;
90 use Friendica\Util\DateTimeFormat;
91 use Friendica\Util\Network;
92 use Friendica\Util\Strings;
94 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
96 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
98 function twitter_install()
100 // we need some hooks, for the configuration and for sending tweets
101 Hook::register('load_config' , __FILE__, 'twitter_load_config');
102 Hook::register('connector_settings' , __FILE__, 'twitter_settings');
103 Hook::register('connector_settings_post', __FILE__, 'twitter_settings_post');
104 Hook::register('hook_fork' , __FILE__, 'twitter_hook_fork');
105 Hook::register('post_local' , __FILE__, 'twitter_post_local');
106 Hook::register('notifier_normal' , __FILE__, 'twitter_post_hook');
107 Hook::register('jot_networks' , __FILE__, 'twitter_jot_nets');
108 Hook::register('cron' , __FILE__, 'twitter_cron');
109 Hook::register('queue_predeliver' , __FILE__, 'twitter_queue_hook');
110 Hook::register('follow' , __FILE__, 'twitter_follow');
111 Hook::register('expire' , __FILE__, 'twitter_expire');
112 Hook::register('prepare_body' , __FILE__, 'twitter_prepare_body');
113 Hook::register('check_item_notification', __FILE__, 'twitter_check_item_notification');
114 Logger::log("installed twitter");
117 function twitter_uninstall()
119 Hook::unregister('load_config' , __FILE__, 'twitter_load_config');
120 Hook::unregister('connector_settings' , __FILE__, 'twitter_settings');
121 Hook::unregister('connector_settings_post', __FILE__, 'twitter_settings_post');
122 Hook::unregister('hook_fork' , __FILE__, 'twitter_hook_fork');
123 Hook::unregister('post_local' , __FILE__, 'twitter_post_local');
124 Hook::unregister('notifier_normal' , __FILE__, 'twitter_post_hook');
125 Hook::unregister('jot_networks' , __FILE__, 'twitter_jot_nets');
126 Hook::unregister('cron' , __FILE__, 'twitter_cron');
127 Hook::unregister('queue_predeliver' , __FILE__, 'twitter_queue_hook');
128 Hook::unregister('follow' , __FILE__, 'twitter_follow');
129 Hook::unregister('expire' , __FILE__, 'twitter_expire');
130 Hook::unregister('prepare_body' , __FILE__, 'twitter_prepare_body');
131 Hook::unregister('check_item_notification', __FILE__, 'twitter_check_item_notification');
133 // old setting - remove only
134 Hook::unregister('post_local_end' , __FILE__, 'twitter_post_hook');
135 Hook::unregister('addon_settings' , __FILE__, 'twitter_settings');
136 Hook::unregister('addon_settings_post', __FILE__, 'twitter_settings_post');
139 function twitter_load_config(App $a, ConfigFileLoader $loader)
141 $a->getConfigCache()->load($loader->loadAddonConfig('twitter'));
144 function twitter_check_item_notification(App $a, array &$notification_data)
146 $own_id = PConfig::get($notification_data["uid"], 'twitter', 'own_id');
148 $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
149 intval($notification_data["uid"]),
150 DBA::escape("twitter::".$own_id)
154 $notification_data["profiles"][] = $own_user[0]["url"];
158 function twitter_follow(App $a, array &$contact)
160 Logger::log("twitter_follow: Check if contact is twitter contact. " . $contact["url"], Logger::DEBUG);
162 if (!strstr($contact["url"], "://twitter.com") && !strstr($contact["url"], "@twitter.com")) {
166 // contact seems to be a twitter contact, so continue
167 $nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $contact["url"]);
168 $nickname = str_replace("@twitter.com", "", $nickname);
170 $uid = $a->user["uid"];
172 $ckey = Config::get('twitter', 'consumerkey');
173 $csecret = Config::get('twitter', 'consumersecret');
174 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
175 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
177 // If the addon is not configured (general or for this user) quit here
178 if (empty($ckey) || empty($csecret) || empty($otoken) || empty($osecret)) {
183 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
184 $connection->post('friendships/create', ['screen_name' => $nickname]);
186 twitter_fetchuser($a, $uid, $nickname);
188 $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
189 FROM `contact` WHERE `uid` = %d AND `nick` = '%s'",
191 DBA::escape($nickname));
192 if (DBA::isResult($r)) {
193 $contact["contact"] = $r[0];
197 function twitter_jot_nets(App $a, array &$jotnets_fields)
203 if (PConfig::get(local_user(), 'twitter', 'post')) {
204 $jotnets_fields[] = [
205 'type' => 'checkbox',
208 L10n::t('Post to Twitter'),
209 PConfig::get(local_user(), 'twitter', 'post_by_default')
216 function twitter_settings_post(App $a)
221 // don't check twitter settings if twitter submit button is not clicked
222 if (empty($_POST['twitter-disconnect']) && empty($_POST['twitter-submit'])) {
226 if (!empty($_POST['twitter-disconnect'])) {
228 * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
229 * from the user configuration
231 PConfig::delete(local_user(), 'twitter', 'consumerkey');
232 PConfig::delete(local_user(), 'twitter', 'consumersecret');
233 PConfig::delete(local_user(), 'twitter', 'oauthtoken');
234 PConfig::delete(local_user(), 'twitter', 'oauthsecret');
235 PConfig::delete(local_user(), 'twitter', 'post');
236 PConfig::delete(local_user(), 'twitter', 'post_by_default');
237 PConfig::delete(local_user(), 'twitter', 'lastid');
238 PConfig::delete(local_user(), 'twitter', 'mirror_posts');
239 PConfig::delete(local_user(), 'twitter', 'import');
240 PConfig::delete(local_user(), 'twitter', 'create_user');
241 PConfig::delete(local_user(), 'twitter', 'own_id');
243 if (isset($_POST['twitter-pin'])) {
244 // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
245 Logger::log('got a Twitter PIN');
246 $ckey = Config::get('twitter', 'consumerkey');
247 $csecret = Config::get('twitter', 'consumersecret');
248 // the token and secret for which the PIN was generated were hidden in the settings
249 // form as token and token2, we need a new connection to Twitter using these token
250 // and secret to request a Access Token with the PIN
252 if (empty($_POST['twitter-pin'])) {
253 throw new Exception(L10n::t('You submitted an empty PIN, please Sign In with Twitter again to get a new one.'));
256 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
257 $token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_POST['twitter-pin']]);
258 // ok, now that we have the Access Token, save them in the user config
259 PConfig::set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
260 PConfig::set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
261 PConfig::set(local_user(), 'twitter', 'post', 1);
262 } catch(Exception $e) {
263 info($e->getMessage());
264 } catch(TwitterOAuthException $e) {
265 info($e->getMessage());
267 // reload the Addon Settings page, if we don't do it see Bug #42
268 $a->internalRedirect('settings/connectors');
270 // if no PIN is supplied in the POST variables, the user has changed the setting
271 // to post a tweet for every new __public__ posting to the wall
272 PConfig::set(local_user(), 'twitter', 'post', intval($_POST['twitter-enable']));
273 PConfig::set(local_user(), 'twitter', 'post_by_default', intval($_POST['twitter-default']));
274 PConfig::set(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror']));
275 PConfig::set(local_user(), 'twitter', 'import', intval($_POST['twitter-import']));
276 PConfig::set(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user']));
278 if (!intval($_POST['twitter-mirror'])) {
279 PConfig::delete(local_user(), 'twitter', 'lastid');
282 info(L10n::t('Twitter settings updated.') . EOL);
287 function twitter_settings(App $a, &$s)
292 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
294 * 1) Check that we have global consumer key & secret
295 * 2) If no OAuthtoken & stuff is present, generate button to get some
296 * 3) Checkbox for "Send public notices (280 chars only)
298 $ckey = Config::get('twitter', 'consumerkey');
299 $csecret = Config::get('twitter', 'consumersecret');
300 $otoken = PConfig::get(local_user(), 'twitter', 'oauthtoken');
301 $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret');
303 $enabled = intval(PConfig::get(local_user(), 'twitter', 'post'));
304 $defenabled = intval(PConfig::get(local_user(), 'twitter', 'post_by_default'));
305 $mirrorenabled = intval(PConfig::get(local_user(), 'twitter', 'mirror_posts'));
306 $importenabled = intval(PConfig::get(local_user(), 'twitter', 'import'));
307 $create_userenabled = intval(PConfig::get(local_user(), 'twitter', 'create_user'));
309 $css = (($enabled) ? '' : '-disabled');
311 $s .= '<span id="settings_twitter_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
312 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
314 $s .= '<div id="settings_twitter_expanded" class="settings-block" style="display: none;">';
315 $s .= '<span class="fakelink" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
316 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
319 if ((!$ckey) && (!$csecret)) {
320 /* no global consumer keys
321 * display warning and skip personal config
323 $s .= '<p>' . L10n::t('No consumer key pair for Twitter found. Please contact your site administrator.') . '</p>';
325 // ok we have a consumer key pair now look into the OAuth stuff
326 if ((!$otoken) && (!$osecret)) {
327 /* the user has not yet connected the account to twitter...
328 * get a temporary OAuth key/secret pair and display a button with
329 * which the user can request a PIN to connect the account to a
330 * account at Twitter.
332 $connection = new TwitterOAuth($ckey, $csecret);
334 $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
335 $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>';
336 $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>';
337 $s .= '<div id="twitter-pin-wrapper">';
338 $s .= '<label id="twitter-pin-label" for="twitter-pin">' . L10n::t('Copy the PIN from Twitter here') . '</label>';
339 $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
340 $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result['oauth_token'] . '" />';
341 $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result['oauth_token_secret'] . '" />';
342 $s .= '</div><div class="clear"></div>';
343 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
344 } catch (TwitterOAuthException $e) {
345 $s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
349 * we have an OAuth key / secret pair for the user
350 * so let's give a chance to disable the postings to Twitter
352 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
354 $details = $connection->get('account/verify_credentials');
356 $field_checkbox = Renderer::getMarkupTemplate('field_checkbox.tpl');
358 $s .= '<div id="twitter-info" >
359 <p>' . L10n::t('Currently connected to: ') . '<a href="https://twitter.com/' . $details->screen_name . '" target="_twitter">' . $details->screen_name . '</a>
360 <button type="submit" name="twitter-disconnect" value="1">' . L10n::t('Disconnect') . '</button>
362 <p id="twitter-info-block">
363 <a href="https://twitter.com/' . $details->screen_name . '" target="_twitter"><img id="twitter-avatar" src="' . $details->profile_image_url . '" /></a>
364 <em>' . $details->description . '</em>
367 $s .= '<div class="clear"></div>';
369 $s .= Renderer::replaceMacros($field_checkbox, [
370 '$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.')]
372 if ($a->user['hidewall']) {
373 $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>';
375 $s .= Renderer::replaceMacros($field_checkbox, [
376 '$field' => ['twitter-default', L10n::t('Send public postings to Twitter by default'), $defenabled, '']
378 $s .= Renderer::replaceMacros($field_checkbox, [
379 '$field' => ['twitter-mirror', L10n::t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '']
381 $s .= Renderer::replaceMacros($field_checkbox, [
382 '$field' => ['twitter-import', L10n::t('Import the remote timeline'), $importenabled, '']
384 $s .= Renderer::replaceMacros($field_checkbox, [
385 '$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.')]
387 $s .= '<div class="clear"></div>';
388 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
389 } catch (TwitterOAuthException $e) {
390 $s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
394 $s .= '</div><div class="clear"></div>';
397 function twitter_hook_fork(App $a, array &$b)
399 if ($b['name'] != 'notifier_normal') {
405 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
406 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
407 $b['execute'] = false;
411 // if post comes from twitter don't send it back
412 if ($post['extid'] == Protocol::TWITTER) {
413 $b['execute'] = false;
417 if ($post['app'] == 'Twitter') {
418 $b['execute'] = false;
422 if (PConfig::get($post['uid'], 'twitter', 'import')) {
423 // Don't fork if it isn't a reply to a twitter post
424 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::TWITTER])) {
425 Logger::log('No twitter parent found for item ' . $post['id']);
426 $b['execute'] = false;
430 // Comments are never exported when we don't import the twitter timeline
431 if (!strstr($post['postopts'], 'twitter') || ($post['parent'] != $post['id']) || $post['private']) {
432 $b['execute'] = false;
438 function twitter_post_local(App $a, array &$b)
444 if (!local_user() || (local_user() != $b['uid'])) {
448 $twitter_post = intval(PConfig::get(local_user(), 'twitter', 'post'));
449 $twitter_enable = (($twitter_post && !empty($_REQUEST['twitter_enable'])) ? intval($_REQUEST['twitter_enable']) : 0);
451 // if API is used, default to the chosen settings
452 if ($b['api_source'] && intval(PConfig::get(local_user(), 'twitter', 'post_by_default'))) {
456 if (!$twitter_enable) {
460 if (strlen($b['postopts'])) {
461 $b['postopts'] .= ',';
464 $b['postopts'] .= 'twitter';
467 function twitter_action(App $a, $uid, $pid, $action)
469 $ckey = Config::get('twitter', 'consumerkey');
470 $csecret = Config::get('twitter', 'consumersecret');
471 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
472 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
474 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
476 $post = ['id' => $pid];
478 Logger::log("twitter_action '" . $action . "' ID: " . $pid . " data: " . print_r($post, true), Logger::DATA);
482 // To-Do: $result = $connection->post('statuses/destroy', $post);
486 $result = $connection->post('favorites/create', $post);
489 $result = $connection->post('favorites/destroy', $post);
492 Logger::log('Unhandled action ' . $action, Logger::DEBUG);
495 Logger::log("twitter_action '" . $action . "' send, result: " . print_r($result, true), Logger::DEBUG);
498 function twitter_post_hook(App $a, array &$b)
501 if (!PConfig::get($b["uid"], 'twitter', 'import')
502 && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
506 if ($b['parent'] != $b['id']) {
507 Logger::log("twitter_post_hook: parameter " . print_r($b, true), Logger::DATA);
509 // Looking if its a reply to a twitter post
510 if ((substr($b["parent-uri"], 0, 9) != "twitter::")
511 && (substr($b["extid"], 0, 9) != "twitter::")
512 && (substr($b["thr-parent"], 0, 9) != "twitter::"))
514 Logger::log("twitter_post_hook: no twitter post " . $b["parent"]);
518 $condition = ['uri' => $b["thr-parent"], 'uid' => $b["uid"]];
519 $orig_post = Item::selectFirst([], $condition);
520 if (!DBA::isResult($orig_post)) {
521 Logger::log("twitter_post_hook: no parent found " . $b["thr-parent"]);
528 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
529 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
530 $nicknameplain = "@" . $nicknameplain;
532 Logger::log("twitter_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], Logger::DEBUG);
533 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
534 $b["body"] = $nickname . " " . $b["body"];
537 Logger::log("twitter_post_hook: parent found " . print_r($orig_post, true), Logger::DATA);
541 if ($b['private'] || !strstr($b['postopts'], 'twitter')) {
545 // Dont't post if the post doesn't belong to us.
546 // This is a check for forum postings
547 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
548 if ($b['contact-id'] != $self['id']) {
553 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
554 twitter_action($a, $b["uid"], substr($orig_post["uri"], 9), "delete");
557 if ($b['verb'] == ACTIVITY_LIKE) {
558 Logger::log("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), Logger::DEBUG);
560 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike");
562 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "like");
568 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
572 // if post comes from twitter don't send it back
573 if ($b['extid'] == Protocol::TWITTER) {
577 if ($b['app'] == "Twitter") {
581 Logger::log('twitter post invoked');
583 PConfig::load($b['uid'], 'twitter');
585 $ckey = Config::get('twitter', 'consumerkey');
586 $csecret = Config::get('twitter', 'consumersecret');
587 $otoken = PConfig::get($b['uid'], 'twitter', 'oauthtoken');
588 $osecret = PConfig::get($b['uid'], 'twitter', 'oauthsecret');
590 if ($ckey && $csecret && $otoken && $osecret) {
591 Logger::log('twitter: we have customer key and oauth stuff, going to send.', Logger::DEBUG);
593 // If it's a repeated message from twitter then do a native retweet and exit
594 if (twitter_is_retweet($a, $b['uid'], $b['body'])) {
598 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
600 // Set the timeout for upload to 30 seconds
601 $connection->setTimeouts(10, 30);
605 // Handling non-native reshares
606 $b['body'] = Friendica\Content\Text\BBCode::convertShare(
608 function (array $attributes, array $author_contact, $content, $is_quote_share) {
609 return twitter_convert_share($attributes, $author_contact, $content, $is_quote_share);
613 $b['body'] = twitter_update_mentions($b['body']);
615 $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 8);
616 $msg = $msgarr["text"];
618 if (($msg == "") && isset($msgarr["title"])) {
619 $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
624 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
625 $msg .= "\n" . $msgarr["url"];
631 if (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
632 $image = $msgarr["image"];
639 // and now tweet it :-)
642 if (!empty($image)) {
644 $img_str = Network::fetchUrl($image);
646 $tempfile = tempnam(get_temppath(), 'cache');
647 file_put_contents($tempfile, $img_str);
649 $media = $connection->upload('media/upload', ['media' => $tempfile]);
653 if (isset($media->media_id_string)) {
654 $post['media_ids'] = $media->media_id_string;
656 throw new Exception('Failed upload of ' . $image);
658 } catch (Exception $e) {
659 Logger::log('Exception when trying to send to Twitter: ' . $e->getMessage());
661 // Workaround: Remove the picture link so that the post can be reposted without it
662 // When there is another url already added, a second url would be superfluous.
664 $msg .= "\n" . $image;
671 $post['status'] = $msg;
674 $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
677 $url = 'statuses/update';
678 $result = $connection->post($url, $post);
679 Logger::log('twitter_post send, result: ' . print_r($result, true), Logger::DEBUG);
681 if (!empty($result->source)) {
682 Config::set("twitter", "application_name", strip_tags($result->source));
685 if (!empty($result->errors)) {
686 Logger::log('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
688 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
689 if (DBA::isResult($r)) {
690 $a->contact = $r[0]["id"];
693 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $post]);
695 Queue::add($a->contact, Protocol::TWITTER, $s);
696 notice(L10n::t('Twitter post failed. Queued for retry.') . EOL);
697 } elseif ($iscomment) {
698 Logger::log('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']);
699 Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]);
704 function twitter_addon_admin_post(App $a)
706 $consumerkey = !empty($_POST['consumerkey']) ? Strings::escapeTags(trim($_POST['consumerkey'])) : '';
707 $consumersecret = !empty($_POST['consumersecret']) ? Strings::escapeTags(trim($_POST['consumersecret'])) : '';
708 Config::set('twitter', 'consumerkey', $consumerkey);
709 Config::set('twitter', 'consumersecret', $consumersecret);
710 info(L10n::t('Settings updated.') . EOL);
713 function twitter_addon_admin(App $a, &$o)
715 $t = Renderer::getMarkupTemplate("admin.tpl", "addon/twitter/");
717 $o = Renderer::replaceMacros($t, [
718 '$submit' => L10n::t('Save Settings'),
719 // name, label, value, help, [extra values]
720 '$consumerkey' => ['consumerkey', L10n::t('Consumer key'), Config::get('twitter', 'consumerkey'), ''],
721 '$consumersecret' => ['consumersecret', L10n::t('Consumer secret'), Config::get('twitter', 'consumersecret'), ''],
725 function twitter_cron(App $a)
727 $last = Config::get('twitter', 'last_poll');
729 $poll_interval = intval(Config::get('twitter', 'poll_interval'));
730 if (!$poll_interval) {
731 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
735 $next = $last + ($poll_interval * 60);
736 if ($next > time()) {
737 Logger::log('twitter: poll intervall not reached');
741 Logger::log('twitter: cron_start');
743 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1'");
744 if (DBA::isResult($r)) {
745 foreach ($r as $rr) {
746 Logger::log('twitter: fetching for user ' . $rr['uid']);
747 Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], "addon/twitter/twitter_sync.php", 1, (int) $rr['uid']);
751 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
752 if ($abandon_days < 1) {
756 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
758 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1'");
759 if (DBA::isResult($r)) {
760 foreach ($r as $rr) {
761 if ($abandon_days != 0) {
762 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
763 if (!DBA::isResult($user)) {
764 Logger::log('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
769 Logger::log('twitter: importing timeline from user ' . $rr['uid']);
770 Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], "addon/twitter/twitter_sync.php", 2, (int) $rr['uid']);
773 // check for new contacts once a day
774 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
775 if($last_contact_check)
776 $next_contact_check = $last_contact_check + 86400;
778 $next_contact_check = 0;
780 if($next_contact_check <= time()) {
781 pumpio_getallusers($a, $rr["uid"]);
782 PConfig::set($rr['uid'],'pumpio','contact_check',time());
788 Logger::log('twitter: cron_end');
790 Config::set('twitter', 'last_poll', time());
793 function twitter_expire(App $a)
795 $days = Config::get('twitter', 'expire');
801 $r = Item::select(['id'], ['deleted' => true, 'network' => Protocol::TWITTER]);
802 while ($row = DBA::fetch($r)) {
803 DBA::delete('item', ['id' => $row['id']]);
807 Logger::log('twitter_expire: expire_start');
809 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
810 if (DBA::isResult($r)) {
811 foreach ($r as $rr) {
812 Logger::log('twitter_expire: user ' . $rr['uid']);
813 Item::expire($rr['uid'], $days, Protocol::TWITTER, true);
817 Logger::log('twitter_expire: expire_end');
820 function twitter_prepare_body(App $a, array &$b)
822 if ($b["item"]["network"] != Protocol::TWITTER) {
829 $item["plink"] = $a->getBaseURL() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
831 $condition = ['uri' => $item["thr-parent"], 'uid' => local_user()];
832 $orig_post = Item::selectFirst(['author-link'], $condition);
833 if (DBA::isResult($orig_post)) {
834 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
835 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
836 $nicknameplain = "@" . $nicknameplain;
838 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
839 $item["body"] = $nickname . " " . $item["body"];
843 $msgarr = ItemContent::getPlaintextPost($item, $max_char, true, 8);
844 $msg = $msgarr["text"];
846 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
847 $msg .= " " . $msgarr["url"];
850 if (isset($msgarr["image"])) {
851 $msg .= " " . $msgarr["image"];
854 $b['html'] = nl2br(htmlspecialchars($msg));
859 * @brief Build the item array for the mirrored post
861 * @param App $a Application class
862 * @param integer $uid User id
863 * @param object $post Twitter object with the post
865 * @return array item data to be posted
867 function twitter_do_mirrorpost(App $a, $uid, $post)
869 $datarray['api_source'] = true;
870 $datarray['profile_uid'] = $uid;
871 $datarray['extid'] = Protocol::TWITTER;
872 $datarray['message_id'] = Item::newURI($uid, Protocol::TWITTER . ':' . $post->id);
873 $datarray['protocol'] = Conversation::PARCEL_TWITTER;
874 $datarray['source'] = json_encode($post);
875 $datarray['title'] = '';
877 if (!empty($post->retweeted_status)) {
878 // We don't support nested shares, so we mustn't show quotes as shares on retweets
879 $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true);
881 if (empty($item['body'])) {
885 $datarray['body'] = "\n" . share_header(
886 $item['author-name'],
887 $item['author-link'],
888 $item['author-avatar'],
894 $datarray['body'] .= $item['body'] . '[/share]';
896 $item = twitter_createpost($a, $uid, $post, ['id' => 0], false, false, false);
898 if (empty($item['body'])) {
902 $datarray['body'] = $item['body'];
905 $datarray['source'] = $item['app'];
906 $datarray['verb'] = $item['verb'];
908 if (isset($item['location'])) {
909 $datarray['location'] = $item['location'];
912 if (isset($item['coord'])) {
913 $datarray['coord'] = $item['coord'];
919 function twitter_fetchtimeline(App $a, $uid)
921 $ckey = Config::get('twitter', 'consumerkey');
922 $csecret = Config::get('twitter', 'consumersecret');
923 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
924 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
925 $lastid = PConfig::get($uid, 'twitter', 'lastid');
927 $application_name = Config::get('twitter', 'application_name');
929 if ($application_name == "") {
930 $application_name = $a->getHostName();
933 $has_picture = false;
935 require_once 'mod/item.php';
936 require_once 'mod/share.php';
938 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
940 $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
942 $first_time = ($lastid == "");
945 $parameters["since_id"] = $lastid;
949 $items = $connection->get('statuses/user_timeline', $parameters);
950 } catch (TwitterOAuthException $e) {
951 Logger::log('Error fetching timeline for user ' . $uid . ': ' . $e->getMessage());
955 if (!is_array($items)) {
956 Logger::log('No items for user ' . $uid, Logger::INFO);
960 $posts = array_reverse($items);
962 Logger::log('Starting from ID ' . $lastid . ' for user ' . $uid, Logger::DEBUG);
965 foreach ($posts as $post) {
966 if ($post->id_str > $lastid) {
967 $lastid = $post->id_str;
968 PConfig::set($uid, 'twitter', 'lastid', $lastid);
975 if (!stristr($post->source, $application_name)) {
976 $_SESSION["authenticated"] = true;
977 $_SESSION["uid"] = $uid;
979 Logger::log('Preparing Twitter ID ' . $post->id_str . ' for user ' . $uid, Logger::DEBUG);
981 $_REQUEST = twitter_do_mirrorpost($a, $uid, $post);
983 if (empty($_REQUEST['body'])) {
987 Logger::log('Posting Twitter ID ' . $post->id_str . ' for user ' . $uid);
993 PConfig::set($uid, 'twitter', 'lastid', $lastid);
994 Logger::log('Last ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
997 function twitter_queue_hook(App $a)
999 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
1000 DBA::escape(Protocol::TWITTER)
1002 if (!DBA::isResult($qi)) {
1006 foreach ($qi as $x) {
1007 if ($x['network'] !== Protocol::TWITTER) {
1011 Logger::log('twitter_queue: run');
1013 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
1014 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
1017 if (!DBA::isResult($r)) {
1023 $ckey = Config::get('twitter', 'consumerkey');
1024 $csecret = Config::get('twitter', 'consumersecret');
1025 $otoken = PConfig::get($user['uid'], 'twitter', 'oauthtoken');
1026 $osecret = PConfig::get($user['uid'], 'twitter', 'oauthsecret');
1030 if ($ckey && $csecret && $otoken && $osecret) {
1031 Logger::log('twitter_queue: able to post');
1033 $z = unserialize($x['content']);
1035 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1036 $result = $connection->post($z['url'], $z['post']);
1038 Logger::log('twitter_queue: post result: ' . print_r($result, true), Logger::DEBUG);
1040 if ($result->errors) {
1041 Logger::log('twitter_queue: Send to Twitter failed: "' . print_r($result->errors, true) . '"');
1044 Queue::removeItem($x['id']);
1047 Logger::log("twitter_queue: Error getting tokens for user " . $user['uid']);
1051 Logger::log('twitter_queue: delayed');
1052 Queue::updateTime($x['id']);
1057 function twitter_fix_avatar($avatar)
1059 $new_avatar = str_replace("_normal.", ".", $avatar);
1061 $info = Image::getInfoFromURL($new_avatar);
1063 $new_avatar = $avatar;
1069 function twitter_fetch_contact($uid, $data, $create_user)
1071 if (empty($data->id_str)) {
1075 $avatar = twitter_fix_avatar($data->profile_image_url_https);
1076 $url = "https://twitter.com/" . $data->screen_name;
1077 $addr = $data->screen_name . "@twitter.com";
1079 GContact::update(["url" => $url, "network" => Protocol::TWITTER,
1080 "photo" => $avatar, "hide" => true,
1081 "name" => $data->name, "nick" => $data->screen_name,
1082 "location" => $data->location, "about" => $data->description,
1083 "addr" => $addr, "generation" => 2]);
1085 $fields = ['url' => $url, 'network' => Protocol::TWITTER,
1086 'name' => $data->name, 'nick' => $data->screen_name, 'addr' => $addr,
1087 'location' => $data->location, 'about' => $data->description];
1089 $cid = Contact::getIdForURL($url, 0, true, $fields);
1091 DBA::update('contact', $fields, ['id' => $cid]);
1092 Contact::updateAvatar($avatar, 0, $cid);
1095 $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'alias' => "twitter::" . $data->id_str]);
1096 if (!DBA::isResult($contact) && !$create_user) {
1100 if (!DBA::isResult($contact)) {
1101 // create contact record
1102 $fields['uid'] = $uid;
1103 $fields['created'] = DateTimeFormat::utcNow();
1104 $fields['nurl'] = Strings::normaliseLink($url);
1105 $fields['alias'] = 'twitter::' . $data->id_str;
1106 $fields['poll'] = 'twitter::' . $data->id_str;
1107 $fields['rel'] = Contact::FRIEND;
1108 $fields['priority'] = 1;
1109 $fields['writable'] = true;
1110 $fields['blocked'] = false;
1111 $fields['readonly'] = false;
1112 $fields['pending'] = false;
1114 if (!DBA::insert('contact', $fields)) {
1118 $contact_id = DBA::lastInsertId();
1120 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1122 Contact::updateAvatar($avatar, $uid, $contact_id);
1124 if ($contact["readonly"] || $contact["blocked"]) {
1125 Logger::log("twitter_fetch_contact: Contact '" . $contact["nick"] . "' is blocked or readonly.", Logger::DEBUG);
1129 $contact_id = $contact['id'];
1131 // update profile photos once every twelve hours as we have no notification of when they change.
1132 $update_photo = ($contact['avatar-date'] < DateTimeFormat::utc('now -12 hours'));
1134 // check that we have all the photos, this has been known to fail on occasion
1135 if (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']) || $update_photo) {
1136 Logger::log("twitter_fetch_contact: Updating contact " . $data->screen_name, Logger::DEBUG);
1138 Contact::updateAvatar($avatar, $uid, $contact['id']);
1140 $fields['name-date'] = DateTimeFormat::utcNow();
1141 $fields['uri-date'] = DateTimeFormat::utcNow();
1143 DBA::update('contact', $fields, ['id' => $contact['id']]);
1150 function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1152 $ckey = Config::get('twitter', 'consumerkey');
1153 $csecret = Config::get('twitter', 'consumersecret');
1154 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1155 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1157 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1160 if (DBA::isResult($r)) {
1168 if ($screen_name != "") {
1169 $parameters["screen_name"] = $screen_name;
1172 if ($user_id != "") {
1173 $parameters["user_id"] = $user_id;
1176 // Fetching user data
1177 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1179 $user = $connection->get('users/show', $parameters);
1180 } catch (TwitterOAuthException $e) {
1181 Logger::log('twitter_fetchuser: Error fetching user ' . $uid . ': ' . $e->getMessage());
1185 if (!is_object($user)) {
1189 $contact_id = twitter_fetch_contact($uid, $user, true);
1194 function twitter_expand_entities(App $a, $body, $item, $picture)
1200 foreach ($item->entities->hashtags AS $hashtag) {
1201 $url = '#[url=' . $a->getBaseURL() . '/search?tag=' . $hashtag->text . ']' . $hashtag->text . '[/url]';
1202 $tags_arr['#' . $hashtag->text] = $url;
1203 $body = str_replace('#' . $hashtag->text, $url, $body);
1206 foreach ($item->entities->user_mentions AS $mention) {
1207 $url = '@[url=https://twitter.com/' . rawurlencode($mention->screen_name) . ']' . $mention->screen_name . '[/url]';
1208 $tags_arr['@' . $mention->screen_name] = $url;
1209 $body = str_replace('@' . $mention->screen_name, $url, $body);
1212 if (isset($item->entities->urls)) {
1218 foreach ($item->entities->urls as $url) {
1219 $plain = str_replace($url->url, '', $plain);
1221 if ($url->url && $url->expanded_url && $url->display_url) {
1222 // Quote tweet, we just remove the quoted tweet URL from the body, the share block will be added later.
1223 if (isset($item->quoted_status_id_str)
1224 && substr($url->expanded_url, -strlen($item->quoted_status_id_str)) == $item->quoted_status_id_str ) {
1225 $body = str_replace($url->url, '', $body);
1229 $expanded_url = $url->expanded_url;
1231 $final_url = Network::finalUrl($url->expanded_url);
1233 $oembed_data = OEmbed::fetchURL($final_url);
1235 if (empty($oembed_data) || empty($oembed_data->type)) {
1239 // Quickfix: Workaround for URL with '[' and ']' in it
1240 if (strpos($expanded_url, '[') || strpos($expanded_url, ']')) {
1241 $expanded_url = $url->url;
1245 $type = $oembed_data->type;
1248 if ($oembed_data->type == 'video') {
1249 $type = $oembed_data->type;
1250 $footerurl = $expanded_url;
1251 $footerlink = '[url=' . $expanded_url . ']' . $url->display_url . '[/url]';
1253 $body = str_replace($url->url, $footerlink, $body);
1254 } elseif (($oembed_data->type == 'photo') && isset($oembed_data->url)) {
1255 $body = str_replace($url->url, '[url=' . $expanded_url . '][img]' . $oembed_data->url . '[/img][/url]', $body);
1256 } elseif ($oembed_data->type != 'link') {
1257 $body = str_replace($url->url, '[url=' . $expanded_url . ']' . $url->display_url . '[/url]', $body);
1259 $img_str = Network::fetchUrl($final_url, true, $redirects, 4);
1261 $tempfile = tempnam(get_temppath(), 'cache');
1262 file_put_contents($tempfile, $img_str);
1264 // See http://php.net/manual/en/function.exif-imagetype.php#79283
1265 if (filesize($tempfile) > 11) {
1266 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1273 if (substr($mime, 0, 6) == 'image/') {
1275 $body = str_replace($url->url, '[img]' . $final_url . '[/img]', $body);
1277 $type = $oembed_data->type;
1278 $footerurl = $expanded_url;
1279 $footerlink = '[url=' . $expanded_url . ']' . $url->display_url . '[/url]';
1281 $body = str_replace($url->url, $footerlink, $body);
1287 // Footer will be taken care of with a share block in the case of a quote
1288 if (empty($item->quoted_status)) {
1289 if ($footerurl != '') {
1290 $footer = add_page_info($footerurl, false, $picture);
1293 if (($footerlink != '') && (trim($footer) != '')) {
1294 $removedlink = trim(str_replace($footerlink, '', $body));
1296 if (($removedlink == '') || strstr($body, $removedlink)) {
1297 $body = $removedlink;
1303 if ($footer == '' && $picture != '') {
1304 $body .= "\n\n[img]" . $picture . "[/img]\n";
1305 } elseif ($footer == '' && $picture == '') {
1306 $body = add_page_info_to_body($body);
1311 // it seems as if the entities aren't always covering all mentions. So the rest will be checked here
1312 $tags = BBCode::getTags($body);
1315 foreach ($tags as $tag) {
1316 if (strstr(trim($tag), ' ')) {
1320 if (strpos($tag, '#') === 0) {
1321 if (strpos($tag, '[url=')) {
1325 // don't link tags that are already embedded in links
1326 if (preg_match('/\[(.*?)' . preg_quote($tag, '/') . '(.*?)\]/', $body)) {
1329 if (preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag, '/') . '(.*?)\)/', $body)) {
1333 $basetag = str_replace('_', ' ', substr($tag, 1));
1334 $url = '#[url=' . $a->getBaseURL() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
1335 $body = str_replace($tag, $url, $body);
1336 $tags_arr['#' . $basetag] = $url;
1337 } elseif (strpos($tag, '@') === 0) {
1338 if (strpos($tag, '[url=')) {
1342 $basetag = substr($tag, 1);
1343 $url = '@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1344 $body = str_replace($tag, $url, $body);
1345 $tags_arr['@' . $basetag] = $url;
1350 $tags = implode($tags_arr, ',');
1352 return ['body' => $body, 'tags' => $tags, 'plain' => $plain];
1356 * @brief Fetch media entities and add media links to the body
1358 * @param object $post Twitter object with the post
1359 * @param array $postarray Array of the item that is about to be posted
1361 * @return $picture string Image URL or empty string
1363 function twitter_media_entities($post, array &$postarray)
1365 // There are no media entities? So we quit.
1366 if (empty($post->extended_entities->media)) {
1370 // When the post links to an external page, we only take one picture.
1371 // We only do this when there is exactly one media.
1372 if ((count($post->entities->urls) > 0) && (count($post->extended_entities->media) == 1)) {
1373 $medium = $post->extended_entities->media[0];
1375 foreach ($post->entities->urls as $link) {
1376 // Let's make sure the external link url matches the media url
1377 if ($medium->url == $link->url && isset($medium->media_url_https)) {
1378 $picture = $medium->media_url_https;
1379 $postarray['body'] = str_replace($medium->url, '', $postarray['body']);
1385 // This is a pure media post, first search for all media urls
1387 foreach ($post->extended_entities->media AS $medium) {
1388 if (!isset($media[$medium->url])) {
1389 $media[$medium->url] = '';
1391 switch ($medium->type) {
1393 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
1394 $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
1397 case 'animated_gif':
1398 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
1399 $postarray['object-type'] = ACTIVITY_OBJ_VIDEO;
1400 if (is_array($medium->video_info->variants)) {
1402 // We take the video with the highest bitrate
1403 foreach ($medium->video_info->variants AS $variant) {
1404 if (($variant->content_type == 'video/mp4') && ($variant->bitrate >= $bitrate)) {
1405 $media[$medium->url] = "\n[video]" . $variant->url . '[/video]';
1406 $bitrate = $variant->bitrate;
1411 // The following code will only be activated for test reasons
1413 // $postarray['body'] .= print_r($medium, true);
1417 // Now we replace the media urls.
1418 foreach ($media AS $key => $value) {
1419 $postarray['body'] = str_replace($key, "\n" . $value . "\n", $postarray['body']);
1425 function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $only_existing_contact, $noquote)
1428 $postarray['network'] = Protocol::TWITTER;
1429 $postarray['uid'] = $uid;
1430 $postarray['wall'] = 0;
1431 $postarray['uri'] = "twitter::" . $post->id_str;
1432 $postarray['protocol'] = Conversation::PARCEL_TWITTER;
1433 $postarray['source'] = json_encode($post);
1435 // Don't import our own comments
1436 if (Item::exists(['extid' => $postarray['uri'], 'uid' => $uid])) {
1437 Logger::log("Item with extid " . $postarray['uri'] . " found.", Logger::DEBUG);
1443 if ($post->in_reply_to_status_id_str != "") {
1444 $parent = "twitter::" . $post->in_reply_to_status_id_str;
1446 $fields = ['uri', 'parent-uri', 'parent'];
1447 $parent_item = Item::selectFirst($fields, ['uri' => $parent, 'uid' => $uid]);
1448 if (!DBA::isResult($parent_item)) {
1449 $parent_item = Item::selectFirst($fields, ['extid' => $parent, 'uid' => $uid]);
1452 if (DBA::isResult($parent_item)) {
1453 $postarray['thr-parent'] = $parent_item['uri'];
1454 $postarray['parent-uri'] = $parent_item['parent-uri'];
1455 $postarray['parent'] = $parent_item['parent'];
1456 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1458 $postarray['thr-parent'] = $postarray['uri'];
1459 $postarray['parent-uri'] = $postarray['uri'];
1460 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1464 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1466 if ($post->user->id_str == $own_id) {
1467 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1470 if (DBA::isResult($r)) {
1471 $contactid = $r[0]["id"];
1473 $postarray['owner-name'] = $r[0]["name"];
1474 $postarray['owner-link'] = $r[0]["url"];
1475 $postarray['owner-avatar'] = $r[0]["photo"];
1477 Logger::log("No self contact for user " . $uid, Logger::DEBUG);
1481 // Don't create accounts of people who just comment something
1482 $create_user = false;
1484 $postarray['parent-uri'] = $postarray['uri'];
1485 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1488 if ($contactid == 0) {
1489 $contactid = twitter_fetch_contact($uid, $post->user, $create_user);
1491 $postarray['owner-name'] = $post->user->name;
1492 $postarray['owner-link'] = "https://twitter.com/" . $post->user->screen_name;
1493 $postarray['owner-avatar'] = twitter_fix_avatar($post->user->profile_image_url_https);
1496 if (($contactid == 0) && !$only_existing_contact) {
1497 $contactid = $self['id'];
1498 } elseif ($contactid <= 0) {
1499 Logger::log("Contact ID is zero or less than zero.", Logger::DEBUG);
1503 $postarray['contact-id'] = $contactid;
1505 $postarray['verb'] = ACTIVITY_POST;
1506 $postarray['author-name'] = $postarray['owner-name'];
1507 $postarray['author-link'] = $postarray['owner-link'];
1508 $postarray['author-avatar'] = $postarray['owner-avatar'];
1509 $postarray['plink'] = "https://twitter.com/" . $post->user->screen_name . "/status/" . $post->id_str;
1510 $postarray['app'] = strip_tags($post->source);
1512 if ($post->user->protected) {
1513 $postarray['private'] = 1;
1514 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1516 $postarray['private'] = 0;
1517 $postarray['allow_cid'] = '';
1520 if (!empty($post->full_text)) {
1521 $postarray['body'] = $post->full_text;
1523 $postarray['body'] = $post->text;
1526 // When the post contains links then use the correct object type
1527 if (count($post->entities->urls) > 0) {
1528 $postarray['object-type'] = ACTIVITY_OBJ_BOOKMARK;
1531 // Search for media links
1532 $picture = twitter_media_entities($post, $postarray);
1534 $converted = twitter_expand_entities($a, $postarray['body'], $post, $picture);
1535 $postarray['body'] = $converted["body"];
1536 $postarray['tag'] = $converted["tags"];
1537 $postarray['created'] = DateTimeFormat::utc($post->created_at);
1538 $postarray['edited'] = DateTimeFormat::utc($post->created_at);
1540 $statustext = $converted["plain"];
1542 if (!empty($post->place->name)) {
1543 $postarray["location"] = $post->place->name;
1545 if (!empty($post->place->full_name)) {
1546 $postarray["location"] = $post->place->full_name;
1548 if (!empty($post->geo->coordinates)) {
1549 $postarray["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
1551 if (!empty($post->coordinates->coordinates)) {
1552 $postarray["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
1554 if (!empty($post->retweeted_status)) {
1555 $retweet = twitter_createpost($a, $uid, $post->retweeted_status, $self, false, false, $noquote);
1557 if (empty($retweet['body'])) {
1562 // Store the original tweet
1563 Item::insert($retweet);
1565 // CHange the other post into a reshare activity
1566 $postarray['verb'] = ACTIVITY2_ANNOUNCE;
1567 $postarray['gravity'] = GRAVITY_ACTIVITY;
1568 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1570 $postarray['thr-parent'] = $retweet['uri'];
1571 $postarray['parent-uri'] = $retweet['uri'];
1573 $retweet['source'] = $postarray['source'];
1574 $retweet['private'] = $postarray['private'];
1575 $retweet['allow_cid'] = $postarray['allow_cid'];
1576 $retweet['contact-id'] = $postarray['contact-id'];
1577 $retweet['owner-name'] = $postarray['owner-name'];
1578 $retweet['owner-link'] = $postarray['owner-link'];
1579 $retweet['owner-avatar'] = $postarray['owner-avatar'];
1581 $postarray = $retweet;
1585 if (!empty($post->quoted_status) && !$noquote) {
1586 $quoted = twitter_createpost($a, $uid, $post->quoted_status, $self, false, false, true);
1588 if (empty($quoted['body'])) {
1592 $postarray['body'] .= "\n" . share_header(
1593 $quoted['author-name'],
1594 $quoted['author-link'],
1595 $quoted['author-avatar'],
1601 $postarray['body'] .= $quoted['body'] . '[/share]';
1607 function twitter_fetchparentposts(App $a, $uid, $post, TwitterOAuth $connection, array $self)
1609 Logger::log("twitter_fetchparentposts: Fetching for user " . $uid . " and post " . $post->id_str, Logger::DEBUG);
1613 while (!empty($post->in_reply_to_status_id_str)) {
1614 $parameters = ["trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str];
1617 $post = $connection->get('statuses/show', $parameters);
1618 } catch (TwitterOAuthException $e) {
1619 Logger::log('twitter_fetchparentposts: Error fetching for user ' . $uid . ' and post ' . $post->id_str . ': ' . $e->getMessage());
1624 Logger::log("twitter_fetchparentposts: Can't fetch post " . $parameters->id, Logger::DEBUG);
1628 if (empty($post->id_str)) {
1629 Logger::log("twitter_fetchparentposts: This is not a post " . json_encode($post), Logger::DEBUG);
1633 if (Item::exists(['uri' => 'twitter::' . $post->id_str, 'uid' => $uid])) {
1640 Logger::log("twitter_fetchparentposts: Fetching " . count($posts) . " parents", Logger::DEBUG);
1642 $posts = array_reverse($posts);
1644 if (!empty($posts)) {
1645 foreach ($posts as $post) {
1646 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1648 if (empty($postarray['body'])) {
1652 $item = Item::insert($postarray);
1654 $postarray["id"] = $item;
1656 Logger::log('twitter_fetchparentpost: User ' . $self["nick"] . ' posted parent timeline item ' . $item);
1661 function twitter_fetchhometimeline(App $a, $uid)
1663 $ckey = Config::get('twitter', 'consumerkey');
1664 $csecret = Config::get('twitter', 'consumersecret');
1665 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1666 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1667 $create_user = PConfig::get($uid, 'twitter', 'create_user');
1668 $mirror_posts = PConfig::get($uid, 'twitter', 'mirror_posts');
1670 Logger::log("Fetching timeline for user " . $uid, Logger::DEBUG);
1672 $application_name = Config::get('twitter', 'application_name');
1674 if ($application_name == "") {
1675 $application_name = $a->getHostName();
1678 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1681 $own_contact = twitter_fetch_own_contact($a, $uid);
1682 } catch (TwitterOAuthException $e) {
1683 Logger::log('Error fetching own contact for user ' . $uid . ': ' . $e->getMessage());
1687 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1688 intval($own_contact),
1691 if (DBA::isResult($r)) {
1692 $own_id = $r[0]["nick"];
1694 Logger::log("Own twitter contact not found for user " . $uid);
1698 $self = User::getOwnerDataById($uid);
1699 if ($self === false) {
1700 Logger::log("Own contact not found for user " . $uid);
1704 $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
1705 //$parameters["count"] = 200;
1706 // Fetching timeline
1707 $lastid = PConfig::get($uid, 'twitter', 'lasthometimelineid');
1709 $first_time = ($lastid == "");
1711 if ($lastid != "") {
1712 $parameters["since_id"] = $lastid;
1716 $items = $connection->get('statuses/home_timeline', $parameters);
1717 } catch (TwitterOAuthException $e) {
1718 Logger::log('Error fetching home timeline for user ' . $uid . ': ' . $e->getMessage());
1722 if (!is_array($items)) {
1723 Logger::log('No array while fetching home timeline for user ' . $uid . ': ' . print_r($items, true));
1727 if (empty($items)) {
1728 Logger::log('No new timeline content for user ' . $uid, Logger::INFO);
1732 $posts = array_reverse($items);
1734 Logger::log('Fetching timeline from ID ' . $lastid . ' for user ' . $uid . ' ' . sizeof($posts) . ' items', Logger::DEBUG);
1736 if (count($posts)) {
1737 foreach ($posts as $post) {
1738 if ($post->id_str > $lastid) {
1739 $lastid = $post->id_str;
1740 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1747 if (stristr($post->source, $application_name) && $post->user->screen_name == $own_id) {
1748 Logger::log("Skip previously sent post", Logger::DEBUG);
1752 if ($mirror_posts && $post->user->screen_name == $own_id && $post->in_reply_to_status_id_str == "") {
1753 Logger::log("Skip post that will be mirrored", Logger::DEBUG);
1757 if ($post->in_reply_to_status_id_str != "") {
1758 twitter_fetchparentposts($a, $uid, $post, $connection, $self);
1761 Logger::log('Preparing post ' . $post->id_str . ' for user ' . $uid, Logger::DEBUG);
1763 $postarray = twitter_createpost($a, $uid, $post, $self, $create_user, true, false);
1765 if (empty($postarray['body']) || trim($postarray['body']) == "") {
1766 Logger::log('Empty body for post ' . $post->id_str . ' and user ' . $uid, Logger::DEBUG);
1772 if (($postarray['uri'] == $postarray['parent-uri']) && ($postarray['author-link'] == $postarray['owner-link'])) {
1773 $contact = DBA::selectFirst('contact', [], ['id' => $postarray['contact-id'], 'self' => false]);
1774 if (DBA::isResult($contact)) {
1775 $notify = Item::isRemoteSelf($contact, $postarray);
1779 $item = Item::insert($postarray, false, $notify);
1780 $postarray["id"] = $item;
1782 Logger::log('User ' . $uid . ' posted home timeline item ' . $item);
1785 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1787 Logger::log('Last timeline ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
1789 // Fetching mentions
1790 $lastid = PConfig::get($uid, 'twitter', 'lastmentionid');
1792 $first_time = ($lastid == "");
1794 if ($lastid != "") {
1795 $parameters["since_id"] = $lastid;
1799 $items = $connection->get('statuses/mentions_timeline', $parameters);
1800 } catch (TwitterOAuthException $e) {
1801 Logger::log('Error fetching mentions: ' . $e->getMessage());
1805 if (!is_array($items)) {
1806 Logger::log("Error fetching mentions: " . print_r($items, true), Logger::DEBUG);
1810 $posts = array_reverse($items);
1812 Logger::log("Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", Logger::DEBUG);
1814 if (count($posts)) {
1815 foreach ($posts as $post) {
1816 if ($post->id_str > $lastid) {
1817 $lastid = $post->id_str;
1824 if ($post->in_reply_to_status_id_str != "") {
1825 twitter_fetchparentposts($a, $uid, $post, $connection, $self);
1828 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1830 if (empty($postarray['body'])) {
1834 $item = Item::insert($postarray);
1836 Logger::log('User ' . $uid . ' posted mention timeline item ' . $item);
1840 PConfig::set($uid, 'twitter', 'lastmentionid', $lastid);
1842 Logger::log('Last mentions ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
1845 function twitter_fetch_own_contact(App $a, $uid)
1847 $ckey = Config::get('twitter', 'consumerkey');
1848 $csecret = Config::get('twitter', 'consumersecret');
1849 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1850 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1852 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1856 if ($own_id == "") {
1857 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1859 // Fetching user data
1860 // get() may throw TwitterOAuthException, but we will catch it later
1861 $user = $connection->get('account/verify_credentials');
1862 if (empty($user) || empty($user->id_str)) {
1866 PConfig::set($uid, 'twitter', 'own_id', $user->id_str);
1868 $contact_id = twitter_fetch_contact($uid, $user, true);
1870 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1872 DBA::escape("twitter::" . $own_id));
1873 if (DBA::isResult($r)) {
1874 $contact_id = $r[0]["id"];
1876 PConfig::delete($uid, 'twitter', 'own_id');
1883 function twitter_is_retweet(App $a, $uid, $body)
1885 $body = trim($body);
1887 // Skip if it isn't a pure repeated messages
1888 // Does it start with a share?
1889 if (strpos($body, "[share") > 0) {
1893 // Does it end with a share?
1894 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1898 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1899 // Skip if there is no shared message in there
1900 if ($body == $attributes) {
1905 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1906 if (!empty($matches[1])) {
1907 $link = $matches[1];
1910 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1911 if (!empty($matches[1])) {
1912 $link = $matches[1];
1915 $id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link);
1920 Logger::log('twitter_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, Logger::DEBUG);
1922 $ckey = Config::get('twitter', 'consumerkey');
1923 $csecret = Config::get('twitter', 'consumersecret');
1924 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1925 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1927 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1928 $result = $connection->post('statuses/retweet/' . $id);
1930 Logger::log('twitter_is_retweet: result ' . print_r($result, true), Logger::DEBUG);
1932 return !isset($result->errors);
1935 function twitter_update_mentions($body)
1937 $URLSearchString = "^\[\]";
1938 $return = preg_replace_callback(
1939 "/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1940 function ($matches) {
1941 if (strpos($matches[1], 'twitter.com')) {
1942 $return = '@' . substr($matches[1], strrpos($matches[1], '/') + 1);
1944 $return = $matches[2] . ' (' . $matches[1] . ')';
1955 function twitter_convert_share(array $attributes, array $author_contact, $content, $is_quote_share)
1957 if ($author_contact['network'] == Protocol::TWITTER) {
1958 $mention = '@' . $author_contact['nickname'];
1960 $mention = $author_contact['addr'];
1963 return ($is_quote_share ? "\n\n" : '' ) . 'RT ' . $mention . ': ' . $content . "\n\n" . $attributes['link'];