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\Group;
83 use Friendica\Model\Item;
84 use Friendica\Model\ItemContent;
85 use Friendica\Model\User;
86 use Friendica\Object\Image;
87 use Friendica\Util\Config\ConfigFileLoader;
88 use Friendica\Util\DateTimeFormat;
89 use Friendica\Util\Network;
90 use Friendica\Util\Strings;
92 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
94 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
96 function twitter_install()
98 // we need some hooks, for the configuration and for sending tweets
99 Hook::register('load_config' , __FILE__, 'twitter_load_config');
100 Hook::register('connector_settings' , __FILE__, 'twitter_settings');
101 Hook::register('connector_settings_post', __FILE__, 'twitter_settings_post');
102 Hook::register('hook_fork' , __FILE__, 'twitter_hook_fork');
103 Hook::register('post_local' , __FILE__, 'twitter_post_local');
104 Hook::register('notifier_normal' , __FILE__, 'twitter_post_hook');
105 Hook::register('jot_networks' , __FILE__, 'twitter_jot_nets');
106 Hook::register('cron' , __FILE__, 'twitter_cron');
107 Hook::register('follow' , __FILE__, 'twitter_follow');
108 Hook::register('expire' , __FILE__, 'twitter_expire');
109 Hook::register('prepare_body' , __FILE__, 'twitter_prepare_body');
110 Hook::register('check_item_notification', __FILE__, 'twitter_check_item_notification');
111 Logger::log("installed twitter");
114 function twitter_uninstall()
116 Hook::unregister('load_config' , __FILE__, 'twitter_load_config');
117 Hook::unregister('connector_settings' , __FILE__, 'twitter_settings');
118 Hook::unregister('connector_settings_post', __FILE__, 'twitter_settings_post');
119 Hook::unregister('hook_fork' , __FILE__, 'twitter_hook_fork');
120 Hook::unregister('post_local' , __FILE__, 'twitter_post_local');
121 Hook::unregister('notifier_normal' , __FILE__, 'twitter_post_hook');
122 Hook::unregister('jot_networks' , __FILE__, 'twitter_jot_nets');
123 Hook::unregister('cron' , __FILE__, 'twitter_cron');
124 Hook::unregister('follow' , __FILE__, 'twitter_follow');
125 Hook::unregister('expire' , __FILE__, 'twitter_expire');
126 Hook::unregister('prepare_body' , __FILE__, 'twitter_prepare_body');
127 Hook::unregister('check_item_notification', __FILE__, 'twitter_check_item_notification');
129 // old setting - remove only
130 Hook::unregister('post_local_end' , __FILE__, 'twitter_post_hook');
131 Hook::unregister('addon_settings' , __FILE__, 'twitter_settings');
132 Hook::unregister('addon_settings_post', __FILE__, 'twitter_settings_post');
135 function twitter_load_config(App $a, ConfigFileLoader $loader)
137 $a->getConfigCache()->load($loader->loadAddonConfig('twitter'));
140 function twitter_check_item_notification(App $a, array &$notification_data)
142 $own_id = PConfig::get($notification_data["uid"], 'twitter', 'own_id');
144 $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
145 intval($notification_data["uid"]),
146 DBA::escape("twitter::".$own_id)
150 $notification_data["profiles"][] = $own_user[0]["url"];
154 function twitter_follow(App $a, array &$contact)
156 Logger::log("twitter_follow: Check if contact is twitter contact. " . $contact["url"], Logger::DEBUG);
158 if (!strstr($contact["url"], "://twitter.com") && !strstr($contact["url"], "@twitter.com")) {
162 // contact seems to be a twitter contact, so continue
163 $nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $contact["url"]);
164 $nickname = str_replace("@twitter.com", "", $nickname);
166 $uid = $a->user["uid"];
168 $ckey = Config::get('twitter', 'consumerkey');
169 $csecret = Config::get('twitter', 'consumersecret');
170 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
171 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
173 // If the addon is not configured (general or for this user) quit here
174 if (empty($ckey) || empty($csecret) || empty($otoken) || empty($osecret)) {
179 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
180 $connection->post('friendships/create', ['screen_name' => $nickname]);
182 twitter_fetchuser($a, $uid, $nickname);
184 $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
185 FROM `contact` WHERE `uid` = %d AND `nick` = '%s'",
187 DBA::escape($nickname));
188 if (DBA::isResult($r)) {
189 $contact["contact"] = $r[0];
193 function twitter_jot_nets(App $a, array &$jotnets_fields)
199 if (PConfig::get(local_user(), 'twitter', 'post')) {
200 $jotnets_fields[] = [
201 'type' => 'checkbox',
204 L10n::t('Post to Twitter'),
205 PConfig::get(local_user(), 'twitter', 'post_by_default')
212 function twitter_settings_post(App $a)
217 // don't check twitter settings if twitter submit button is not clicked
218 if (empty($_POST['twitter-disconnect']) && empty($_POST['twitter-submit'])) {
222 if (!empty($_POST['twitter-disconnect'])) {
224 * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
225 * from the user configuration
227 PConfig::delete(local_user(), 'twitter', 'consumerkey');
228 PConfig::delete(local_user(), 'twitter', 'consumersecret');
229 PConfig::delete(local_user(), 'twitter', 'oauthtoken');
230 PConfig::delete(local_user(), 'twitter', 'oauthsecret');
231 PConfig::delete(local_user(), 'twitter', 'post');
232 PConfig::delete(local_user(), 'twitter', 'post_by_default');
233 PConfig::delete(local_user(), 'twitter', 'lastid');
234 PConfig::delete(local_user(), 'twitter', 'mirror_posts');
235 PConfig::delete(local_user(), 'twitter', 'import');
236 PConfig::delete(local_user(), 'twitter', 'create_user');
237 PConfig::delete(local_user(), 'twitter', 'own_id');
239 if (isset($_POST['twitter-pin'])) {
240 // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
241 Logger::log('got a Twitter PIN');
242 $ckey = Config::get('twitter', 'consumerkey');
243 $csecret = Config::get('twitter', 'consumersecret');
244 // the token and secret for which the PIN was generated were hidden in the settings
245 // form as token and token2, we need a new connection to Twitter using these token
246 // and secret to request a Access Token with the PIN
248 if (empty($_POST['twitter-pin'])) {
249 throw new Exception(L10n::t('You submitted an empty PIN, please Sign In with Twitter again to get a new one.'));
252 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
253 $token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_POST['twitter-pin']]);
254 // ok, now that we have the Access Token, save them in the user config
255 PConfig::set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
256 PConfig::set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
257 PConfig::set(local_user(), 'twitter', 'post', 1);
258 } catch(Exception $e) {
259 info($e->getMessage());
260 } catch(TwitterOAuthException $e) {
261 info($e->getMessage());
263 // reload the Addon Settings page, if we don't do it see Bug #42
264 $a->internalRedirect('settings/connectors');
266 // if no PIN is supplied in the POST variables, the user has changed the setting
267 // to post a tweet for every new __public__ posting to the wall
268 PConfig::set(local_user(), 'twitter', 'post', intval($_POST['twitter-enable']));
269 PConfig::set(local_user(), 'twitter', 'post_by_default', intval($_POST['twitter-default']));
270 PConfig::set(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror']));
271 PConfig::set(local_user(), 'twitter', 'import', intval($_POST['twitter-import']));
272 PConfig::set(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user']));
274 if (!intval($_POST['twitter-mirror'])) {
275 PConfig::delete(local_user(), 'twitter', 'lastid');
278 info(L10n::t('Twitter settings updated.') . EOL);
283 function twitter_settings(App $a, &$s)
288 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->getBaseURL() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
290 * 1) Check that we have global consumer key & secret
291 * 2) If no OAuthtoken & stuff is present, generate button to get some
292 * 3) Checkbox for "Send public notices (280 chars only)
294 $ckey = Config::get('twitter', 'consumerkey');
295 $csecret = Config::get('twitter', 'consumersecret');
296 $otoken = PConfig::get(local_user(), 'twitter', 'oauthtoken');
297 $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret');
299 $enabled = intval(PConfig::get(local_user(), 'twitter', 'post'));
300 $defenabled = intval(PConfig::get(local_user(), 'twitter', 'post_by_default'));
301 $mirrorenabled = intval(PConfig::get(local_user(), 'twitter', 'mirror_posts'));
302 $importenabled = intval(PConfig::get(local_user(), 'twitter', 'import'));
303 $create_userenabled = intval(PConfig::get(local_user(), 'twitter', 'create_user'));
305 $css = (($enabled) ? '' : '-disabled');
307 $s .= '<span id="settings_twitter_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
308 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
310 $s .= '<div id="settings_twitter_expanded" class="settings-block" style="display: none;">';
311 $s .= '<span class="fakelink" 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>';
315 if ((!$ckey) && (!$csecret)) {
316 /* no global consumer keys
317 * display warning and skip personal config
319 $s .= '<p>' . L10n::t('No consumer key pair for Twitter found. Please contact your site administrator.') . '</p>';
321 // ok we have a consumer key pair now look into the OAuth stuff
322 if ((!$otoken) && (!$osecret)) {
323 /* the user has not yet connected the account to twitter...
324 * get a temporary OAuth key/secret pair and display a button with
325 * which the user can request a PIN to connect the account to a
326 * account at Twitter.
328 $connection = new TwitterOAuth($ckey, $csecret);
330 $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
331 $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>';
332 $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>';
333 $s .= '<div id="twitter-pin-wrapper">';
334 $s .= '<label id="twitter-pin-label" for="twitter-pin">' . L10n::t('Copy the PIN from Twitter here') . '</label>';
335 $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
336 $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result['oauth_token'] . '" />';
337 $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result['oauth_token_secret'] . '" />';
338 $s .= '</div><div class="clear"></div>';
339 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
340 } catch (TwitterOAuthException $e) {
341 $s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
345 * we have an OAuth key / secret pair for the user
346 * so let's give a chance to disable the postings to Twitter
348 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
350 $details = $connection->get('account/verify_credentials');
352 $field_checkbox = Renderer::getMarkupTemplate('field_checkbox.tpl');
354 $s .= '<div id="twitter-info" >
355 <p>' . L10n::t('Currently connected to: ') . '<a href="https://twitter.com/' . $details->screen_name . '" target="_twitter">' . $details->screen_name . '</a>
356 <button type="submit" name="twitter-disconnect" value="1">' . L10n::t('Disconnect') . '</button>
358 <p id="twitter-info-block">
359 <a href="https://twitter.com/' . $details->screen_name . '" target="_twitter"><img id="twitter-avatar" src="' . $details->profile_image_url . '" /></a>
360 <em>' . $details->description . '</em>
363 $s .= '<div class="clear"></div>';
365 $s .= Renderer::replaceMacros($field_checkbox, [
366 '$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.')]
368 if ($a->user['hidewall']) {
369 $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>';
371 $s .= Renderer::replaceMacros($field_checkbox, [
372 '$field' => ['twitter-default', L10n::t('Send public postings to Twitter by default'), $defenabled, '']
374 $s .= Renderer::replaceMacros($field_checkbox, [
375 '$field' => ['twitter-mirror', L10n::t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '']
377 $s .= Renderer::replaceMacros($field_checkbox, [
378 '$field' => ['twitter-import', L10n::t('Import the remote timeline'), $importenabled, '']
380 $s .= Renderer::replaceMacros($field_checkbox, [
381 '$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.')]
383 $s .= '<div class="clear"></div>';
384 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
385 } catch (TwitterOAuthException $e) {
386 $s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
390 $s .= '</div><div class="clear"></div>';
393 function twitter_hook_fork(App $a, array &$b)
395 if ($b['name'] != 'notifier_normal') {
401 // Deleting and editing is not supported by the addon (deleting could, but isn't by now)
402 if ($post['deleted'] || ($post['created'] !== $post['edited'])) {
403 $b['execute'] = false;
407 // if post comes from twitter don't send it back
408 if ($post['extid'] == Protocol::TWITTER) {
409 $b['execute'] = false;
413 if ($post['app'] == 'Twitter') {
414 $b['execute'] = false;
418 if (PConfig::get($post['uid'], 'twitter', 'import')) {
419 // Don't fork if it isn't a reply to a twitter post
420 if (($post['parent'] != $post['id']) && !Item::exists(['id' => $post['parent'], 'network' => Protocol::TWITTER])) {
421 Logger::log('No twitter parent found for item ' . $post['id']);
422 $b['execute'] = false;
426 // Comments are never exported when we don't import the twitter timeline
427 if (!strstr($post['postopts'], 'twitter') || ($post['parent'] != $post['id']) || $post['private']) {
428 $b['execute'] = false;
434 function twitter_post_local(App $a, array &$b)
440 if (!local_user() || (local_user() != $b['uid'])) {
444 $twitter_post = intval(PConfig::get(local_user(), 'twitter', 'post'));
445 $twitter_enable = (($twitter_post && !empty($_REQUEST['twitter_enable'])) ? intval($_REQUEST['twitter_enable']) : 0);
447 // if API is used, default to the chosen settings
448 if ($b['api_source'] && intval(PConfig::get(local_user(), 'twitter', 'post_by_default'))) {
452 if (!$twitter_enable) {
456 if (strlen($b['postopts'])) {
457 $b['postopts'] .= ',';
460 $b['postopts'] .= 'twitter';
463 function twitter_action(App $a, $uid, $pid, $action)
465 $ckey = Config::get('twitter', 'consumerkey');
466 $csecret = Config::get('twitter', 'consumersecret');
467 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
468 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
470 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
472 $post = ['id' => $pid];
474 Logger::log("twitter_action '" . $action . "' ID: " . $pid . " data: " . print_r($post, true), Logger::DATA);
478 // To-Do: $result = $connection->post('statuses/destroy', $post);
482 $result = $connection->post('favorites/create', $post);
485 $result = $connection->post('favorites/destroy', $post);
488 Logger::log('Unhandled action ' . $action, Logger::DEBUG);
491 Logger::log("twitter_action '" . $action . "' send, result: " . print_r($result, true), Logger::DEBUG);
494 function twitter_post_hook(App $a, array &$b)
497 if (!PConfig::get($b["uid"], 'twitter', 'import')
498 && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
502 if ($b['parent'] != $b['id']) {
503 Logger::log("twitter_post_hook: parameter " . print_r($b, true), Logger::DATA);
505 // Looking if its a reply to a twitter post
506 if ((substr($b["parent-uri"], 0, 9) != "twitter::")
507 && (substr($b["extid"], 0, 9) != "twitter::")
508 && (substr($b["thr-parent"], 0, 9) != "twitter::"))
510 Logger::log("twitter_post_hook: no twitter post " . $b["parent"]);
514 $condition = ['uri' => $b["thr-parent"], 'uid' => $b["uid"]];
515 $orig_post = Item::selectFirst([], $condition);
516 if (!DBA::isResult($orig_post)) {
517 Logger::log("twitter_post_hook: no parent found " . $b["thr-parent"]);
524 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
525 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
526 $nicknameplain = "@" . $nicknameplain;
528 Logger::log("twitter_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], Logger::DEBUG);
529 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
530 $b["body"] = $nickname . " " . $b["body"];
533 Logger::log("twitter_post_hook: parent found " . print_r($orig_post, true), Logger::DATA);
537 if ($b['private'] || !strstr($b['postopts'], 'twitter')) {
541 // Dont't post if the post doesn't belong to us.
542 // This is a check for forum postings
543 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
544 if ($b['contact-id'] != $self['id']) {
549 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
550 twitter_action($a, $b["uid"], substr($orig_post["uri"], 9), "delete");
553 if ($b['verb'] == ACTIVITY_LIKE) {
554 Logger::log("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), Logger::DEBUG);
556 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike");
558 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "like");
564 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
568 // if post comes from twitter don't send it back
569 if ($b['extid'] == Protocol::TWITTER) {
573 if ($b['app'] == "Twitter") {
577 Logger::notice('twitter post invoked', ['id' => $b['id'], 'guid' => $b['guid']]);
579 PConfig::load($b['uid'], 'twitter');
581 $ckey = Config::get('twitter', 'consumerkey');
582 $csecret = Config::get('twitter', 'consumersecret');
583 $otoken = PConfig::get($b['uid'], 'twitter', 'oauthtoken');
584 $osecret = PConfig::get($b['uid'], 'twitter', 'oauthsecret');
586 if ($ckey && $csecret && $otoken && $osecret) {
587 Logger::log('twitter: we have customer key and oauth stuff, going to send.', Logger::DEBUG);
589 // If it's a repeated message from twitter then do a native retweet and exit
590 if (twitter_is_retweet($a, $b['uid'], $b['body'])) {
594 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
596 // Set the timeout for upload to 30 seconds
597 $connection->setTimeouts(10, 30);
601 // Handling non-native reshares
602 $b['body'] = Friendica\Content\Text\BBCode::convertShare(
604 function (array $attributes, array $author_contact, $content, $is_quote_share) {
605 return twitter_convert_share($attributes, $author_contact, $content, $is_quote_share);
609 $b['body'] = twitter_update_mentions($b['body']);
611 $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 8);
612 Logger::info('Got plaintext', $msgarr);
613 $msg = $msgarr["text"];
615 if (($msg == "") && isset($msgarr["title"])) {
616 $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
621 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
622 $msg .= "\n" . $msgarr["url"];
628 if (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
629 $image = $msgarr["image"];
636 // and now tweet it :-)
639 if (!empty($image)) {
641 $img_str = Network::fetchUrl($image);
643 $tempfile = tempnam(get_temppath(), 'cache');
644 file_put_contents($tempfile, $img_str);
646 $media = $connection->upload('media/upload', ['media' => $tempfile]);
650 if (isset($media->media_id_string)) {
651 $post['media_ids'] = $media->media_id_string;
653 throw new Exception('Failed upload of ' . $image);
655 } catch (Exception $e) {
656 Logger::log('Exception when trying to send to Twitter: ' . $e->getMessage());
658 // Workaround: Remove the picture link so that the post can be reposted without it
659 // When there is another url already added, a second url would be superfluous.
661 $msg .= "\n" . $image;
668 $post['status'] = $msg;
671 $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
674 $url = 'statuses/update';
675 $result = $connection->post($url, $post);
676 Logger::log('twitter_post send, result: ' . print_r($result, true), Logger::DEBUG);
678 if (!empty($result->source)) {
679 Config::set("twitter", "application_name", strip_tags($result->source));
682 if (!empty($result->errors)) {
683 Logger::log('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
685 } elseif ($iscomment) {
686 Logger::log('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']);
687 Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]);
692 function twitter_addon_admin_post(App $a)
694 $consumerkey = !empty($_POST['consumerkey']) ? Strings::escapeTags(trim($_POST['consumerkey'])) : '';
695 $consumersecret = !empty($_POST['consumersecret']) ? Strings::escapeTags(trim($_POST['consumersecret'])) : '';
696 Config::set('twitter', 'consumerkey', $consumerkey);
697 Config::set('twitter', 'consumersecret', $consumersecret);
698 info(L10n::t('Settings updated.') . EOL);
701 function twitter_addon_admin(App $a, &$o)
703 $t = Renderer::getMarkupTemplate("admin.tpl", "addon/twitter/");
705 $o = Renderer::replaceMacros($t, [
706 '$submit' => L10n::t('Save Settings'),
707 // name, label, value, help, [extra values]
708 '$consumerkey' => ['consumerkey', L10n::t('Consumer key'), Config::get('twitter', 'consumerkey'), ''],
709 '$consumersecret' => ['consumersecret', L10n::t('Consumer secret'), Config::get('twitter', 'consumersecret'), ''],
713 function twitter_cron(App $a)
715 $last = Config::get('twitter', 'last_poll');
717 $poll_interval = intval(Config::get('twitter', 'poll_interval'));
718 if (!$poll_interval) {
719 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
723 $next = $last + ($poll_interval * 60);
724 if ($next > time()) {
725 Logger::log('twitter: poll intervall not reached');
729 Logger::log('twitter: cron_start');
731 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1'");
732 if (DBA::isResult($r)) {
733 foreach ($r as $rr) {
734 Logger::log('twitter: fetching for user ' . $rr['uid']);
735 Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], "addon/twitter/twitter_sync.php", 1, (int) $rr['uid']);
739 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
740 if ($abandon_days < 1) {
744 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
746 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1'");
747 if (DBA::isResult($r)) {
748 foreach ($r as $rr) {
749 if ($abandon_days != 0) {
750 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
751 if (!DBA::isResult($user)) {
752 Logger::log('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
757 Logger::log('twitter: importing timeline from user ' . $rr['uid']);
758 Worker::add(['priority' => PRIORITY_MEDIUM, 'force_priority' => true], "addon/twitter/twitter_sync.php", 2, (int) $rr['uid']);
761 // check for new contacts once a day
762 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
763 if($last_contact_check)
764 $next_contact_check = $last_contact_check + 86400;
766 $next_contact_check = 0;
768 if($next_contact_check <= time()) {
769 pumpio_getallusers($a, $rr["uid"]);
770 PConfig::set($rr['uid'],'pumpio','contact_check',time());
776 Logger::log('twitter: cron_end');
778 Config::set('twitter', 'last_poll', time());
781 function twitter_expire(App $a)
783 $days = Config::get('twitter', 'expire');
789 $r = Item::select(['id'], ['deleted' => true, 'network' => Protocol::TWITTER]);
790 while ($row = DBA::fetch($r)) {
791 DBA::delete('item', ['id' => $row['id']]);
795 Logger::log('twitter_expire: expire_start');
797 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
798 if (DBA::isResult($r)) {
799 foreach ($r as $rr) {
800 Logger::log('twitter_expire: user ' . $rr['uid']);
801 Item::expire($rr['uid'], $days, Protocol::TWITTER, true);
805 Logger::log('twitter_expire: expire_end');
808 function twitter_prepare_body(App $a, array &$b)
810 if ($b["item"]["network"] != Protocol::TWITTER) {
817 $item["plink"] = $a->getBaseURL() . "/display/" . $item["guid"];
819 $condition = ['uri' => $item["thr-parent"], 'uid' => local_user()];
820 $orig_post = Item::selectFirst(['author-link'], $condition);
821 if (DBA::isResult($orig_post)) {
822 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
823 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
824 $nicknameplain = "@" . $nicknameplain;
826 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
827 $item["body"] = $nickname . " " . $item["body"];
831 $msgarr = ItemContent::getPlaintextPost($item, $max_char, true, 8);
832 $msg = $msgarr["text"];
834 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
835 $msg .= " " . $msgarr["url"];
838 if (isset($msgarr["image"])) {
839 $msg .= " " . $msgarr["image"];
842 $b['html'] = nl2br(htmlspecialchars($msg));
847 * @brief Build the item array for the mirrored post
849 * @param App $a Application class
850 * @param integer $uid User id
851 * @param object $post Twitter object with the post
853 * @return array item data to be posted
855 function twitter_do_mirrorpost(App $a, $uid, $post)
857 $datarray['api_source'] = true;
858 $datarray['profile_uid'] = $uid;
859 $datarray['extid'] = Protocol::TWITTER;
860 $datarray['message_id'] = Item::newURI($uid, Protocol::TWITTER . ':' . $post->id);
861 $datarray['protocol'] = Conversation::PARCEL_TWITTER;
862 $datarray['source'] = json_encode($post);
863 $datarray['title'] = '';
865 if (!empty($post->retweeted_status)) {
866 // We don't support nested shares, so we mustn't show quotes as shares on retweets
867 $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true);
869 if (empty($item['body'])) {
873 $datarray['body'] = "\n" . share_header(
874 $item['author-name'],
875 $item['author-link'],
876 $item['author-avatar'],
882 $datarray['body'] .= $item['body'] . '[/share]';
884 $item = twitter_createpost($a, $uid, $post, ['id' => 0], false, false, false);
886 if (empty($item['body'])) {
890 $datarray['body'] = $item['body'];
893 $datarray['source'] = $item['app'];
894 $datarray['verb'] = $item['verb'];
896 if (isset($item['location'])) {
897 $datarray['location'] = $item['location'];
900 if (isset($item['coord'])) {
901 $datarray['coord'] = $item['coord'];
907 function twitter_fetchtimeline(App $a, $uid)
909 $ckey = Config::get('twitter', 'consumerkey');
910 $csecret = Config::get('twitter', 'consumersecret');
911 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
912 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
913 $lastid = PConfig::get($uid, 'twitter', 'lastid');
915 $application_name = Config::get('twitter', 'application_name');
917 if ($application_name == "") {
918 $application_name = $a->getHostName();
921 $has_picture = false;
923 require_once 'mod/item.php';
924 require_once 'mod/share.php';
926 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
928 $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
930 $first_time = ($lastid == "");
933 $parameters["since_id"] = $lastid;
937 $items = $connection->get('statuses/user_timeline', $parameters);
938 } catch (TwitterOAuthException $e) {
939 Logger::log('Error fetching timeline for user ' . $uid . ': ' . $e->getMessage());
943 if (!is_array($items)) {
944 Logger::log('No items for user ' . $uid, Logger::INFO);
948 $posts = array_reverse($items);
950 Logger::log('Starting from ID ' . $lastid . ' for user ' . $uid, Logger::DEBUG);
953 foreach ($posts as $post) {
954 if ($post->id_str > $lastid) {
955 $lastid = $post->id_str;
956 PConfig::set($uid, 'twitter', 'lastid', $lastid);
963 if (!stristr($post->source, $application_name)) {
964 $_SESSION["authenticated"] = true;
965 $_SESSION["uid"] = $uid;
967 Logger::log('Preparing Twitter ID ' . $post->id_str . ' for user ' . $uid, Logger::DEBUG);
969 $_REQUEST = twitter_do_mirrorpost($a, $uid, $post);
971 if (empty($_REQUEST['body'])) {
975 Logger::log('Posting Twitter ID ' . $post->id_str . ' for user ' . $uid);
981 PConfig::set($uid, 'twitter', 'lastid', $lastid);
982 Logger::log('Last ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
985 function twitter_fix_avatar($avatar)
987 $new_avatar = str_replace("_normal.", ".", $avatar);
989 $info = Image::getInfoFromURL($new_avatar);
991 $new_avatar = $avatar;
997 function twitter_fetch_contact($uid, $data, $create_user)
999 if (empty($data->id_str)) {
1003 $avatar = twitter_fix_avatar($data->profile_image_url_https);
1004 $url = "https://twitter.com/" . $data->screen_name;
1005 $addr = $data->screen_name . "@twitter.com";
1007 $fields = ['url' => $url, 'network' => Protocol::TWITTER,
1008 'name' => $data->name, 'nick' => $data->screen_name, 'addr' => $addr,
1009 'location' => $data->location, 'about' => $data->description];
1011 $cid = Contact::getIdForURL($url, 0, true, $fields);
1013 DBA::update('contact', $fields, ['id' => $cid]);
1014 Contact::updateAvatar($avatar, 0, $cid);
1017 $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'alias' => "twitter::" . $data->id_str]);
1018 if (!DBA::isResult($contact) && !$create_user) {
1022 if (!DBA::isResult($contact)) {
1023 // create contact record
1024 $fields['uid'] = $uid;
1025 $fields['created'] = DateTimeFormat::utcNow();
1026 $fields['nurl'] = Strings::normaliseLink($url);
1027 $fields['alias'] = 'twitter::' . $data->id_str;
1028 $fields['poll'] = 'twitter::' . $data->id_str;
1029 $fields['rel'] = Contact::FRIEND;
1030 $fields['priority'] = 1;
1031 $fields['writable'] = true;
1032 $fields['blocked'] = false;
1033 $fields['readonly'] = false;
1034 $fields['pending'] = false;
1036 if (!DBA::insert('contact', $fields)) {
1040 $contact_id = DBA::lastInsertId();
1042 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1044 Contact::updateAvatar($avatar, $uid, $contact_id);
1046 if ($contact["readonly"] || $contact["blocked"]) {
1047 Logger::log("twitter_fetch_contact: Contact '" . $contact["nick"] . "' is blocked or readonly.", Logger::DEBUG);
1051 $contact_id = $contact['id'];
1053 // update profile photos once every twelve hours as we have no notification of when they change.
1054 $update_photo = ($contact['avatar-date'] < DateTimeFormat::utc('now -12 hours'));
1056 // check that we have all the photos, this has been known to fail on occasion
1057 if (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']) || $update_photo) {
1058 Logger::log("twitter_fetch_contact: Updating contact " . $data->screen_name, Logger::DEBUG);
1060 Contact::updateAvatar($avatar, $uid, $contact['id']);
1062 $fields['name-date'] = DateTimeFormat::utcNow();
1063 $fields['uri-date'] = DateTimeFormat::utcNow();
1065 DBA::update('contact', $fields, ['id' => $contact['id']]);
1072 function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1074 $ckey = Config::get('twitter', 'consumerkey');
1075 $csecret = Config::get('twitter', 'consumersecret');
1076 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1077 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1079 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1082 if (DBA::isResult($r)) {
1090 if ($screen_name != "") {
1091 $parameters["screen_name"] = $screen_name;
1094 if ($user_id != "") {
1095 $parameters["user_id"] = $user_id;
1098 // Fetching user data
1099 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1101 $user = $connection->get('users/show', $parameters);
1102 } catch (TwitterOAuthException $e) {
1103 Logger::log('twitter_fetchuser: Error fetching user ' . $uid . ': ' . $e->getMessage());
1107 if (!is_object($user)) {
1111 $contact_id = twitter_fetch_contact($uid, $user, true);
1116 function twitter_expand_entities(App $a, $body, $item, $picture)
1122 foreach ($item->entities->hashtags AS $hashtag) {
1123 $url = '#[url=' . $a->getBaseURL() . '/search?tag=' . $hashtag->text . ']' . $hashtag->text . '[/url]';
1124 $tags_arr['#' . $hashtag->text] = $url;
1125 $body = str_replace('#' . $hashtag->text, $url, $body);
1128 foreach ($item->entities->user_mentions AS $mention) {
1129 $url = '@[url=https://twitter.com/' . rawurlencode($mention->screen_name) . ']' . $mention->screen_name . '[/url]';
1130 $tags_arr['@' . $mention->screen_name] = $url;
1131 $body = str_replace('@' . $mention->screen_name, $url, $body);
1134 if (isset($item->entities->urls)) {
1140 foreach ($item->entities->urls as $url) {
1141 $plain = str_replace($url->url, '', $plain);
1143 if ($url->url && $url->expanded_url && $url->display_url) {
1144 // Quote tweet, we just remove the quoted tweet URL from the body, the share block will be added later.
1145 if (isset($item->quoted_status_id_str)
1146 && substr($url->expanded_url, -strlen($item->quoted_status_id_str)) == $item->quoted_status_id_str ) {
1147 $body = str_replace($url->url, '', $body);
1151 $expanded_url = $url->expanded_url;
1153 $final_url = Network::finalUrl($url->expanded_url);
1155 $oembed_data = OEmbed::fetchURL($final_url);
1157 if (empty($oembed_data) || empty($oembed_data->type)) {
1161 // Quickfix: Workaround for URL with '[' and ']' in it
1162 if (strpos($expanded_url, '[') || strpos($expanded_url, ']')) {
1163 $expanded_url = $url->url;
1167 $type = $oembed_data->type;
1170 if ($oembed_data->type == 'video') {
1171 $type = $oembed_data->type;
1172 $footerurl = $expanded_url;
1173 $footerlink = '[url=' . $expanded_url . ']' . $url->display_url . '[/url]';
1175 $body = str_replace($url->url, $footerlink, $body);
1176 } elseif (($oembed_data->type == 'photo') && isset($oembed_data->url)) {
1177 $body = str_replace($url->url, '[url=' . $expanded_url . '][img]' . $oembed_data->url . '[/img][/url]', $body);
1178 } elseif ($oembed_data->type != 'link') {
1179 $body = str_replace($url->url, '[url=' . $expanded_url . ']' . $url->display_url . '[/url]', $body);
1181 $img_str = Network::fetchUrl($final_url, true, 4);
1183 $tempfile = tempnam(get_temppath(), 'cache');
1184 file_put_contents($tempfile, $img_str);
1186 // See http://php.net/manual/en/function.exif-imagetype.php#79283
1187 if (filesize($tempfile) > 11) {
1188 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1195 if (substr($mime, 0, 6) == 'image/') {
1197 $body = str_replace($url->url, '[img]' . $final_url . '[/img]', $body);
1199 $type = $oembed_data->type;
1200 $footerurl = $expanded_url;
1201 $footerlink = '[url=' . $expanded_url . ']' . $url->display_url . '[/url]';
1203 $body = str_replace($url->url, $footerlink, $body);
1209 // Footer will be taken care of with a share block in the case of a quote
1210 if (empty($item->quoted_status)) {
1211 if ($footerurl != '') {
1212 $footer = add_page_info($footerurl, false, $picture);
1215 if (($footerlink != '') && (trim($footer) != '')) {
1216 $removedlink = trim(str_replace($footerlink, '', $body));
1218 if (($removedlink == '') || strstr($body, $removedlink)) {
1219 $body = $removedlink;
1225 if ($footer == '' && $picture != '') {
1226 $body .= "\n\n[img]" . $picture . "[/img]\n";
1227 } elseif ($footer == '' && $picture == '') {
1228 $body = add_page_info_to_body($body);
1233 // it seems as if the entities aren't always covering all mentions. So the rest will be checked here
1234 $tags = BBCode::getTags($body);
1237 foreach ($tags as $tag) {
1238 if (strstr(trim($tag), ' ')) {
1242 if (strpos($tag, '#') === 0) {
1243 if (strpos($tag, '[url=')) {
1247 // don't link tags that are already embedded in links
1248 if (preg_match('/\[(.*?)' . preg_quote($tag, '/') . '(.*?)\]/', $body)) {
1251 if (preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag, '/') . '(.*?)\)/', $body)) {
1255 $basetag = str_replace('_', ' ', substr($tag, 1));
1256 $url = '#[url=' . $a->getBaseURL() . '/search?tag=' . $basetag . ']' . $basetag . '[/url]';
1257 $body = str_replace($tag, $url, $body);
1258 $tags_arr['#' . $basetag] = $url;
1259 } elseif (strpos($tag, '@') === 0) {
1260 if (strpos($tag, '[url=')) {
1264 $basetag = substr($tag, 1);
1265 $url = '@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1266 $body = str_replace($tag, $url, $body);
1267 $tags_arr['@' . $basetag] = $url;
1272 $tags = implode($tags_arr, ',');
1274 return ['body' => $body, 'tags' => $tags, 'plain' => $plain];
1278 * @brief Fetch media entities and add media links to the body
1280 * @param object $post Twitter object with the post
1281 * @param array $postarray Array of the item that is about to be posted
1283 * @return $picture string Image URL or empty string
1285 function twitter_media_entities($post, array &$postarray)
1287 // There are no media entities? So we quit.
1288 if (empty($post->extended_entities->media)) {
1292 // When the post links to an external page, we only take one picture.
1293 // We only do this when there is exactly one media.
1294 if ((count($post->entities->urls) > 0) && (count($post->extended_entities->media) == 1)) {
1295 $medium = $post->extended_entities->media[0];
1297 foreach ($post->entities->urls as $link) {
1298 // Let's make sure the external link url matches the media url
1299 if ($medium->url == $link->url && isset($medium->media_url_https)) {
1300 $picture = $medium->media_url_https;
1301 $postarray['body'] = str_replace($medium->url, '', $postarray['body']);
1307 // This is a pure media post, first search for all media urls
1309 foreach ($post->extended_entities->media AS $medium) {
1310 if (!isset($media[$medium->url])) {
1311 $media[$medium->url] = '';
1313 switch ($medium->type) {
1315 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
1316 $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
1319 case 'animated_gif':
1320 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . '[/img]';
1321 $postarray['object-type'] = ACTIVITY_OBJ_VIDEO;
1322 if (is_array($medium->video_info->variants)) {
1324 // We take the video with the highest bitrate
1325 foreach ($medium->video_info->variants AS $variant) {
1326 if (($variant->content_type == 'video/mp4') && ($variant->bitrate >= $bitrate)) {
1327 $media[$medium->url] = "\n[video]" . $variant->url . '[/video]';
1328 $bitrate = $variant->bitrate;
1333 // The following code will only be activated for test reasons
1335 // $postarray['body'] .= print_r($medium, true);
1339 // Now we replace the media urls.
1340 foreach ($media AS $key => $value) {
1341 $postarray['body'] = str_replace($key, "\n" . $value . "\n", $postarray['body']);
1347 function twitter_createpost(App $a, $uid, $post, array $self, $create_user, $only_existing_contact, $noquote)
1350 $postarray['network'] = Protocol::TWITTER;
1351 $postarray['uid'] = $uid;
1352 $postarray['wall'] = 0;
1353 $postarray['uri'] = "twitter::" . $post->id_str;
1354 $postarray['protocol'] = Conversation::PARCEL_TWITTER;
1355 $postarray['source'] = json_encode($post);
1357 // Don't import our own comments
1358 if (Item::exists(['extid' => $postarray['uri'], 'uid' => $uid])) {
1359 Logger::log("Item with extid " . $postarray['uri'] . " found.", Logger::DEBUG);
1365 if ($post->in_reply_to_status_id_str != "") {
1366 $parent = "twitter::" . $post->in_reply_to_status_id_str;
1368 $fields = ['uri', 'parent-uri', 'parent'];
1369 $parent_item = Item::selectFirst($fields, ['uri' => $parent, 'uid' => $uid]);
1370 if (!DBA::isResult($parent_item)) {
1371 $parent_item = Item::selectFirst($fields, ['extid' => $parent, 'uid' => $uid]);
1374 if (DBA::isResult($parent_item)) {
1375 $postarray['thr-parent'] = $parent_item['uri'];
1376 $postarray['parent-uri'] = $parent_item['parent-uri'];
1377 $postarray['parent'] = $parent_item['parent'];
1378 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1380 $postarray['thr-parent'] = $postarray['uri'];
1381 $postarray['parent-uri'] = $postarray['uri'];
1382 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1386 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1388 if ($post->user->id_str == $own_id) {
1389 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1392 if (DBA::isResult($r)) {
1393 $contactid = $r[0]["id"];
1395 $postarray['owner-name'] = $r[0]["name"];
1396 $postarray['owner-link'] = $r[0]["url"];
1397 $postarray['owner-avatar'] = $r[0]["photo"];
1399 Logger::log("No self contact for user " . $uid, Logger::DEBUG);
1403 // Don't create accounts of people who just comment something
1404 $create_user = false;
1406 $postarray['parent-uri'] = $postarray['uri'];
1407 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1410 if ($contactid == 0) {
1411 $contactid = twitter_fetch_contact($uid, $post->user, $create_user);
1413 $postarray['owner-name'] = $post->user->name;
1414 $postarray['owner-link'] = "https://twitter.com/" . $post->user->screen_name;
1415 $postarray['owner-avatar'] = twitter_fix_avatar($post->user->profile_image_url_https);
1418 if (($contactid == 0) && !$only_existing_contact) {
1419 $contactid = $self['id'];
1420 } elseif ($contactid <= 0) {
1421 Logger::log("Contact ID is zero or less than zero.", Logger::DEBUG);
1425 $postarray['contact-id'] = $contactid;
1427 $postarray['verb'] = ACTIVITY_POST;
1428 $postarray['author-name'] = $postarray['owner-name'];
1429 $postarray['author-link'] = $postarray['owner-link'];
1430 $postarray['author-avatar'] = $postarray['owner-avatar'];
1431 $postarray['plink'] = "https://twitter.com/" . $post->user->screen_name . "/status/" . $post->id_str;
1432 $postarray['app'] = strip_tags($post->source);
1434 if ($post->user->protected) {
1435 $postarray['private'] = 1;
1436 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1438 $postarray['private'] = 0;
1439 $postarray['allow_cid'] = '';
1442 if (!empty($post->full_text)) {
1443 $postarray['body'] = $post->full_text;
1445 $postarray['body'] = $post->text;
1448 // When the post contains links then use the correct object type
1449 if (count($post->entities->urls) > 0) {
1450 $postarray['object-type'] = ACTIVITY_OBJ_BOOKMARK;
1453 // Search for media links
1454 $picture = twitter_media_entities($post, $postarray);
1456 $converted = twitter_expand_entities($a, $postarray['body'], $post, $picture);
1457 $postarray['body'] = $converted["body"];
1458 $postarray['tag'] = $converted["tags"];
1459 $postarray['created'] = DateTimeFormat::utc($post->created_at);
1460 $postarray['edited'] = DateTimeFormat::utc($post->created_at);
1462 $statustext = $converted["plain"];
1464 if (!empty($post->place->name)) {
1465 $postarray["location"] = $post->place->name;
1467 if (!empty($post->place->full_name)) {
1468 $postarray["location"] = $post->place->full_name;
1470 if (!empty($post->geo->coordinates)) {
1471 $postarray["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
1473 if (!empty($post->coordinates->coordinates)) {
1474 $postarray["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
1476 if (!empty($post->retweeted_status)) {
1477 $retweet = twitter_createpost($a, $uid, $post->retweeted_status, $self, false, false, $noquote);
1479 if (empty($retweet['body'])) {
1484 // Store the original tweet
1485 Item::insert($retweet);
1487 // CHange the other post into a reshare activity
1488 $postarray['verb'] = ACTIVITY2_ANNOUNCE;
1489 $postarray['gravity'] = GRAVITY_ACTIVITY;
1490 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1492 $postarray['thr-parent'] = $retweet['uri'];
1493 $postarray['parent-uri'] = $retweet['uri'];
1495 $retweet['source'] = $postarray['source'];
1496 $retweet['private'] = $postarray['private'];
1497 $retweet['allow_cid'] = $postarray['allow_cid'];
1498 $retweet['contact-id'] = $postarray['contact-id'];
1499 $retweet['owner-name'] = $postarray['owner-name'];
1500 $retweet['owner-link'] = $postarray['owner-link'];
1501 $retweet['owner-avatar'] = $postarray['owner-avatar'];
1503 $postarray = $retweet;
1507 if (!empty($post->quoted_status) && !$noquote) {
1508 $quoted = twitter_createpost($a, $uid, $post->quoted_status, $self, false, false, true);
1510 if (empty($quoted['body'])) {
1514 $postarray['body'] .= "\n" . share_header(
1515 $quoted['author-name'],
1516 $quoted['author-link'],
1517 $quoted['author-avatar'],
1523 $postarray['body'] .= $quoted['body'] . '[/share]';
1529 function twitter_fetchparentposts(App $a, $uid, $post, TwitterOAuth $connection, array $self)
1531 Logger::log("twitter_fetchparentposts: Fetching for user " . $uid . " and post " . $post->id_str, Logger::DEBUG);
1535 while (!empty($post->in_reply_to_status_id_str)) {
1536 $parameters = ["trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str];
1539 $post = $connection->get('statuses/show', $parameters);
1540 } catch (TwitterOAuthException $e) {
1541 Logger::log('twitter_fetchparentposts: Error fetching for user ' . $uid . ' and post ' . $post->id_str . ': ' . $e->getMessage());
1546 Logger::log("twitter_fetchparentposts: Can't fetch post " . $parameters['id'], Logger::DEBUG);
1550 if (empty($post->id_str)) {
1551 Logger::log("twitter_fetchparentposts: This is not a post " . json_encode($post), Logger::DEBUG);
1555 if (Item::exists(['uri' => 'twitter::' . $post->id_str, 'uid' => $uid])) {
1562 Logger::log("twitter_fetchparentposts: Fetching " . count($posts) . " parents", Logger::DEBUG);
1564 $posts = array_reverse($posts);
1566 if (!empty($posts)) {
1567 foreach ($posts as $post) {
1568 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1570 if (empty($postarray['body'])) {
1574 $item = Item::insert($postarray);
1576 $postarray["id"] = $item;
1578 Logger::log('twitter_fetchparentpost: User ' . $self["nick"] . ' posted parent timeline item ' . $item);
1583 function twitter_fetchhometimeline(App $a, $uid)
1585 $ckey = Config::get('twitter', 'consumerkey');
1586 $csecret = Config::get('twitter', 'consumersecret');
1587 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1588 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1589 $create_user = PConfig::get($uid, 'twitter', 'create_user');
1590 $mirror_posts = PConfig::get($uid, 'twitter', 'mirror_posts');
1592 Logger::log("Fetching timeline for user " . $uid, Logger::DEBUG);
1594 $application_name = Config::get('twitter', 'application_name');
1596 if ($application_name == "") {
1597 $application_name = $a->getHostName();
1600 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1603 $own_contact = twitter_fetch_own_contact($a, $uid);
1604 } catch (TwitterOAuthException $e) {
1605 Logger::log('Error fetching own contact for user ' . $uid . ': ' . $e->getMessage());
1609 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1610 intval($own_contact),
1613 if (DBA::isResult($r)) {
1614 $own_id = $r[0]["nick"];
1616 Logger::log("Own twitter contact not found for user " . $uid);
1620 $self = User::getOwnerDataById($uid);
1621 if ($self === false) {
1622 Logger::log("Own contact not found for user " . $uid);
1626 $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
1627 //$parameters["count"] = 200;
1628 // Fetching timeline
1629 $lastid = PConfig::get($uid, 'twitter', 'lasthometimelineid');
1631 $first_time = ($lastid == "");
1633 if ($lastid != "") {
1634 $parameters["since_id"] = $lastid;
1638 $items = $connection->get('statuses/home_timeline', $parameters);
1639 } catch (TwitterOAuthException $e) {
1640 Logger::log('Error fetching home timeline for user ' . $uid . ': ' . $e->getMessage());
1644 if (!is_array($items)) {
1645 Logger::log('No array while fetching home timeline for user ' . $uid . ': ' . print_r($items, true));
1649 if (empty($items)) {
1650 Logger::log('No new timeline content for user ' . $uid, Logger::INFO);
1654 $posts = array_reverse($items);
1656 Logger::log('Fetching timeline from ID ' . $lastid . ' for user ' . $uid . ' ' . sizeof($posts) . ' items', Logger::DEBUG);
1658 if (count($posts)) {
1659 foreach ($posts as $post) {
1660 if ($post->id_str > $lastid) {
1661 $lastid = $post->id_str;
1662 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1669 if (stristr($post->source, $application_name) && $post->user->screen_name == $own_id) {
1670 Logger::log("Skip previously sent post", Logger::DEBUG);
1674 if ($mirror_posts && $post->user->screen_name == $own_id && $post->in_reply_to_status_id_str == "") {
1675 Logger::log("Skip post that will be mirrored", Logger::DEBUG);
1679 if ($post->in_reply_to_status_id_str != "") {
1680 twitter_fetchparentposts($a, $uid, $post, $connection, $self);
1683 Logger::log('Preparing post ' . $post->id_str . ' for user ' . $uid, Logger::DEBUG);
1685 $postarray = twitter_createpost($a, $uid, $post, $self, $create_user, true, false);
1687 if (empty($postarray['body']) || trim($postarray['body']) == "") {
1688 Logger::log('Empty body for post ' . $post->id_str . ' and user ' . $uid, Logger::DEBUG);
1694 if (($postarray['uri'] == $postarray['parent-uri']) && ($postarray['author-link'] == $postarray['owner-link'])) {
1695 $contact = DBA::selectFirst('contact', [], ['id' => $postarray['contact-id'], 'self' => false]);
1696 if (DBA::isResult($contact)) {
1697 $notify = Item::isRemoteSelf($contact, $postarray);
1701 $item = Item::insert($postarray, false, $notify);
1702 $postarray["id"] = $item;
1704 Logger::log('User ' . $uid . ' posted home timeline item ' . $item);
1707 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1709 Logger::log('Last timeline ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
1711 // Fetching mentions
1712 $lastid = PConfig::get($uid, 'twitter', 'lastmentionid');
1714 $first_time = ($lastid == "");
1716 if ($lastid != "") {
1717 $parameters["since_id"] = $lastid;
1721 $items = $connection->get('statuses/mentions_timeline', $parameters);
1722 } catch (TwitterOAuthException $e) {
1723 Logger::log('Error fetching mentions: ' . $e->getMessage());
1727 if (!is_array($items)) {
1728 Logger::log("Error fetching mentions: " . print_r($items, true), Logger::DEBUG);
1732 $posts = array_reverse($items);
1734 Logger::log("Fetching mentions 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;
1746 if ($post->in_reply_to_status_id_str != "") {
1747 twitter_fetchparentposts($a, $uid, $post, $connection, $self);
1750 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1752 if (empty($postarray['body'])) {
1756 $item = Item::insert($postarray);
1758 Logger::log('User ' . $uid . ' posted mention timeline item ' . $item);
1762 PConfig::set($uid, 'twitter', 'lastmentionid', $lastid);
1764 Logger::log('Last mentions ID for user ' . $uid . ' is now ' . $lastid, Logger::DEBUG);
1767 function twitter_fetch_own_contact(App $a, $uid)
1769 $ckey = Config::get('twitter', 'consumerkey');
1770 $csecret = Config::get('twitter', 'consumersecret');
1771 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1772 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1774 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1778 if ($own_id == "") {
1779 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1781 // Fetching user data
1782 // get() may throw TwitterOAuthException, but we will catch it later
1783 $user = $connection->get('account/verify_credentials');
1784 if (empty($user) || empty($user->id_str)) {
1788 PConfig::set($uid, 'twitter', 'own_id', $user->id_str);
1790 $contact_id = twitter_fetch_contact($uid, $user, true);
1792 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1794 DBA::escape("twitter::" . $own_id));
1795 if (DBA::isResult($r)) {
1796 $contact_id = $r[0]["id"];
1798 PConfig::delete($uid, 'twitter', 'own_id');
1805 function twitter_is_retweet(App $a, $uid, $body)
1807 $body = trim($body);
1809 // Skip if it isn't a pure repeated messages
1810 // Does it start with a share?
1811 if (strpos($body, "[share") > 0) {
1815 // Does it end with a share?
1816 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1820 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1821 // Skip if there is no shared message in there
1822 if ($body == $attributes) {
1827 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1828 if (!empty($matches[1])) {
1829 $link = $matches[1];
1832 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1833 if (!empty($matches[1])) {
1834 $link = $matches[1];
1837 $id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link);
1842 Logger::log('twitter_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, Logger::DEBUG);
1844 $ckey = Config::get('twitter', 'consumerkey');
1845 $csecret = Config::get('twitter', 'consumersecret');
1846 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1847 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1849 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1850 $result = $connection->post('statuses/retweet/' . $id);
1852 Logger::log('twitter_is_retweet: result ' . print_r($result, true), Logger::DEBUG);
1854 return !isset($result->errors);
1857 function twitter_update_mentions($body)
1859 $URLSearchString = "^\[\]";
1860 $return = preg_replace_callback(
1861 "/@\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",
1862 function ($matches) {
1863 if (strpos($matches[1], 'twitter.com')) {
1864 $return = '@' . substr($matches[1], strrpos($matches[1], '/') + 1);
1866 $return = $matches[2] . ' (' . $matches[1] . ')';
1877 function twitter_convert_share(array $attributes, array $author_contact, $content, $is_quote_share)
1879 if ($author_contact['network'] == Protocol::TWITTER) {
1880 $mention = '@' . $author_contact['nickname'];
1882 $mention = $author_contact['addr'];
1885 return ($is_quote_share ? "\n\n" : '' ) . 'RT ' . $mention . ': ' . $content . "\n\n" . $attributes['link'];