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.ini.php or use the admin panel.
54 * consumerkey = your consumer_key here
55 * consumersecret = your consumer_secret here
57 * To activate the addon itself add it to the [system] addon
58 * setting. After this, your user can configure their Twitter account settings
59 * from "Settings -> Addon Settings".
61 * Requirements: PHP5, curl
64 use Abraham\TwitterOAuth\TwitterOAuth;
65 use Abraham\TwitterOAuth\TwitterOAuthException;
67 use Friendica\Content\OEmbed;
68 use Friendica\Content\Text\Plaintext;
69 use Friendica\Core\Addon;
70 use Friendica\Core\Config;
71 use Friendica\Core\L10n;
72 use Friendica\Core\PConfig;
73 use Friendica\Core\Worker;
74 use Friendica\Database\DBA;
75 use Friendica\Model\Contact;
76 use Friendica\Model\GContact;
77 use Friendica\Model\Group;
78 use Friendica\Model\Item;
79 use Friendica\Model\ItemContent;
80 use Friendica\Model\Queue;
81 use Friendica\Model\User;
82 use Friendica\Object\Image;
83 use Friendica\Util\DateTimeFormat;
84 use Friendica\Util\Network;
86 require_once 'boot.php';
87 require_once 'include/dba.php';
88 require_once 'include/enotify.php';
89 require_once 'include/text.php';
91 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
93 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
95 function twitter_install()
97 // we need some hooks, for the configuration and for sending tweets
98 Addon::registerHook('load_config', 'addon/twitter/twitter.php', 'twitter_load_config');
99 Addon::registerHook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings');
100 Addon::registerHook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
101 Addon::registerHook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
102 Addon::registerHook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
103 Addon::registerHook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
104 Addon::registerHook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
105 Addon::registerHook('queue_predeliver', 'addon/twitter/twitter.php', 'twitter_queue_hook');
106 Addon::registerHook('follow', 'addon/twitter/twitter.php', 'twitter_follow');
107 Addon::registerHook('expire', 'addon/twitter/twitter.php', 'twitter_expire');
108 Addon::registerHook('prepare_body', 'addon/twitter/twitter.php', 'twitter_prepare_body');
109 Addon::registerHook('check_item_notification', 'addon/twitter/twitter.php', 'twitter_check_item_notification');
110 logger("installed twitter");
113 function twitter_uninstall()
115 Addon::unregisterHook('load_config', 'addon/twitter/twitter.php', 'twitter_load_config');
116 Addon::unregisterHook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings');
117 Addon::unregisterHook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
118 Addon::unregisterHook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
119 Addon::unregisterHook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
120 Addon::unregisterHook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
121 Addon::unregisterHook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
122 Addon::unregisterHook('queue_predeliver', 'addon/twitter/twitter.php', 'twitter_queue_hook');
123 Addon::unregisterHook('follow', 'addon/twitter/twitter.php', 'twitter_follow');
124 Addon::unregisterHook('expire', 'addon/twitter/twitter.php', 'twitter_expire');
125 Addon::unregisterHook('prepare_body', 'addon/twitter/twitter.php', 'twitter_prepare_body');
126 Addon::unregisterHook('check_item_notification', 'addon/twitter/twitter.php', 'twitter_check_item_notification');
128 // old setting - remove only
129 Addon::unregisterHook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
130 Addon::unregisterHook('addon_settings', 'addon/twitter/twitter.php', 'twitter_settings');
131 Addon::unregisterHook('addon_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
134 function twitter_load_config(App $a)
136 $a->loadConfigFile(__DIR__. '/config/twitter.ini.php');
139 function twitter_check_item_notification(App $a, &$notification_data)
141 $own_id = PConfig::get($notification_data["uid"], 'twitter', 'own_id');
143 $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
144 intval($notification_data["uid"]),
145 dbesc("twitter::".$own_id)
149 $notification_data["profiles"][] = $own_user[0]["url"];
153 function twitter_follow(App $a, &$contact)
155 logger("twitter_follow: Check if contact is twitter contact. " . $contact["url"], LOGGER_DEBUG);
157 if (!strstr($contact["url"], "://twitter.com") && !strstr($contact["url"], "@twitter.com")) {
161 // contact seems to be a twitter contact, so continue
162 $nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $contact["url"]);
163 $nickname = str_replace("@twitter.com", "", $nickname);
165 $uid = $a->user["uid"];
167 $ckey = Config::get('twitter', 'consumerkey');
168 $csecret = Config::get('twitter', 'consumersecret');
169 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
170 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
172 // If the addon is not configured (general or for this user) quit here
173 if (empty($ckey) || empty($csecret) || empty($otoken) || empty($osecret)) {
178 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
179 $connection->post('friendships/create', ['screen_name' => $nickname]);
181 twitter_fetchuser($a, $uid, $nickname);
183 $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
184 FROM `contact` WHERE `uid` = %d AND `nick` = '%s'",
187 if (DBA::isResult($r)) {
188 $contact["contact"] = $r[0];
192 function twitter_jot_nets(App $a, &$b)
198 $tw_post = PConfig::get(local_user(), 'twitter', 'post');
199 if (intval($tw_post) == 1) {
200 $tw_defpost = PConfig::get(local_user(), 'twitter', 'post_by_default');
201 $selected = ((intval($tw_defpost) == 1) ? ' checked="checked" ' : '');
202 $b .= '<div class="profile-jot-net"><input type="checkbox" name="twitter_enable"' . $selected . ' value="1" /> '
203 . L10n::t('Post to Twitter') . '</div>';
207 function twitter_settings_post(App $a, $post)
212 // don't check twitter settings if twitter submit button is not clicked
213 if (empty($_POST['twitter-disconnect']) && empty($_POST['twitter-submit'])) {
217 if (!empty($_POST['twitter-disconnect'])) {
219 * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
220 * from the user configuration
222 PConfig::delete(local_user(), 'twitter', 'consumerkey');
223 PConfig::delete(local_user(), 'twitter', 'consumersecret');
224 PConfig::delete(local_user(), 'twitter', 'oauthtoken');
225 PConfig::delete(local_user(), 'twitter', 'oauthsecret');
226 PConfig::delete(local_user(), 'twitter', 'post');
227 PConfig::delete(local_user(), 'twitter', 'post_by_default');
228 PConfig::delete(local_user(), 'twitter', 'lastid');
229 PConfig::delete(local_user(), 'twitter', 'mirror_posts');
230 PConfig::delete(local_user(), 'twitter', 'import');
231 PConfig::delete(local_user(), 'twitter', 'create_user');
232 PConfig::delete(local_user(), 'twitter', 'own_id');
234 if (isset($_POST['twitter-pin'])) {
235 // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
236 logger('got a Twitter PIN');
237 $ckey = Config::get('twitter', 'consumerkey');
238 $csecret = Config::get('twitter', 'consumersecret');
239 // the token and secret for which the PIN was generated were hidden in the settings
240 // form as token and token2, we need a new connection to Twitter using these token
241 // and secret to request a Access Token with the PIN
243 if (empty($_POST['twitter-pin'])) {
244 throw new Exception(L10n::t('You submitted an empty PIN, please Sign In with Twitter again to get a new one.'));
247 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
248 $token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_POST['twitter-pin']]);
249 // ok, now that we have the Access Token, save them in the user config
250 PConfig::set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
251 PConfig::set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
252 PConfig::set(local_user(), 'twitter', 'post', 1);
253 } catch(Exception $e) {
254 info($e->getMessage());
255 } catch(TwitterOAuthException $e) {
256 info($e->getMessage());
258 // reload the Addon Settings page, if we don't do it see Bug #42
259 goaway('settings/connectors');
261 // if no PIN is supplied in the POST variables, the user has changed the setting
262 // to post a tweet for every new __public__ posting to the wall
263 PConfig::set(local_user(), 'twitter', 'post', intval($_POST['twitter-enable']));
264 PConfig::set(local_user(), 'twitter', 'post_by_default', intval($_POST['twitter-default']));
265 PConfig::set(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror']));
266 PConfig::set(local_user(), 'twitter', 'import', intval($_POST['twitter-import']));
267 PConfig::set(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user']));
269 if (!intval($_POST['twitter-mirror'])) {
270 PConfig::delete(local_user(), 'twitter', 'lastid');
273 info(L10n::t('Twitter settings updated.') . EOL);
278 function twitter_settings(App $a, &$s)
283 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
285 * 1) Check that we have global consumer key & secret
286 * 2) If no OAuthtoken & stuff is present, generate button to get some
287 * 3) Checkbox for "Send public notices (280 chars only)
289 $ckey = Config::get('twitter', 'consumerkey');
290 $csecret = Config::get('twitter', 'consumersecret');
291 $otoken = PConfig::get(local_user(), 'twitter', 'oauthtoken');
292 $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret');
294 $enabled = intval(PConfig::get(local_user(), 'twitter', 'post'));
295 $defenabled = intval(PConfig::get(local_user(), 'twitter', 'post_by_default'));
296 $mirrorenabled = intval(PConfig::get(local_user(), 'twitter', 'mirror_posts'));
297 $importenabled = intval(PConfig::get(local_user(), 'twitter', 'import'));
298 $create_userenabled = intval(PConfig::get(local_user(), 'twitter', 'create_user'));
300 $css = (($enabled) ? '' : '-disabled');
302 $s .= '<span id="settings_twitter_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
303 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
305 $s .= '<div id="settings_twitter_expanded" class="settings-block" style="display: none;">';
306 $s .= '<span class="fakelink" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
307 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
310 if ((!$ckey) && (!$csecret)) {
311 /* no global consumer keys
312 * display warning and skip personal config
314 $s .= '<p>' . L10n::t('No consumer key pair for Twitter found. Please contact your site administrator.') . '</p>';
316 // ok we have a consumer key pair now look into the OAuth stuff
317 if ((!$otoken) && (!$osecret)) {
318 /* the user has not yet connected the account to twitter...
319 * get a temporary OAuth key/secret pair and display a button with
320 * which the user can request a PIN to connect the account to a
321 * account at Twitter.
323 $connection = new TwitterOAuth($ckey, $csecret);
325 $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
326 $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>';
327 $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>';
328 $s .= '<div id="twitter-pin-wrapper">';
329 $s .= '<label id="twitter-pin-label" for="twitter-pin">' . L10n::t('Copy the PIN from Twitter here') . '</label>';
330 $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
331 $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result['oauth_token'] . '" />';
332 $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result['oauth_token_secret'] . '" />';
333 $s .= '</div><div class="clear"></div>';
334 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
335 } catch (TwitterOAuthException $e) {
336 $s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
340 * we have an OAuth key / secret pair for the user
341 * so let's give a chance to disable the postings to Twitter
343 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
345 $details = $connection->get('account/verify_credentials');
347 $field_checkbox = get_markup_template('field_checkbox.tpl');
349 $s .= '<div id="twitter-info" >
350 <p>' . L10n::t('Currently connected to: ') . '<a href="https://twitter.com/' . $details->screen_name . '" target="_twitter">' . $details->screen_name . '</a>
351 <button type="submit" name="twitter-disconnect" value="1">' . L10n::t('Disconnect') . '</button>
353 <p id="twitter-info-block">
354 <a href="https://twitter.com/' . $details->screen_name . '" target="_twitter"><img id="twitter-avatar" src="' . $details->profile_image_url . '" /></a>
355 <em>' . $details->description . '</em>
358 $s .= '<div class="clear"></div>';
360 $s .= replace_macros($field_checkbox, [
361 '$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.')]
363 if ($a->user['hidewall']) {
364 $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>';
366 $s .= replace_macros($field_checkbox, [
367 '$field' => ['twitter-default', L10n::t('Send public postings to Twitter by default'), $defenabled, '']
369 $s .= replace_macros($field_checkbox, [
370 '$field' => ['twitter-mirror', L10n::t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '']
372 $s .= replace_macros($field_checkbox, [
373 '$field' => ['twitter-import', L10n::t('Import the remote timeline'), $importenabled, '']
375 $s .= replace_macros($field_checkbox, [
376 '$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.')]
378 $s .= '<div class="clear"></div>';
379 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
380 } catch (TwitterOAuthException $e) {
381 $s .= '<p>' . L10n::t('An error occured: ') . $e->getMessage() . '</p>';
385 $s .= '</div><div class="clear"></div>';
388 function twitter_post_local(App $a, &$b)
394 if (!local_user() || (local_user() != $b['uid'])) {
398 $twitter_post = intval(PConfig::get(local_user(), 'twitter', 'post'));
399 $twitter_enable = (($twitter_post && x($_REQUEST, 'twitter_enable')) ? intval($_REQUEST['twitter_enable']) : 0);
401 // if API is used, default to the chosen settings
402 if ($b['api_source'] && intval(PConfig::get(local_user(), 'twitter', 'post_by_default'))) {
406 if (!$twitter_enable) {
410 if (strlen($b['postopts'])) {
411 $b['postopts'] .= ',';
414 $b['postopts'] .= 'twitter';
417 function twitter_action(App $a, $uid, $pid, $action)
419 $ckey = Config::get('twitter', 'consumerkey');
420 $csecret = Config::get('twitter', 'consumersecret');
421 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
422 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
424 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
426 $post = ['id' => $pid];
428 logger("twitter_action '" . $action . "' ID: " . $pid . " data: " . print_r($post, true), LOGGER_DATA);
432 // To-Do: $result = $connection->post('statuses/destroy', $post);
436 $result = $connection->post('favorites/create', $post);
439 $result = $connection->post('favorites/destroy', $post);
442 logger('Unhandled action ' . $action, LOGGER_DEBUG);
445 logger("twitter_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG);
448 function twitter_post_hook(App $a, &$b)
451 if (!PConfig::get($b["uid"], 'twitter', 'import')
452 && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
456 if ($b['parent'] != $b['id']) {
457 logger("twitter_post_hook: parameter " . print_r($b, true), LOGGER_DATA);
459 // Looking if its a reply to a twitter post
460 if ((substr($b["parent-uri"], 0, 9) != "twitter::")
461 && (substr($b["extid"], 0, 9) != "twitter::")
462 && (substr($b["thr-parent"], 0, 9) != "twitter::"))
464 logger("twitter_post_hook: no twitter post " . $b["parent"]);
468 $condition = ['uri' => $b["thr-parent"], 'uid' => $b["uid"]];
469 $orig_post = Item::selectFirst([], $condition);
470 if (!DBA::isResult($orig_post)) {
471 logger("twitter_post_hook: no parent found " . $b["thr-parent"]);
478 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
479 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
480 $nicknameplain = "@" . $nicknameplain;
482 logger("twitter_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], LOGGER_DEBUG);
483 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
484 $b["body"] = $nickname . " " . $b["body"];
487 logger("twitter_post_hook: parent found " . print_r($orig_post, true), LOGGER_DATA);
491 if ($b['private'] || !strstr($b['postopts'], 'twitter')) {
495 // Dont't post if the post doesn't belong to us.
496 // This is a check for forum postings
497 $self = DBA::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
498 if ($b['contact-id'] != $self['id']) {
503 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
504 twitter_action($a, $b["uid"], substr($orig_post["uri"], 9), "delete");
507 if ($b['verb'] == ACTIVITY_LIKE) {
508 logger("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), LOGGER_DEBUG);
510 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike");
512 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "like");
518 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
522 // if post comes from twitter don't send it back
523 if ($b['extid'] == NETWORK_TWITTER) {
527 if ($b['app'] == "Twitter") {
531 logger('twitter post invoked');
533 PConfig::load($b['uid'], 'twitter');
535 $ckey = Config::get('twitter', 'consumerkey');
536 $csecret = Config::get('twitter', 'consumersecret');
537 $otoken = PConfig::get($b['uid'], 'twitter', 'oauthtoken');
538 $osecret = PConfig::get($b['uid'], 'twitter', 'oauthsecret');
540 if ($ckey && $csecret && $otoken && $osecret) {
541 logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
543 // If it's a repeated message from twitter then do a native retweet and exit
544 if (twitter_is_retweet($a, $b['uid'], $b['body'])) {
548 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
550 // Set the timeout for upload to 30 seconds
551 $connection->setTimeouts(10, 30);
554 $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 8);
555 $msg = $msgarr["text"];
557 if (($msg == "") && isset($msgarr["title"])) {
558 $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
563 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
564 $msg .= "\n" . $msgarr["url"];
570 if (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
571 $image = $msgarr["image"];
578 // and now tweet it :-)
581 if (!empty($image)) {
583 $img_str = Network::fetchUrl($image);
585 $tempfile = tempnam(get_temppath(), 'cache');
586 file_put_contents($tempfile, $img_str);
588 $media = $connection->upload('media/upload', ['media' => $tempfile]);
592 $post['media_ids'] = $media->media_id_string;
593 } catch (Exception $e) {
594 logger('Exception when trying to send to Twitter: ' . $e->getMessage());
596 // Workaround: Remove the picture link so that the post can be reposted without it
597 // When there is another url already added, a second url would be superfluous.
599 $msg .= "\n" . $image;
606 $post['status'] = $msg;
609 $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
612 $url = 'statuses/update';
613 $result = $connection->post($url, $post);
614 logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG);
616 if (!empty($result->source)) {
617 Config::set("twitter", "application_name", strip_tags($result->source));
620 if (!empty($result->errors)) {
621 logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
623 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
624 if (DBA::isResult($r)) {
625 $a->contact = $r[0]["id"];
628 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $post]);
630 Queue::add($a->contact, NETWORK_TWITTER, $s);
631 notice(L10n::t('Twitter post failed. Queued for retry.') . EOL);
632 } elseif ($iscomment) {
633 logger('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']);
634 Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]);
639 function twitter_addon_admin_post(App $a)
641 $consumerkey = x($_POST, 'consumerkey') ? notags(trim($_POST['consumerkey'])) : '';
642 $consumersecret = x($_POST, 'consumersecret') ? notags(trim($_POST['consumersecret'])) : '';
643 Config::set('twitter', 'consumerkey', $consumerkey);
644 Config::set('twitter', 'consumersecret', $consumersecret);
645 info(L10n::t('Settings updated.') . EOL);
648 function twitter_addon_admin(App $a, &$o)
650 $t = get_markup_template("admin.tpl", "addon/twitter/");
652 $o = replace_macros($t, [
653 '$submit' => L10n::t('Save Settings'),
654 // name, label, value, help, [extra values]
655 '$consumerkey' => ['consumerkey', L10n::t('Consumer key'), Config::get('twitter', 'consumerkey'), ''],
656 '$consumersecret' => ['consumersecret', L10n::t('Consumer secret'), Config::get('twitter', 'consumersecret'), ''],
660 function twitter_cron(App $a, $b)
662 $last = Config::get('twitter', 'last_poll');
664 $poll_interval = intval(Config::get('twitter', 'poll_interval'));
665 if (!$poll_interval) {
666 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
670 $next = $last + ($poll_interval * 60);
671 if ($next > time()) {
672 logger('twitter: poll intervall not reached');
676 logger('twitter: cron_start');
678 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1'");
679 if (DBA::isResult($r)) {
680 foreach ($r as $rr) {
681 logger('twitter: fetching for user ' . $rr['uid']);
682 Worker::add(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 1, (int) $rr['uid']);
686 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
687 if ($abandon_days < 1) {
691 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
693 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1'");
694 if (DBA::isResult($r)) {
695 foreach ($r as $rr) {
696 if ($abandon_days != 0) {
697 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
698 if (!DBA::isResult($user)) {
699 logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
704 logger('twitter: importing timeline from user ' . $rr['uid']);
705 Worker::add(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 2, (int) $rr['uid']);
708 // check for new contacts once a day
709 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
710 if($last_contact_check)
711 $next_contact_check = $last_contact_check + 86400;
713 $next_contact_check = 0;
715 if($next_contact_check <= time()) {
716 pumpio_getallusers($a, $rr["uid"]);
717 PConfig::set($rr['uid'],'pumpio','contact_check',time());
723 logger('twitter: cron_end');
725 Config::set('twitter', 'last_poll', time());
728 function twitter_expire(App $a, $b)
730 $days = Config::get('twitter', 'expire');
736 $r = DBA::select('item', ['id', 'iaid', 'icid'], ['deleted' => true, 'network' => NETWORK_TWITTER]);
737 while ($row = DBA::fetch($r)) {
738 DBA::delete('item', ['id' => $row['id']]);
739 if (!empty($row['iaid']) && !DBA::exists('item', ['iaid' => $row['iaid']])) {
740 DBA::delete('item-activity', ['id' => $row['iaid']]);
742 if (!empty($row['icid']) && !DBA::exists('item', ['icid' => $row['icid']])) {
743 DBA::delete('item-content', ['id' => $row['icid']]);
748 require_once "include/items.php";
750 logger('twitter_expire: expire_start');
752 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
753 if (DBA::isResult($r)) {
754 foreach ($r as $rr) {
755 logger('twitter_expire: user ' . $rr['uid']);
756 Item::expire($rr['uid'], $days, NETWORK_TWITTER, true);
760 logger('twitter_expire: expire_end');
763 function twitter_prepare_body(App $a, &$b)
765 if ($b["item"]["network"] != NETWORK_TWITTER) {
772 $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
774 $condition = ['uri' => $item["thr-parent"], 'uid' => local_user()];
775 $orig_post = Item::selectFirst(['author-link'], $condition);
776 if (DBA::isResult($orig_post)) {
777 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
778 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
779 $nicknameplain = "@" . $nicknameplain;
781 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
782 $item["body"] = $nickname . " " . $item["body"];
786 $msgarr = ItemContent::getPlaintextPost($item, $max_char, true, 8);
787 $msg = $msgarr["text"];
789 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
790 $msg .= " " . $msgarr["url"];
793 if (isset($msgarr["image"])) {
794 $msg .= " " . $msgarr["image"];
797 $b['html'] = nl2br(htmlspecialchars($msg));
802 * @brief Build the item array for the mirrored post
804 * @param App $a Application class
805 * @param integer $uid User id
806 * @param object $post Twitter object with the post
808 * @return array item data to be posted
810 function twitter_do_mirrorpost(App $a, $uid, $post)
812 $datarray["api_source"] = true;
813 $datarray["profile_uid"] = $uid;
814 $datarray["extid"] = NETWORK_TWITTER;
815 $datarray['message_id'] = Item::newURI($uid, NETWORK_TWITTER . ":" . $post->id);
816 // $datarray['object'] = json_encode($post); // Activate for debugging
817 $datarray["title"] = "";
819 if (!empty($post->retweeted_status)) {
820 // We don't support nested shares, so we mustn't show quotes as shares on retweets
821 $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true);
823 $datarray['body'] = "\n" . share_header(
824 $item['author-name'],
825 $item['author-link'],
826 $item['author-avatar'],
832 $datarray['body'] .= $item['body'] . '[/share]';
834 $item = twitter_createpost($a, $uid, $post, ['id' => 0], false, false, false);
836 $datarray['body'] = $item['body'];
839 $datarray["source"] = $item['app'];
840 $datarray["verb"] = $item['verb'];
842 if (isset($item["location"])) {
843 $datarray["location"] = $item["location"];
846 if (isset($item["coord"])) {
847 $datarray["coord"] = $item["coord"];
853 function twitter_fetchtimeline(App $a, $uid)
855 $ckey = Config::get('twitter', 'consumerkey');
856 $csecret = Config::get('twitter', 'consumersecret');
857 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
858 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
859 $lastid = PConfig::get($uid, 'twitter', 'lastid');
861 $application_name = Config::get('twitter', 'application_name');
863 if ($application_name == "") {
864 $application_name = $a->get_hostname();
867 $has_picture = false;
869 require_once 'mod/item.php';
870 require_once 'include/items.php';
871 require_once 'mod/share.php';
873 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
875 $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
877 $first_time = ($lastid == "");
880 $parameters["since_id"] = $lastid;
884 $items = $connection->get('statuses/user_timeline', $parameters);
885 } catch (TwitterOAuthException $e) {
886 logger('twitter_fetchtimeline: Error fetching timeline for user ' . $uid . ': ' . $e->getMessage());
890 if (!is_array($items)) {
894 $posts = array_reverse($items);
897 foreach ($posts as $post) {
898 if ($post->id_str > $lastid) {
899 $lastid = $post->id_str;
900 PConfig::set($uid, 'twitter', 'lastid', $lastid);
907 if (!stristr($post->source, $application_name)) {
908 $_SESSION["authenticated"] = true;
909 $_SESSION["uid"] = $uid;
911 $_REQUEST = twitter_do_mirrorpost($a, $uid, $post);
913 logger('twitter: posting for user ' . $uid);
919 PConfig::set($uid, 'twitter', 'lastid', $lastid);
922 function twitter_queue_hook(App $a, &$b)
924 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
925 dbesc(NETWORK_TWITTER)
927 if (!DBA::isResult($qi)) {
931 foreach ($qi as $x) {
932 if ($x['network'] !== NETWORK_TWITTER) {
936 logger('twitter_queue: run');
938 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
939 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
942 if (!DBA::isResult($r)) {
948 $ckey = Config::get('twitter', 'consumerkey');
949 $csecret = Config::get('twitter', 'consumersecret');
950 $otoken = PConfig::get($user['uid'], 'twitter', 'oauthtoken');
951 $osecret = PConfig::get($user['uid'], 'twitter', 'oauthsecret');
955 if ($ckey && $csecret && $otoken && $osecret) {
956 logger('twitter_queue: able to post');
958 $z = unserialize($x['content']);
960 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
961 $result = $connection->post($z['url'], $z['post']);
963 logger('twitter_queue: post result: ' . print_r($result, true), LOGGER_DEBUG);
965 if ($result->errors) {
966 logger('twitter_queue: Send to Twitter failed: "' . print_r($result->errors, true) . '"');
969 Queue::removeItem($x['id']);
972 logger("twitter_queue: Error getting tokens for user " . $user['uid']);
976 logger('twitter_queue: delayed');
977 Queue::updateTime($x['id']);
982 function twitter_fix_avatar($avatar)
984 $new_avatar = str_replace("_normal.", ".", $avatar);
986 $info = Image::getInfoFromURL($new_avatar);
988 $new_avatar = $avatar;
994 function twitter_fetch_contact($uid, $data, $create_user)
996 if ($data->id_str == "") {
1000 $avatar = twitter_fix_avatar($data->profile_image_url_https);
1001 $url = "https://twitter.com/" . $data->screen_name;
1002 $addr = $data->screen_name . "@twitter.com";
1004 GContact::update(["url" => $url, "network" => NETWORK_TWITTER,
1005 "photo" => $avatar, "hide" => true,
1006 "name" => $data->name, "nick" => $data->screen_name,
1007 "location" => $data->location, "about" => $data->description,
1008 "addr" => $addr, "generation" => 2]);
1010 $fields = ['url' => $url, 'network' => NETWORK_TWITTER,
1011 'name' => $data->name, 'nick' => $data->screen_name, 'addr' => $addr,
1012 'location' => $data->location, 'about' => $data->description];
1014 $cid = Contact::getIdForURL($url, 0, true, $fields);
1016 DBA::update('contact', $fields, ['id' => $cid]);
1017 Contact::updateAvatar($avatar, 0, $cid);
1020 $contact = DBA::selectFirst('contact', [], ['uid' => $uid, 'alias' => "twitter::" . $data->id_str]);
1021 if (!DBA::isResult($contact) && !$create_user) {
1025 if (!DBA::isResult($contact)) {
1026 // create contact record
1027 $fields['uid'] = $uid;
1028 $fields['created'] = DateTimeFormat::utcNow();
1029 $fields['nurl'] = normalise_link($url);
1030 $fields['alias'] = 'twitter::' . $data->id_str;
1031 $fields['poll'] = 'twitter::' . $data->id_str;
1032 $fields['rel'] = CONTACT_IS_FRIEND;
1033 $fields['priority'] = 1;
1034 $fields['writable'] = true;
1035 $fields['blocked'] = false;
1036 $fields['readonly'] = false;
1037 $fields['pending'] = false;
1039 if (!DBA::insert('contact', $fields)) {
1043 $contact_id = DBA::lastInsertId();
1045 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1047 Contact::updateAvatar($avatar, $uid, $contact_id);
1049 if ($contact["readonly"] || $contact["blocked"]) {
1050 logger("twitter_fetch_contact: Contact '" . $contact["nick"] . "' is blocked or readonly.", LOGGER_DEBUG);
1054 $contact_id = $contact['id'];
1056 // update profile photos once every twelve hours as we have no notification of when they change.
1057 $update_photo = ($contact['avatar-date'] < DateTimeFormat::utc('now -12 hours'));
1059 // check that we have all the photos, this has been known to fail on occasion
1060 if (empty($contact['photo']) || empty($contact['thumb']) || empty($contact['micro']) || $update_photo) {
1061 logger("twitter_fetch_contact: Updating contact " . $data->screen_name, LOGGER_DEBUG);
1063 Contact::updateAvatar($avatar, $uid, $contact['id']);
1065 $fields['name-date'] = DateTimeFormat::utcNow();
1066 $fields['uri-date'] = DateTimeFormat::utcNow();
1068 DBA::update('contact', $fields, ['id' => $contact['id']]);
1075 function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1077 $ckey = Config::get('twitter', 'consumerkey');
1078 $csecret = Config::get('twitter', 'consumersecret');
1079 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1080 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1082 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1085 if (DBA::isResult($r)) {
1093 if ($screen_name != "") {
1094 $parameters["screen_name"] = $screen_name;
1097 if ($user_id != "") {
1098 $parameters["user_id"] = $user_id;
1101 // Fetching user data
1102 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1104 $user = $connection->get('users/show', $parameters);
1105 } catch (TwitterOAuthException $e) {
1106 logger('twitter_fetchuser: Error fetching user ' . $uid . ': ' . $e->getMessage());
1110 if (!is_object($user)) {
1114 $contact_id = twitter_fetch_contact($uid, $user, true);
1119 function twitter_expand_entities(App $a, $body, $item, $picture)
1125 foreach ($item->entities->hashtags AS $hashtag) {
1126 $url = "#[url=" . $a->get_baseurl() . "/search?tag=" . rawurlencode($hashtag->text) . "]" . $hashtag->text . "[/url]";
1127 $tags_arr["#" . $hashtag->text] = $url;
1128 $body = str_replace("#" . $hashtag->text, $url, $body);
1131 foreach ($item->entities->user_mentions AS $mention) {
1132 $url = "@[url=https://twitter.com/" . rawurlencode($mention->screen_name) . "]" . $mention->screen_name . "[/url]";
1133 $tags_arr["@" . $mention->screen_name] = $url;
1134 $body = str_replace("@" . $mention->screen_name, $url, $body);
1137 if (isset($item->entities->urls)) {
1143 foreach ($item->entities->urls as $url) {
1144 $plain = str_replace($url->url, '', $plain);
1146 if ($url->url && $url->expanded_url && $url->display_url) {
1147 $expanded_url = Network::finalUrl($url->expanded_url);
1149 $oembed_data = OEmbed::fetchURL($expanded_url);
1151 if (empty($oembed_data) || empty($oembed_data->type)) {
1155 // Quickfix: Workaround for URL with "[" and "]" in it
1156 if (strpos($expanded_url, "[") || strpos($expanded_url, "]")) {
1157 $expanded_url = $url->url;
1161 $type = $oembed_data->type;
1164 if ($oembed_data->type == "video") {
1165 //$body = str_replace($url->url,
1166 // "[video]".$expanded_url."[/video]", $body);
1167 //$dontincludemedia = true;
1168 $type = $oembed_data->type;
1169 $footerurl = $expanded_url;
1170 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1172 $body = str_replace($url->url, $footerlink, $body);
1173 //} elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia) {
1174 } elseif (($oembed_data->type == "photo") && isset($oembed_data->url)) {
1175 $body = str_replace($url->url, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1176 //$dontincludemedia = true;
1177 } elseif ($oembed_data->type != "link") {
1178 $body = str_replace($url->url, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1180 $img_str = Network::fetchUrl($expanded_url, true, $redirects, 4);
1182 $tempfile = tempnam(get_temppath(), "cache");
1183 file_put_contents($tempfile, $img_str);
1184 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1187 if (substr($mime, 0, 6) == "image/") {
1189 $body = str_replace($url->url, "[img]" . $expanded_url . "[/img]", $body);
1190 //$dontincludemedia = true;
1192 $type = $oembed_data->type;
1193 $footerurl = $expanded_url;
1194 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1196 $body = str_replace($url->url, $footerlink, $body);
1202 if ($footerurl != "") {
1203 $footer = add_page_info($footerurl, false, $picture);
1206 if (($footerlink != "") && (trim($footer) != "")) {
1207 $removedlink = trim(str_replace($footerlink, "", $body));
1209 if (($removedlink == "") || strstr($body, $removedlink)) {
1210 $body = $removedlink;
1216 if (($footer == "") && ($picture != "")) {
1217 $body .= "\n\n[img]" . $picture . "[/img]\n";
1218 } elseif (($footer == "") && ($picture == "")) {
1219 $body = add_page_info_to_body($body);
1223 // it seems as if the entities aren't always covering all mentions. So the rest will be checked here
1224 $tags = get_tags($body);
1227 foreach ($tags as $tag) {
1228 if (strstr(trim($tag), " ")) {
1232 if (strpos($tag, '#') === 0) {
1233 if (strpos($tag, '[url=')) {
1237 // don't link tags that are already embedded in links
1238 if (preg_match('/\[(.*?)' . preg_quote($tag, '/') . '(.*?)\]/', $body)) {
1241 if (preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag, '/') . '(.*?)\)/', $body)) {
1245 $basetag = str_replace('_', ' ', substr($tag, 1));
1246 $url = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1247 $body = str_replace($tag, $url, $body);
1248 $tags_arr["#" . $basetag] = $url;
1249 } elseif (strpos($tag, '@') === 0) {
1250 if (strpos($tag, '[url=')) {
1254 $basetag = substr($tag, 1);
1255 $url = '@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1256 $body = str_replace($tag, $url, $body);
1257 $tags_arr["@" . $basetag] = $url;
1262 $tags = implode($tags_arr, ",");
1264 return ["body" => $body, "tags" => $tags, "plain" => $plain];
1268 * @brief Fetch media entities and add media links to the body
1270 * @param object $post Twitter object with the post
1271 * @param array $postarray Array of the item that is about to be posted
1273 * @return $picture string Image URL or empty string
1275 function twitter_media_entities($post, &$postarray)
1277 // There are no media entities? So we quit.
1278 if (empty($post->extended_entities->media)) {
1282 // When the post links to an external page, we only take one picture.
1283 // We only do this when there is exactly one media.
1284 if ((count($post->entities->urls) > 0) && (count($post->extended_entities->media) == 1)) {
1286 foreach ($post->extended_entities->media AS $medium) {
1287 if (isset($medium->media_url_https)) {
1288 $picture = $medium->media_url_https;
1289 $postarray['body'] = str_replace($medium->url, "", $postarray['body']);
1295 // This is a pure media post, first search for all media urls
1297 foreach ($post->extended_entities->media AS $medium) {
1298 if (!isset($media[$medium->url])) {
1299 $media[$medium->url] = '';
1301 switch ($medium->type) {
1303 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . "[/img]";
1304 $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
1307 case 'animated_gif':
1308 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . "[/img]";
1309 $postarray['object-type'] = ACTIVITY_OBJ_VIDEO;
1310 if (is_array($medium->video_info->variants)) {
1312 // We take the video with the highest bitrate
1313 foreach ($medium->video_info->variants AS $variant) {
1314 if (($variant->content_type == "video/mp4") && ($variant->bitrate >= $bitrate)) {
1315 $media[$medium->url] = "\n[video]" . $variant->url . "[/video]";
1316 $bitrate = $variant->bitrate;
1321 // The following code will only be activated for test reasons
1323 // $postarray['body'] .= print_r($medium, true);
1327 // Now we replace the media urls.
1328 foreach ($media AS $key => $value) {
1329 $postarray['body'] = str_replace($key, "\n" . $value . "\n", $postarray['body']);
1334 function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact, $noquote)
1337 $postarray['network'] = NETWORK_TWITTER;
1338 $postarray['uid'] = $uid;
1339 $postarray['wall'] = 0;
1340 $postarray['uri'] = "twitter::" . $post->id_str;
1341 // $postarray['object'] = json_encode($post); // Activate for debugging
1343 // Don't import our own comments
1344 if (DBA::exists('item', ['extid' => $postarray['uri'], 'uid' => $uid])) {
1345 logger("Item with extid " . $postarray['uri'] . " found.", LOGGER_DEBUG);
1351 if ($post->in_reply_to_status_id_str != "") {
1352 $parent = "twitter::" . $post->in_reply_to_status_id_str;
1354 $fields = ['uri', 'parent-uri', 'parent'];
1355 $parent_item = Item::selectFirst($fields, ['uri' => $parent, 'uid' => $uid]);
1356 if (!DBA::isResult($parent_item)) {
1357 $parent_item = Item::selectFirst($fields, ['extid' => $parent, 'uid' => $uid]);
1360 if (DBA::isResult($parent_item)) {
1361 $postarray['thr-parent'] = $parent_item['uri'];
1362 $postarray['parent-uri'] = $parent_item['parent-uri'];
1363 $postarray['parent'] = $parent_item['parent'];
1364 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1366 $postarray['thr-parent'] = $postarray['uri'];
1367 $postarray['parent-uri'] = $postarray['uri'];
1368 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1372 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1374 if ($post->user->id_str == $own_id) {
1375 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1378 if (DBA::isResult($r)) {
1379 $contactid = $r[0]["id"];
1381 $postarray['owner-name'] = $r[0]["name"];
1382 $postarray['owner-link'] = $r[0]["url"];
1383 $postarray['owner-avatar'] = $r[0]["photo"];
1385 logger("No self contact for user " . $uid, LOGGER_DEBUG);
1389 // Don't create accounts of people who just comment something
1390 $create_user = false;
1392 $postarray['parent-uri'] = $postarray['uri'];
1393 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1396 if ($contactid == 0) {
1397 $contactid = twitter_fetch_contact($uid, $post->user, $create_user);
1399 $postarray['owner-name'] = $post->user->name;
1400 $postarray['owner-link'] = "https://twitter.com/" . $post->user->screen_name;
1401 $postarray['owner-avatar'] = twitter_fix_avatar($post->user->profile_image_url_https);
1404 if (($contactid == 0) && !$only_existing_contact) {
1405 $contactid = $self['id'];
1406 } elseif ($contactid <= 0) {
1407 logger("Contact ID is zero or less than zero.", LOGGER_DEBUG);
1411 $postarray['contact-id'] = $contactid;
1413 $postarray['verb'] = ACTIVITY_POST;
1414 $postarray['author-name'] = $postarray['owner-name'];
1415 $postarray['author-link'] = $postarray['owner-link'];
1416 $postarray['author-avatar'] = $postarray['owner-avatar'];
1417 $postarray['plink'] = "https://twitter.com/" . $post->user->screen_name . "/status/" . $post->id_str;
1418 $postarray['app'] = strip_tags($post->source);
1420 if ($post->user->protected) {
1421 $postarray['private'] = 1;
1422 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1424 $postarray['private'] = 0;
1425 $postarray['allow_cid'] = '';
1428 if (is_string($post->full_text)) {
1429 $postarray['body'] = $post->full_text;
1431 $postarray['body'] = $post->text;
1434 // When the post contains links then use the correct object type
1435 if (count($post->entities->urls) > 0) {
1436 $postarray['object-type'] = ACTIVITY_OBJ_BOOKMARK;
1439 // Search for media links
1440 $picture = twitter_media_entities($post, $postarray);
1442 $converted = twitter_expand_entities($a, $postarray['body'], $post, $picture);
1443 $postarray['body'] = $converted["body"];
1444 $postarray['tag'] = $converted["tags"];
1445 $postarray['created'] = DateTimeFormat::utc($post->created_at);
1446 $postarray['edited'] = DateTimeFormat::utc($post->created_at);
1448 $statustext = $converted["plain"];
1450 if (!empty($post->place->name)) {
1451 $postarray["location"] = $post->place->name;
1453 if (!empty($post->place->full_name)) {
1454 $postarray["location"] = $post->place->full_name;
1456 if (!empty($post->geo->coordinates)) {
1457 $postarray["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
1459 if (!empty($post->coordinates->coordinates)) {
1460 $postarray["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
1462 if (!empty($post->retweeted_status)) {
1463 $retweet = twitter_createpost($a, $uid, $post->retweeted_status, $self, false, false, $noquote);
1465 //$retweet['object'] = $postarray['object']; // Activate for debugging
1466 $retweet['private'] = $postarray['private'];
1467 $retweet['allow_cid'] = $postarray['allow_cid'];
1468 $retweet['contact-id'] = $postarray['contact-id'];
1469 $retweet['owner-name'] = $postarray['owner-name'];
1470 $retweet['owner-link'] = $postarray['owner-link'];
1471 $retweet['owner-avatar'] = $postarray['owner-avatar'];
1473 $postarray = $retweet;
1476 if (!empty($post->quoted_status) && !$noquote) {
1477 $quoted = twitter_createpost($a, $uid, $post->quoted_status, $self, false, false, true);
1479 $postarray['body'] = $statustext;
1481 $postarray['body'] .= "\n" . share_header(
1482 $quoted['author-name'],
1483 $quoted['author-link'],
1484 $quoted['author-avatar'],
1490 $postarray['body'] .= $quoted['body'] . '[/share]';
1496 function twitter_fetchparentposts(App $a, $uid, $post, TwitterOAuth $connection, $self, $own_id)
1498 logger("twitter_fetchparentposts: Fetching for user " . $uid . " and post " . $post->id_str, LOGGER_DEBUG);
1502 while ($post->in_reply_to_status_id_str != "") {
1503 $parameters = ["trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str];
1506 $post = $connection->get('statuses/show', $parameters);
1507 } catch (TwitterOAuthException $e) {
1508 logger('twitter_fetchparentposts: Error fetching for user ' . $uid . ' and post ' . $post->id_str . ': ' . $e->getMessage());
1513 logger("twitter_fetchparentposts: Can't fetch post " . $parameters->id, LOGGER_DEBUG);
1517 if (DBA::exists('item', ['uri' => 'twitter::' . $post->id_str, 'uid' => $uid])) {
1524 logger("twitter_fetchparentposts: Fetching " . count($posts) . " parents", LOGGER_DEBUG);
1526 $posts = array_reverse($posts);
1528 if (!empty($posts)) {
1529 foreach ($posts as $post) {
1530 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1532 if (empty($postarray['body'])) {
1536 $item = Item::insert($postarray);
1538 $postarray["id"] = $item;
1540 logger('twitter_fetchparentpost: User ' . $self["nick"] . ' posted parent timeline item ' . $item);
1545 function twitter_fetchhometimeline(App $a, $uid)
1547 $ckey = Config::get('twitter', 'consumerkey');
1548 $csecret = Config::get('twitter', 'consumersecret');
1549 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1550 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1551 $create_user = PConfig::get($uid, 'twitter', 'create_user');
1552 $mirror_posts = PConfig::get($uid, 'twitter', 'mirror_posts');
1554 logger("twitter_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG);
1556 $application_name = Config::get('twitter', 'application_name');
1558 if ($application_name == "") {
1559 $application_name = $a->get_hostname();
1562 require_once 'include/items.php';
1564 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1567 $own_contact = twitter_fetch_own_contact($a, $uid);
1568 } catch (TwitterOAuthException $e) {
1569 logger('twitter_fetchhometimeline: Error fetching own contact for user ' . $uid . ': ' . $e->getMessage());
1573 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1574 intval($own_contact),
1577 if (DBA::isResult($r)) {
1578 $own_id = $r[0]["nick"];
1580 logger("twitter_fetchhometimeline: Own twitter contact not found for user " . $uid, LOGGER_DEBUG);
1584 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1587 if (DBA::isResult($r)) {
1590 logger("twitter_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG);
1594 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1596 if (!DBA::isResult($u)) {
1597 logger("twitter_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG);
1601 $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
1602 //$parameters["count"] = 200;
1603 // Fetching timeline
1604 $lastid = PConfig::get($uid, 'twitter', 'lasthometimelineid');
1606 $first_time = ($lastid == "");
1608 if ($lastid != "") {
1609 $parameters["since_id"] = $lastid;
1613 $items = $connection->get('statuses/home_timeline', $parameters);
1614 } catch (TwitterOAuthException $e) {
1615 logger('twitter_fetchhometimeline: Error fetching home timeline: ' . $e->getMessage());
1619 if (!is_array($items)) {
1620 logger("twitter_fetchhometimeline: Error fetching home timeline: " . print_r($items, true), LOGGER_DEBUG);
1624 $posts = array_reverse($items);
1626 logger("twitter_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1628 if (count($posts)) {
1629 foreach ($posts as $post) {
1630 if ($post->id_str > $lastid) {
1631 $lastid = $post->id_str;
1632 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1639 if (stristr($post->source, $application_name) && $post->user->screen_name == $own_id) {
1640 logger("twitter_fetchhometimeline: Skip previously sended post", LOGGER_DEBUG);
1644 if ($mirror_posts && $post->user->screen_name == $own_id && $post->in_reply_to_status_id_str == "") {
1645 logger("twitter_fetchhometimeline: Skip post that will be mirrored", LOGGER_DEBUG);
1649 if ($post->in_reply_to_status_id_str != "") {
1650 twitter_fetchparentposts($a, $uid, $post, $connection, $self, $own_id);
1653 $postarray = twitter_createpost($a, $uid, $post, $self, $create_user, true, false);
1655 if (empty($postarray['body']) || trim($postarray['body']) == "") {
1661 if ($postarray['uri'] == $postarray['parent-uri']) {
1662 $contact = DBA::selectFirst('contact', [], ['id' => $postarray['contact-id'], 'self' => false]);
1663 if (DBA::isResult($contact)) {
1664 $notify = Item::isRemoteSelf($contact, $postarray);
1668 $item = Item::insert($postarray, false, $notify);
1669 $postarray["id"] = $item;
1671 logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1674 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1676 // Fetching mentions
1677 $lastid = PConfig::get($uid, 'twitter', 'lastmentionid');
1679 $first_time = ($lastid == "");
1681 if ($lastid != "") {
1682 $parameters["since_id"] = $lastid;
1686 $items = $connection->get('statuses/mentions_timeline', $parameters);
1687 } catch (TwitterOAuthException $e) {
1688 logger('twitter_fetchhometimeline: Error fetching mentions: ' . $e->getMessage());
1692 if (!is_array($items)) {
1693 logger("twitter_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG);
1697 $posts = array_reverse($items);
1699 logger("twitter_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1701 if (count($posts)) {
1702 foreach ($posts as $post) {
1703 if ($post->id_str > $lastid) {
1704 $lastid = $post->id_str;
1711 if ($post->in_reply_to_status_id_str != "") {
1712 twitter_fetchparentposts($a, $uid, $post, $connection, $self, $own_id);
1715 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1717 if (trim($postarray['body']) == "") {
1721 $item = Item::insert($postarray);
1723 logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1727 PConfig::set($uid, 'twitter', 'lastmentionid', $lastid);
1730 function twitter_fetch_own_contact(App $a, $uid)
1732 $ckey = Config::get('twitter', 'consumerkey');
1733 $csecret = Config::get('twitter', 'consumersecret');
1734 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1735 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1737 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1741 if ($own_id == "") {
1742 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1744 // Fetching user data
1745 // get() may throw TwitterOAuthException, but we will catch it later
1746 $user = $connection->get('account/verify_credentials');
1748 PConfig::set($uid, 'twitter', 'own_id', $user->id_str);
1750 $contact_id = twitter_fetch_contact($uid, $user, true);
1752 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1754 dbesc("twitter::" . $own_id));
1755 if (DBA::isResult($r)) {
1756 $contact_id = $r[0]["id"];
1758 PConfig::delete($uid, 'twitter', 'own_id');
1765 function twitter_is_retweet(App $a, $uid, $body)
1767 $body = trim($body);
1769 // Skip if it isn't a pure repeated messages
1770 // Does it start with a share?
1771 if (strpos($body, "[share") > 0) {
1775 // Does it end with a share?
1776 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1780 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1781 // Skip if there is no shared message in there
1782 if ($body == $attributes) {
1787 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1788 if (!empty($matches[1])) {
1789 $link = $matches[1];
1792 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1793 if (!empty($matches[1])) {
1794 $link = $matches[1];
1797 $id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link);
1802 logger('twitter_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG);
1804 $ckey = Config::get('twitter', 'consumerkey');
1805 $csecret = Config::get('twitter', 'consumersecret');
1806 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1807 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1809 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1810 $result = $connection->post('statuses/retweet/' . $id);
1812 logger('twitter_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);
1814 return !isset($result->errors);