3 * Name: Twitter Connector
4 * Description: Bidirectional (posting, relaying and reading) connector for Twitter.
6 * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8 * Maintainer: Hypolite Petovan <https://friendica.mrpetovan.com/profile/hypolite>
10 * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel, Hypolite Petovan
11 * All rights reserved.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions are met:
15 * * Redistributions of source code must retain the above copyright notice,
16 * this list of conditions and the following disclaimer.
17 * * Redistributions in binary form must reproduce the above
18 * * copyright notice, this list of conditions and the following disclaimer in
19 * the documentation and/or other materials provided with the distribution.
20 * * Neither the name of the <organization> nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
28 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
32 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
36 /* Twitter Addon for Friendica
38 * Author: Tobias Diekershoff
39 * tobias.diekershoff@gmx.net
41 * License:3-clause BSD license
44 * To use this addon you need a OAuth Consumer key pair (key & secret)
45 * you can get it from Twitter at https://twitter.com/apps
47 * Register your Friendica site as "Client" application with "Read & Write" access
48 * we do not need "Twitter as login". When you've registered the app you get the
49 * OAuth Consumer key and secret pair for your application/site.
51 * Add this key pair to your global .htconfig.php or use the admin panel.
53 * $a->config['twitter']['consumerkey'] = 'your consumer_key here';
54 * $a->config['twitter']['consumersecret'] = 'your consumer_secret here';
56 * To activate the addon itself add it to the $a->config['system']['addon']
57 * setting. After this, your user can configure their Twitter account settings
58 * from "Settings -> Addon Settings".
60 * Requirements: PHP5, curl
63 use Abraham\TwitterOAuth\TwitterOAuth;
65 use Friendica\Content\OEmbed;
66 use Friendica\Content\Text\Plaintext;
67 use Friendica\Core\Addon;
68 use Friendica\Core\Config;
69 use Friendica\Core\L10n;
70 use Friendica\Core\PConfig;
71 use Friendica\Core\Worker;
72 use Friendica\Model\GContact;
73 use Friendica\Model\Group;
74 use Friendica\Model\Item;
75 use Friendica\Model\ItemContent;
76 use Friendica\Model\Photo;
77 use Friendica\Model\Queue;
78 use Friendica\Model\User;
79 use Friendica\Object\Image;
80 use Friendica\Util\DateTimeFormat;
81 use Friendica\Util\Network;
82 use Friendica\Database\DBM;
84 require_once 'boot.php';
85 require_once 'include/dba.php';
86 require_once 'include/enotify.php';
87 require_once 'include/text.php';
89 require_once __DIR__ . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'autoload.php';
91 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
93 function twitter_install()
95 // we need some hooks, for the configuration and for sending tweets
96 Addon::registerHook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings');
97 Addon::registerHook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
98 Addon::registerHook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
99 Addon::registerHook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
100 Addon::registerHook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
101 Addon::registerHook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
102 Addon::registerHook('queue_predeliver', 'addon/twitter/twitter.php', 'twitter_queue_hook');
103 Addon::registerHook('follow', 'addon/twitter/twitter.php', 'twitter_follow');
104 Addon::registerHook('expire', 'addon/twitter/twitter.php', 'twitter_expire');
105 Addon::registerHook('prepare_body', 'addon/twitter/twitter.php', 'twitter_prepare_body');
106 Addon::registerHook('check_item_notification', 'addon/twitter/twitter.php', 'twitter_check_item_notification');
107 logger("installed twitter");
110 function twitter_uninstall()
112 Addon::unregisterHook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings');
113 Addon::unregisterHook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
114 Addon::unregisterHook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
115 Addon::unregisterHook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
116 Addon::unregisterHook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
117 Addon::unregisterHook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
118 Addon::unregisterHook('queue_predeliver', 'addon/twitter/twitter.php', 'twitter_queue_hook');
119 Addon::unregisterHook('follow', 'addon/twitter/twitter.php', 'twitter_follow');
120 Addon::unregisterHook('expire', 'addon/twitter/twitter.php', 'twitter_expire');
121 Addon::unregisterHook('prepare_body', 'addon/twitter/twitter.php', 'twitter_prepare_body');
122 Addon::unregisterHook('check_item_notification', 'addon/twitter/twitter.php', 'twitter_check_item_notification');
124 // old setting - remove only
125 Addon::unregisterHook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
126 Addon::unregisterHook('addon_settings', 'addon/twitter/twitter.php', 'twitter_settings');
127 Addon::unregisterHook('addon_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
130 function twitter_check_item_notification(App $a, &$notification_data)
132 $own_id = PConfig::get($notification_data["uid"], 'twitter', 'own_id');
134 $own_user = q("SELECT `url` FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
135 intval($notification_data["uid"]),
136 dbesc("twitter::".$own_id)
140 $notification_data["profiles"][] = $own_user[0]["url"];
144 function twitter_follow(App $a, &$contact)
146 logger("twitter_follow: Check if contact is twitter contact. " . $contact["url"], LOGGER_DEBUG);
148 if (!strstr($contact["url"], "://twitter.com") && !strstr($contact["url"], "@twitter.com")) {
152 // contact seems to be a twitter contact, so continue
153 $nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $contact["url"]);
154 $nickname = str_replace("@twitter.com", "", $nickname);
156 $uid = $a->user["uid"];
158 $ckey = Config::get('twitter', 'consumerkey');
159 $csecret = Config::get('twitter', 'consumersecret');
160 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
161 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
163 // If the addon is not configured (general or for this user) quit here
164 if (empty($ckey) || empty($csecret) || empty($otoken) || empty($osecret)) {
169 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
170 $connection->post('friendships/create', ['screen_name' => $nickname]);
172 twitter_fetchuser($a, $uid, $nickname);
174 $r = q("SELECT name,nick,url,addr,batch,notify,poll,request,confirm,poco,photo,priority,network,alias,pubkey
175 FROM `contact` WHERE `uid` = %d AND `nick` = '%s'",
179 $contact["contact"] = $r[0];
183 function twitter_jot_nets(App $a, &$b)
189 $tw_post = PConfig::get(local_user(), 'twitter', 'post');
190 if (intval($tw_post) == 1) {
191 $tw_defpost = PConfig::get(local_user(), 'twitter', 'post_by_default');
192 $selected = ((intval($tw_defpost) == 1) ? ' checked="checked" ' : '');
193 $b .= '<div class="profile-jot-net"><input type="checkbox" name="twitter_enable"' . $selected . ' value="1" /> '
194 . L10n::t('Post to Twitter') . '</div>';
198 function twitter_settings_post(App $a, $post)
203 // don't check twitter settings if twitter submit button is not clicked
204 if (empty($_POST['twitter-disconnect']) && empty($_POST['twitter-submit'])) {
208 if (!empty($_POST['twitter-disconnect'])) {
210 * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
211 * from the user configuration
213 PConfig::delete(local_user(), 'twitter', 'consumerkey');
214 PConfig::delete(local_user(), 'twitter', 'consumersecret');
215 PConfig::delete(local_user(), 'twitter', 'oauthtoken');
216 PConfig::delete(local_user(), 'twitter', 'oauthsecret');
217 PConfig::delete(local_user(), 'twitter', 'post');
218 PConfig::delete(local_user(), 'twitter', 'post_by_default');
219 PConfig::delete(local_user(), 'twitter', 'lastid');
220 PConfig::delete(local_user(), 'twitter', 'mirror_posts');
221 PConfig::delete(local_user(), 'twitter', 'import');
222 PConfig::delete(local_user(), 'twitter', 'create_user');
223 PConfig::delete(local_user(), 'twitter', 'own_id');
225 if (isset($_POST['twitter-pin'])) {
226 // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
227 logger('got a Twitter PIN');
228 $ckey = Config::get('twitter', 'consumerkey');
229 $csecret = Config::get('twitter', 'consumersecret');
230 // the token and secret for which the PIN was generated were hidden in the settings
231 // form as token and token2, we need a new connection to Twitter using these token
232 // and secret to request a Access Token with the PIN
234 if (empty($_POST['twitter-pin'])) {
235 throw new Exception(L10n::t('You submitted an empty PIN, please Sign In with Twitter again to get a new one.'));
238 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
239 $token = $connection->oauth("oauth/access_token", ["oauth_verifier" => $_POST['twitter-pin']]);
240 // ok, now that we have the Access Token, save them in the user config
241 PConfig::set(local_user(), 'twitter', 'oauthtoken', $token['oauth_token']);
242 PConfig::set(local_user(), 'twitter', 'oauthsecret', $token['oauth_token_secret']);
243 PConfig::set(local_user(), 'twitter', 'post', 1);
244 } catch(Exception $e) {
245 info($e->getMessage());
247 // reload the Addon Settings page, if we don't do it see Bug #42
248 goaway('settings/connectors');
250 // if no PIN is supplied in the POST variables, the user has changed the setting
251 // to post a tweet for every new __public__ posting to the wall
252 PConfig::set(local_user(), 'twitter', 'post', intval($_POST['twitter-enable']));
253 PConfig::set(local_user(), 'twitter', 'post_by_default', intval($_POST['twitter-default']));
254 PConfig::set(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror']));
255 PConfig::set(local_user(), 'twitter', 'import', intval($_POST['twitter-import']));
256 PConfig::set(local_user(), 'twitter', 'create_user', intval($_POST['twitter-create_user']));
258 if (!intval($_POST['twitter-mirror'])) {
259 PConfig::delete(local_user(), 'twitter', 'lastid');
262 info(L10n::t('Twitter settings updated.') . EOL);
267 function twitter_settings(App $a, &$s)
272 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
274 * 1) Check that we have global consumer key & secret
275 * 2) If no OAuthtoken & stuff is present, generate button to get some
276 * 3) Checkbox for "Send public notices (280 chars only)
278 $ckey = Config::get('twitter', 'consumerkey');
279 $csecret = Config::get('twitter', 'consumersecret');
280 $otoken = PConfig::get(local_user(), 'twitter', 'oauthtoken');
281 $osecret = PConfig::get(local_user(), 'twitter', 'oauthsecret');
283 $enabled = intval(PConfig::get(local_user(), 'twitter', 'post'));
284 $defenabled = intval(PConfig::get(local_user(), 'twitter', 'post_by_default'));
285 $mirrorenabled = intval(PConfig::get(local_user(), 'twitter', 'mirror_posts'));
286 $importenabled = intval(PConfig::get(local_user(), 'twitter', 'import'));
287 $create_userenabled = intval(PConfig::get(local_user(), 'twitter', 'create_user'));
289 $css = (($enabled) ? '' : '-disabled');
291 $s .= '<span id="settings_twitter_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
292 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
294 $s .= '<div id="settings_twitter_expanded" class="settings-block" style="display: none;">';
295 $s .= '<span class="fakelink" onclick="openClose(\'settings_twitter_expanded\'); openClose(\'settings_twitter_inflated\');">';
296 $s .= '<img class="connector' . $css . '" src="images/twitter.png" /><h3 class="connector">' . L10n::t('Twitter Import/Export/Mirror') . '</h3>';
299 if ((!$ckey) && (!$csecret)) {
300 /* no global consumer keys
301 * display warning and skip personal config
303 $s .= '<p>' . L10n::t('No consumer key pair for Twitter found. Please contact your site administrator.') . '</p>';
305 // ok we have a consumer key pair now look into the OAuth stuff
306 if ((!$otoken) && (!$osecret)) {
307 /* the user has not yet connected the account to twitter...
308 * get a temporary OAuth key/secret pair and display a button with
309 * which the user can request a PIN to connect the account to a
310 * account at Twitter.
312 $connection = new TwitterOAuth($ckey, $csecret);
313 $result = $connection->oauth('oauth/request_token', ['oauth_callback' => 'oob']);
315 $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>';
316 $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>';
317 $s .= '<div id="twitter-pin-wrapper">';
318 $s .= '<label id="twitter-pin-label" for="twitter-pin">' . L10n::t('Copy the PIN from Twitter here') . '</label>';
319 $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
320 $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="' . $result['oauth_token'] . '" />';
321 $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="' . $result['oauth_token_secret'] . '" />';
322 $s .= '</div><div class="clear"></div>';
323 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
326 * we have an OAuth key / secret pair for the user
327 * so let's give a chance to disable the postings to Twitter
329 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
330 $details = $connection->get('account/verify_credentials');
332 $field_checkbox = get_markup_template('field_checkbox.tpl');
334 $s .= '<div id="twitter-info" >
335 <p>' . L10n::t('Currently connected to: ') . '<a href="https://twitter.com/' . $details->screen_name . '" target="_twitter">' . $details->screen_name . '</a>
336 <button type="submit" name="twitter-disconnect" value="1">' . L10n::t('Disconnect') . '</button>
338 <p id="twitter-info-block">
339 <a href="https://twitter.com/' . $details->screen_name . '" target="_twitter"><img id="twitter-avatar" src="' . $details->profile_image_url . '" /></a>
340 <em>' . $details->description . '</em>
343 $s .= '<div class="clear"></div>';
345 $s .= replace_macros($field_checkbox, [
346 '$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.')]
348 if ($a->user['hidewall']) {
349 $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>';
351 $s .= replace_macros($field_checkbox, [
352 '$field' => ['twitter-default', L10n::t('Send public postings to Twitter by default'), $defenabled, '']
354 $s .= replace_macros($field_checkbox, [
355 '$field' => ['twitter-mirror', L10n::t('Mirror all posts from twitter that are no replies'), $mirrorenabled, '']
357 $s .= replace_macros($field_checkbox, [
358 '$field' => ['twitter-import', L10n::t('Import the remote timeline'), $importenabled, '']
360 $s .= replace_macros($field_checkbox, [
361 '$field' => ['twitter-create_user', L10n::t('Automatically create contacts'), $create_userenabled, '']
364 $s .= '<div class="clear"></div>';
365 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . L10n::t('Save Settings') . '" /></div>';
368 $s .= '</div><div class="clear"></div>';
371 function twitter_post_local(App $a, &$b)
377 if (!local_user() || (local_user() != $b['uid'])) {
381 $twitter_post = intval(PConfig::get(local_user(), 'twitter', 'post'));
382 $twitter_enable = (($twitter_post && x($_REQUEST, 'twitter_enable')) ? intval($_REQUEST['twitter_enable']) : 0);
384 // if API is used, default to the chosen settings
385 if ($b['api_source'] && intval(PConfig::get(local_user(), 'twitter', 'post_by_default'))) {
389 if (!$twitter_enable) {
393 if (strlen($b['postopts'])) {
394 $b['postopts'] .= ',';
397 $b['postopts'] .= 'twitter';
400 function twitter_action(App $a, $uid, $pid, $action)
402 $ckey = Config::get('twitter', 'consumerkey');
403 $csecret = Config::get('twitter', 'consumersecret');
404 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
405 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
407 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
409 $post = ['id' => $pid];
411 logger("twitter_action '" . $action . "' ID: " . $pid . " data: " . print_r($post, true), LOGGER_DATA);
415 // To-Do: $result = $connection->post('statuses/destroy', $post);
418 $result = $connection->post('favorites/create', $post);
421 $result = $connection->post('favorites/destroy', $post);
424 logger("twitter_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG);
427 function twitter_post_hook(App $a, &$b)
430 if (!PConfig::get($b["uid"], 'twitter', 'import')
431 && ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))) {
435 if ($b['parent'] != $b['id']) {
436 logger("twitter_post_hook: parameter " . print_r($b, true), LOGGER_DATA);
438 // Looking if its a reply to a twitter post
439 if ((substr($b["parent-uri"], 0, 9) != "twitter::")
440 && (substr($b["extid"], 0, 9) != "twitter::")
441 && (substr($b["thr-parent"], 0, 9) != "twitter::"))
443 logger("twitter_post_hook: no twitter post " . $b["parent"]);
447 $r = q("SELECT * FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
448 dbesc($b["thr-parent"]),
452 logger("twitter_post_hook: no parent found " . $b["thr-parent"]);
460 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
461 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
462 $nicknameplain = "@" . $nicknameplain;
464 logger("twitter_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], LOGGER_DEBUG);
465 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false)) {
466 $b["body"] = $nickname . " " . $b["body"];
469 logger("twitter_post_hook: parent found " . print_r($orig_post, true), LOGGER_DATA);
473 if ($b['private'] || !strstr($b['postopts'], 'twitter')) {
477 // Dont't post if the post doesn't belong to us.
478 // This is a check for forum postings
479 $self = dba::selectFirst('contact', ['id'], ['uid' => $b['uid'], 'self' => true]);
480 if ($b['contact-id'] != $self['id']) {
485 if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
486 twitter_action($a, $b["uid"], substr($orig_post["uri"], 9), "delete");
489 if ($b['verb'] == ACTIVITY_LIKE) {
490 logger("twitter_post_hook: parameter 2 " . substr($b["thr-parent"], 9), LOGGER_DEBUG);
492 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "unlike");
494 twitter_action($a, $b["uid"], substr($b["thr-parent"], 9), "like");
500 if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
504 // if post comes from twitter don't send it back
505 if ($b['extid'] == NETWORK_TWITTER) {
509 if ($b['app'] == "Twitter") {
513 logger('twitter post invoked');
515 PConfig::load($b['uid'], 'twitter');
517 $ckey = Config::get('twitter', 'consumerkey');
518 $csecret = Config::get('twitter', 'consumersecret');
519 $otoken = PConfig::get($b['uid'], 'twitter', 'oauthtoken');
520 $osecret = PConfig::get($b['uid'], 'twitter', 'oauthsecret');
522 if ($ckey && $csecret && $otoken && $osecret) {
523 logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
525 // If it's a repeated message from twitter then do a native retweet and exit
526 if (twitter_is_retweet($a, $b['uid'], $b['body'])) {
530 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
532 // Set the timeout for upload to 30 seconds
533 $connection->setTimeouts(10, 30);
536 $msgarr = ItemContent::getPlaintextPost($b, $max_char, true, 8);
537 $msg = $msgarr["text"];
539 if (($msg == "") && isset($msgarr["title"])) {
540 $msg = Plaintext::shorten($msgarr["title"], $max_char - 50);
545 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
546 $msg .= "\n" . $msgarr["url"];
552 if (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
553 $image = $msgarr["image"];
560 // and now tweet it :-)
563 if (!empty($image)) {
565 $img_str = Network::fetchUrl($image);
567 $tempfile = tempnam(get_temppath(), 'cache');
568 file_put_contents($tempfile, $img_str);
570 $media = $connection->upload('media/upload', ['media' => $tempfile]);
574 $post['media_ids'] = $media->media_id_string;
575 } catch (Exception $e) {
576 logger('Exception when trying to send to Twitter: ' . $e->getMessage());
578 // Workaround: Remove the picture link so that the post can be reposted without it
579 // When there is another url already added, a second url would be superfluous.
581 $msg .= "\n" . $image;
588 $post['status'] = $msg;
591 $post["in_reply_to_status_id"] = substr($orig_post["uri"], 9);
594 $url = 'statuses/update';
595 $result = $connection->post($url, $post);
596 logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG);
598 if ($result->source) {
599 Config::set("twitter", "application_name", strip_tags($result->source));
602 if ($result->errors) {
603 logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
605 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
607 $a->contact = $r[0]["id"];
610 $s = serialize(['url' => $url, 'item' => $b['id'], 'post' => $post]);
612 Queue::add($a->contact, NETWORK_TWITTER, $s);
613 notice(L10n::t('Twitter post failed. Queued for retry.') . EOL);
614 } elseif ($iscomment) {
615 logger('twitter_post: Update extid ' . $result->id_str . " for post id " . $b['id']);
616 Item::update(['extid' => "twitter::" . $result->id_str], ['id' => $b['id']]);
621 function twitter_addon_admin_post(App $a)
623 $consumerkey = x($_POST, 'consumerkey') ? notags(trim($_POST['consumerkey'])) : '';
624 $consumersecret = x($_POST, 'consumersecret') ? notags(trim($_POST['consumersecret'])) : '';
625 Config::set('twitter', 'consumerkey', $consumerkey);
626 Config::set('twitter', 'consumersecret', $consumersecret);
627 info(L10n::t('Settings updated.') . EOL);
630 function twitter_addon_admin(App $a, &$o)
632 $t = get_markup_template("admin.tpl", "addon/twitter/");
634 $o = replace_macros($t, [
635 '$submit' => L10n::t('Save Settings'),
636 // name, label, value, help, [extra values]
637 '$consumerkey' => ['consumerkey', L10n::t('Consumer key'), Config::get('twitter', 'consumerkey'), ''],
638 '$consumersecret' => ['consumersecret', L10n::t('Consumer secret'), Config::get('twitter', 'consumersecret'), ''],
642 function twitter_cron(App $a, $b)
644 $last = Config::get('twitter', 'last_poll');
646 $poll_interval = intval(Config::get('twitter', 'poll_interval'));
647 if (!$poll_interval) {
648 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
652 $next = $last + ($poll_interval * 60);
653 if ($next > time()) {
654 logger('twitter: poll intervall not reached');
658 logger('twitter: cron_start');
660 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1'");
662 foreach ($r as $rr) {
663 logger('twitter: fetching for user ' . $rr['uid']);
664 Worker::add(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 1, (int) $rr['uid']);
668 $abandon_days = intval(Config::get('system', 'account_abandon_days'));
669 if ($abandon_days < 1) {
673 $abandon_limit = date(DateTimeFormat::MYSQL, time() - $abandon_days * 86400);
675 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1'");
677 foreach ($r as $rr) {
678 if ($abandon_days != 0) {
679 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
681 logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
686 logger('twitter: importing timeline from user ' . $rr['uid']);
687 Worker::add(PRIORITY_MEDIUM, "addon/twitter/twitter_sync.php", 2, (int) $rr['uid']);
690 // check for new contacts once a day
691 $last_contact_check = PConfig::get($rr['uid'],'pumpio','contact_check');
692 if($last_contact_check)
693 $next_contact_check = $last_contact_check + 86400;
695 $next_contact_check = 0;
697 if($next_contact_check <= time()) {
698 pumpio_getallusers($a, $rr["uid"]);
699 PConfig::set($rr['uid'],'pumpio','contact_check',time());
705 logger('twitter: cron_end');
707 Config::set('twitter', 'last_poll', time());
710 function twitter_expire(App $a, $b)
712 $days = Config::get('twitter', 'expire');
718 if (method_exists('dba', 'delete')) {
719 $r = dba::select('item', ['id'], ['deleted' => true, 'network' => NETWORK_TWITTER]);
720 while ($row = dba::fetch($r)) {
721 dba::delete('item', ['id' => $row['id']]);
725 $r = q("DELETE FROM `item` WHERE `deleted` AND `network` = '%s'", dbesc(NETWORK_TWITTER));
728 require_once "include/items.php";
730 logger('twitter_expire: expire_start');
732 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
734 foreach ($r as $rr) {
735 logger('twitter_expire: user ' . $rr['uid']);
736 Item::expire($rr['uid'], $days, NETWORK_TWITTER, true);
740 logger('twitter_expire: expire_end');
743 function twitter_prepare_body(App $a, &$b)
745 if ($b["item"]["network"] != NETWORK_TWITTER) {
752 $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
754 $r = q("SELECT `author-link` FROM item WHERE item.uri = '%s' AND item.uid = %d LIMIT 1",
755 dbesc($item["thr-parent"]),
756 intval(local_user()));
761 $nicknameplain = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
762 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nicknameplain . "[/url]";
763 $nicknameplain = "@" . $nicknameplain;
765 if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
766 $item["body"] = $nickname . " " . $item["body"];
770 $msgarr = ItemContent::getPlaintextPost($item, $max_char, true, 8);
771 $msg = $msgarr["text"];
773 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
774 $msg .= " " . $msgarr["url"];
777 if (isset($msgarr["image"])) {
778 $msg .= " " . $msgarr["image"];
781 $b['html'] = nl2br(htmlspecialchars($msg));
786 * @brief Build the item array for the mirrored post
788 * @param App $a Application class
789 * @param integer $uid User id
790 * @param object $post Twitter object with the post
792 * @return array item data to be posted
794 function twitter_do_mirrorpost(App $a, $uid, $post)
796 $datarray["type"] = "wall";
797 $datarray["api_source"] = true;
798 $datarray["profile_uid"] = $uid;
799 $datarray["extid"] = NETWORK_TWITTER;
800 $datarray['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_TWITTER . ":" . $post->id);
801 $datarray['object'] = json_encode($post);
802 $datarray["title"] = "";
804 if (is_object($post->retweeted_status)) {
805 // We don't support nested shares, so we mustn't show quotes as shares on retweets
806 $item = twitter_createpost($a, $uid, $post->retweeted_status, ['id' => 0], false, false, true);
808 $datarray['body'] = "\n" . share_header(
809 $item['author-name'],
810 $item['author-link'],
811 $item['author-avatar'],
817 $datarray['body'] .= $item['body'] . '[/share]';
819 $item = twitter_createpost($a, $uid, $post, ['id' => 0], false, false, false);
821 $datarray['body'] = $item['body'];
824 $datarray["source"] = $item['app'];
825 $datarray["verb"] = $item['verb'];
827 if (isset($item["location"])) {
828 $datarray["location"] = $item["location"];
831 if (isset($item["coord"])) {
832 $datarray["coord"] = $item["coord"];
838 function twitter_fetchtimeline(App $a, $uid)
840 $ckey = Config::get('twitter', 'consumerkey');
841 $csecret = Config::get('twitter', 'consumersecret');
842 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
843 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
844 $lastid = PConfig::get($uid, 'twitter', 'lastid');
846 $application_name = Config::get('twitter', 'application_name');
848 if ($application_name == "") {
849 $application_name = $a->get_hostname();
852 $has_picture = false;
854 require_once 'mod/item.php';
855 require_once 'include/items.php';
856 require_once 'mod/share.php';
858 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
860 $parameters = ["exclude_replies" => true, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
862 $first_time = ($lastid == "");
865 $parameters["since_id"] = $lastid;
868 $items = $connection->get('statuses/user_timeline', $parameters);
870 if (!is_array($items)) {
874 $posts = array_reverse($items);
877 foreach ($posts as $post) {
878 if ($post->id_str > $lastid) {
879 $lastid = $post->id_str;
880 PConfig::set($uid, 'twitter', 'lastid', $lastid);
887 if (!stristr($post->source, $application_name)) {
888 $_SESSION["authenticated"] = true;
889 $_SESSION["uid"] = $uid;
891 $_REQUEST = twitter_do_mirrorpost($a, $uid, $post);
893 logger('twitter: posting for user ' . $uid);
899 PConfig::set($uid, 'twitter', 'lastid', $lastid);
902 function twitter_queue_hook(App $a, &$b)
904 $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
905 dbesc(NETWORK_TWITTER)
911 foreach ($qi as $x) {
912 if ($x['network'] !== NETWORK_TWITTER) {
916 logger('twitter_queue: run');
918 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
919 WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
928 $ckey = Config::get('twitter', 'consumerkey');
929 $csecret = Config::get('twitter', 'consumersecret');
930 $otoken = PConfig::get($user['uid'], 'twitter', 'oauthtoken');
931 $osecret = PConfig::get($user['uid'], 'twitter', 'oauthsecret');
935 if ($ckey && $csecret && $otoken && $osecret) {
936 logger('twitter_queue: able to post');
938 $z = unserialize($x['content']);
940 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
941 $result = $connection->post($z['url'], $z['post']);
943 logger('twitter_queue: post result: ' . print_r($result, true), LOGGER_DEBUG);
945 if ($result->errors) {
946 logger('twitter_queue: Send to Twitter failed: "' . print_r($result->errors, true) . '"');
949 Queue::removeItem($x['id']);
952 logger("twitter_queue: Error getting tokens for user " . $user['uid']);
956 logger('twitter_queue: delayed');
957 Queue::updateTime($x['id']);
962 function twitter_fix_avatar($avatar)
964 $new_avatar = str_replace("_normal.", ".", $avatar);
966 $info = Image::getInfoFromURL($new_avatar);
968 $new_avatar = $avatar;
974 function twitter_fetch_contact($uid, $contact, $create_user)
976 if ($contact->id_str == "") {
980 $avatar = twitter_fix_avatar($contact->profile_image_url_https);
982 GContact::update(["url" => "https://twitter.com/" . $contact->screen_name,
983 "network" => NETWORK_TWITTER, "photo" => $avatar, "hide" => true,
984 "name" => $contact->name, "nick" => $contact->screen_name,
985 "location" => $contact->location, "about" => $contact->description,
986 "addr" => $contact->screen_name . "@twitter.com", "generation" => 2]);
988 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
990 dbesc("twitter::" . $contact->id_str));
992 if (!count($r) && !$create_user) {
996 if (count($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
997 logger("twitter_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", LOGGER_DEBUG);
1002 // create contact record
1003 q("INSERT INTO `contact` (`uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1004 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1005 `location`, `about`, `writable`, `blocked`, `readonly`, `pending`)
1006 VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0)",
1008 dbesc(DateTimeFormat::utcNow()),
1009 dbesc("https://twitter.com/" . $contact->screen_name),
1010 dbesc(normalise_link("https://twitter.com/" . $contact->screen_name)),
1011 dbesc($contact->screen_name."@twitter.com"),
1012 dbesc("twitter::" . $contact->id_str),
1014 dbesc("twitter::" . $contact->id_str),
1015 dbesc($contact->name),
1016 dbesc($contact->screen_name),
1018 dbesc(NETWORK_TWITTER),
1019 intval(CONTACT_IS_FRIEND),
1021 dbesc($contact->location),
1022 dbesc($contact->description),
1026 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
1027 dbesc("twitter::".$contact->id_str),
1035 $contact_id = $r[0]['id'];
1037 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1039 $photos = Photo::importProfilePhoto($avatar, $uid, $contact_id, true);
1042 q("UPDATE `contact` SET `photo` = '%s',
1047 `avatar-date` = '%s'
1052 dbesc(DateTimeFormat::utcNow()),
1053 dbesc(DateTimeFormat::utcNow()),
1054 dbesc(DateTimeFormat::utcNow()),
1059 // update profile photos once every two weeks as we have no notification of when they change.
1060 //$update_photo = (($r[0]['avatar-date'] < DateTimeFormat::convert('now -2 days', '', '', )) ? true : false);
1061 $update_photo = ($r[0]['avatar-date'] < DateTimeFormat::utc('now -12 hours'));
1063 // check that we have all the photos, this has been known to fail on occasion
1064 if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1065 logger("twitter_fetch_contact: Updating contact " . $contact->screen_name, LOGGER_DEBUG);
1067 $photos = Photo::importProfilePhoto($avatar, $uid, $r[0]['id'], true);
1070 q("UPDATE `contact` SET `photo` = '%s',
1075 `avatar-date` = '%s',
1087 dbesc(DateTimeFormat::utcNow()),
1088 dbesc(DateTimeFormat::utcNow()),
1089 dbesc(DateTimeFormat::utcNow()),
1090 dbesc("https://twitter.com/".$contact->screen_name),
1091 dbesc(normalise_link("https://twitter.com/".$contact->screen_name)),
1092 dbesc($contact->screen_name."@twitter.com"),
1093 dbesc($contact->name),
1094 dbesc($contact->screen_name),
1095 dbesc($contact->location),
1096 dbesc($contact->description),
1106 function twitter_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1108 $ckey = Config::get('twitter', 'consumerkey');
1109 $csecret = Config::get('twitter', 'consumersecret');
1110 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1111 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1113 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1124 if ($screen_name != "") {
1125 $parameters["screen_name"] = $screen_name;
1128 if ($user_id != "") {
1129 $parameters["user_id"] = $user_id;
1132 // Fetching user data
1133 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1134 $user = $connection->get('users/show', $parameters);
1136 if (!is_object($user)) {
1140 $contact_id = twitter_fetch_contact($uid, $user, true);
1145 function twitter_expand_entities(App $a, $body, $item, $picture)
1151 foreach ($item->entities->hashtags AS $hashtag) {
1152 $url = "#[url=" . $a->get_baseurl() . "/search?tag=" . rawurlencode($hashtag->text) . "]" . $hashtag->text . "[/url]";
1153 $tags_arr["#" . $hashtag->text] = $url;
1154 $body = str_replace("#" . $hashtag->text, $url, $body);
1157 foreach ($item->entities->user_mentions AS $mention) {
1158 $url = "@[url=https://twitter.com/" . rawurlencode($mention->screen_name) . "]" . $mention->screen_name . "[/url]";
1159 $tags_arr["@" . $mention->screen_name] = $url;
1160 $body = str_replace("@" . $mention->screen_name, $url, $body);
1163 if (isset($item->entities->urls)) {
1169 foreach ($item->entities->urls as $url) {
1170 $plain = str_replace($url->url, '', $plain);
1172 if ($url->url && $url->expanded_url && $url->display_url) {
1173 $expanded_url = Network::finalUrl($url->expanded_url);
1175 $oembed_data = OEmbed::fetchURL($expanded_url);
1177 // Quickfix: Workaround for URL with "[" and "]" in it
1178 if (strpos($expanded_url, "[") || strpos($expanded_url, "]")) {
1179 $expanded_url = $url->url;
1183 $type = $oembed_data->type;
1186 if ($oembed_data->type == "video") {
1187 //$body = str_replace($url->url,
1188 // "[video]".$expanded_url."[/video]", $body);
1189 //$dontincludemedia = true;
1190 $type = $oembed_data->type;
1191 $footerurl = $expanded_url;
1192 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1194 $body = str_replace($url->url, $footerlink, $body);
1195 //} elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia) {
1196 } elseif (($oembed_data->type == "photo") && isset($oembed_data->url)) {
1197 $body = str_replace($url->url, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1198 //$dontincludemedia = true;
1199 } elseif ($oembed_data->type != "link") {
1200 $body = str_replace($url->url, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1202 $img_str = Network::fetchUrl($expanded_url, true, $redirects, 4);
1204 $tempfile = tempnam(get_temppath(), "cache");
1205 file_put_contents($tempfile, $img_str);
1206 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1209 if (substr($mime, 0, 6) == "image/") {
1211 $body = str_replace($url->url, "[img]" . $expanded_url . "[/img]", $body);
1212 //$dontincludemedia = true;
1214 $type = $oembed_data->type;
1215 $footerurl = $expanded_url;
1216 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1218 $body = str_replace($url->url, $footerlink, $body);
1224 if ($footerurl != "") {
1225 $footer = add_page_info($footerurl, false, $picture);
1228 if (($footerlink != "") && (trim($footer) != "")) {
1229 $removedlink = trim(str_replace($footerlink, "", $body));
1231 if (($removedlink == "") || strstr($body, $removedlink)) {
1232 $body = $removedlink;
1238 if (($footer == "") && ($picture != "")) {
1239 $body .= "\n\n[img]" . $picture . "[/img]\n";
1240 } elseif (($footer == "") && ($picture == "")) {
1241 $body = add_page_info_to_body($body);
1245 // it seems as if the entities aren't always covering all mentions. So the rest will be checked here
1246 $tags = get_tags($body);
1249 foreach ($tags as $tag) {
1250 if (strstr(trim($tag), " ")) {
1254 if (strpos($tag, '#') === 0) {
1255 if (strpos($tag, '[url=')) {
1259 // don't link tags that are already embedded in links
1260 if (preg_match('/\[(.*?)' . preg_quote($tag, '/') . '(.*?)\]/', $body)) {
1263 if (preg_match('/\[(.*?)\]\((.*?)' . preg_quote($tag, '/') . '(.*?)\)/', $body)) {
1267 $basetag = str_replace('_', ' ', substr($tag, 1));
1268 $url = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1269 $body = str_replace($tag, $url, $body);
1270 $tags_arr["#" . $basetag] = $url;
1271 } elseif (strpos($tag, '@') === 0) {
1272 if (strpos($tag, '[url=')) {
1276 $basetag = substr($tag, 1);
1277 $url = '@[url=https://twitter.com/' . rawurlencode($basetag) . ']' . $basetag . '[/url]';
1278 $body = str_replace($tag, $url, $body);
1279 $tags_arr["@" . $basetag] = $url;
1284 $tags = implode($tags_arr, ",");
1286 return ["body" => $body, "tags" => $tags, "plain" => $plain];
1290 * @brief Fetch media entities and add media links to the body
1292 * @param object $post Twitter object with the post
1293 * @param array $postarray Array of the item that is about to be posted
1295 * @return $picture string Image URL or empty string
1297 function twitter_media_entities($post, &$postarray)
1299 // There are no media entities? So we quit.
1300 if (!is_array($post->extended_entities->media)) {
1304 // When the post links to an external page, we only take one picture.
1305 // We only do this when there is exactly one media.
1306 if ((count($post->entities->urls) > 0) && (count($post->extended_entities->media) == 1)) {
1308 foreach ($post->extended_entities->media AS $medium) {
1309 if (isset($medium->media_url_https)) {
1310 $picture = $medium->media_url_https;
1311 $postarray['body'] = str_replace($medium->url, "", $postarray['body']);
1317 // This is a pure media post, first search for all media urls
1319 foreach ($post->extended_entities->media AS $medium) {
1320 switch ($medium->type) {
1322 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . "[/img]";
1323 $postarray['object-type'] = ACTIVITY_OBJ_IMAGE;
1326 case 'animated_gif':
1327 $media[$medium->url] .= "\n[img]" . $medium->media_url_https . "[/img]";
1328 $postarray['object-type'] = ACTIVITY_OBJ_VIDEO;
1329 if (is_array($medium->video_info->variants)) {
1331 // We take the video with the highest bitrate
1332 foreach ($medium->video_info->variants AS $variant) {
1333 if (($variant->content_type == "video/mp4") && ($variant->bitrate >= $bitrate)) {
1334 $media[$medium->url] = "\n[video]" . $variant->url . "[/video]";
1335 $bitrate = $variant->bitrate;
1340 // The following code will only be activated for test reasons
1342 // $postarray['body'] .= print_r($medium, true);
1346 // Now we replace the media urls.
1347 foreach ($media AS $key => $value) {
1348 $postarray['body'] = str_replace($key, "\n" . $value . "\n", $postarray['body']);
1353 function twitter_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact, $noquote)
1356 $postarray['network'] = NETWORK_TWITTER;
1357 $postarray['gravity'] = 0;
1358 $postarray['uid'] = $uid;
1359 $postarray['wall'] = 0;
1360 $postarray['uri'] = "twitter::" . $post->id_str;
1361 $postarray['object'] = json_encode($post);
1363 // Don't import our own comments
1364 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1365 dbesc($postarray['uri']),
1370 logger("Item with extid " . $postarray['uri'] . " found.", LOGGER_DEBUG);
1376 if ($post->in_reply_to_status_id_str != "") {
1377 $parent = "twitter::" . $post->in_reply_to_status_id_str;
1379 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1384 $postarray['thr-parent'] = $r[0]["uri"];
1385 $postarray['parent-uri'] = $r[0]["parent-uri"];
1386 $postarray['parent'] = $r[0]["parent"];
1387 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1389 $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1394 $postarray['thr-parent'] = $r[0]['uri'];
1395 $postarray['parent-uri'] = $r[0]['parent-uri'];
1396 $postarray['parent'] = $r[0]['parent'];
1397 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1399 $postarray['thr-parent'] = $postarray['uri'];
1400 $postarray['parent-uri'] = $postarray['uri'];
1401 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1406 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1408 if ($post->user->id_str == $own_id) {
1409 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1413 $contactid = $r[0]["id"];
1415 $postarray['owner-name'] = $r[0]["name"];
1416 $postarray['owner-link'] = $r[0]["url"];
1417 $postarray['owner-avatar'] = $r[0]["photo"];
1419 logger("No self contact for user " . $uid, LOGGER_DEBUG);
1423 // Don't create accounts of people who just comment something
1424 $create_user = false;
1426 $postarray['parent-uri'] = $postarray['uri'];
1427 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1430 if ($contactid == 0) {
1431 $contactid = twitter_fetch_contact($uid, $post->user, $create_user);
1433 $postarray['owner-name'] = $post->user->name;
1434 $postarray['owner-link'] = "https://twitter.com/" . $post->user->screen_name;
1435 $postarray['owner-avatar'] = twitter_fix_avatar($post->user->profile_image_url_https);
1438 if (($contactid == 0) && !$only_existing_contact) {
1439 $contactid = $self['id'];
1440 } elseif ($contactid <= 0) {
1441 logger("Contact ID is zero or less than zero.", LOGGER_DEBUG);
1445 $postarray['contact-id'] = $contactid;
1447 $postarray['verb'] = ACTIVITY_POST;
1448 $postarray['author-name'] = $postarray['owner-name'];
1449 $postarray['author-link'] = $postarray['owner-link'];
1450 $postarray['author-avatar'] = $postarray['owner-avatar'];
1451 $postarray['plink'] = "https://twitter.com/" . $post->user->screen_name . "/status/" . $post->id_str;
1452 $postarray['app'] = strip_tags($post->source);
1454 if ($post->user->protected) {
1455 $postarray['private'] = 1;
1456 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1459 if (is_string($post->full_text)) {
1460 $postarray['body'] = $post->full_text;
1462 $postarray['body'] = $post->text;
1465 // When the post contains links then use the correct object type
1466 if (count($post->entities->urls) > 0) {
1467 $postarray['object-type'] = ACTIVITY_OBJ_BOOKMARK;
1470 // Search for media links
1471 $picture = twitter_media_entities($post, $postarray);
1473 $converted = twitter_expand_entities($a, $postarray['body'], $post, $picture);
1474 $postarray['body'] = $converted["body"];
1475 $postarray['tag'] = $converted["tags"];
1476 $postarray['created'] = DateTimeFormat::utc($post->created_at);
1477 $postarray['edited'] = DateTimeFormat::utc($post->created_at);
1479 $statustext = $converted["plain"];
1481 if (is_string($post->place->name)) {
1482 $postarray["location"] = $post->place->name;
1484 if (is_string($post->place->full_name)) {
1485 $postarray["location"] = $post->place->full_name;
1487 if (is_array($post->geo->coordinates)) {
1488 $postarray["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
1490 if (is_array($post->coordinates->coordinates)) {
1491 $postarray["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
1493 if (is_object($post->retweeted_status)) {
1494 $retweet = twitter_createpost($a, $uid, $post->retweeted_status, $self, false, false, $noquote);
1496 $retweet['object'] = $postarray['object'];
1497 $retweet['private'] = $postarray['private'];
1498 $retweet['allow_cid'] = $postarray['allow_cid'];
1499 $retweet['contact-id'] = $postarray['contact-id'];
1500 $retweet['owner-name'] = $postarray['owner-name'];
1501 $retweet['owner-link'] = $postarray['owner-link'];
1502 $retweet['owner-avatar'] = $postarray['owner-avatar'];
1504 $postarray = $retweet;
1507 if (is_object($post->quoted_status) && !$noquote) {
1508 $quoted = twitter_createpost($a, $uid, $post->quoted_status, $self, false, false, true);
1510 $postarray['body'] = $statustext;
1512 $postarray['body'] .= "\n" . share_header(
1513 $quoted['author-name'],
1514 $quoted['author-link'],
1515 $quoted['author-avatar'],
1521 $postarray['body'] .= $quoted['body'] . '[/share]';
1527 function twitter_checknotification(App $a, $uid, $own_id, $top_item, $postarray)
1529 /// TODO: this whole function doesn't seem to work. Needs complete check
1530 $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1534 if (!count($user)) {
1539 if (link_compare($user[0]["url"], $postarray['author-link'])) {
1543 $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1545 dbesc("twitter::".$own_id)
1548 if (!count($own_user)) {
1552 // Is it me from twitter?
1553 if (link_compare($own_user[0]["url"], $postarray['author-link'])) {
1557 $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1558 dbesc($postarray['parent-uri']),
1562 if (count($myconv)) {
1563 foreach ($myconv as $conv) {
1564 // now if we find a match, it means we're in this conversation
1565 if (!link_compare($conv['author-link'], $user[0]["url"]) && !link_compare($conv['author-link'], $own_user[0]["url"])) {
1569 require_once 'include/enotify.php';
1571 $conv_parent = $conv['parent'];
1574 'type' => NOTIFY_COMMENT,
1575 'notify_flags' => $user[0]['notify-flags'],
1576 'language' => $user[0]['language'],
1577 'to_name' => $user[0]['username'],
1578 'to_email' => $user[0]['email'],
1579 'uid' => $user[0]['uid'],
1580 'item' => $postarray,
1581 'link' => $a->get_baseurl() . '/display/' . urlencode(Item::getGuidById($top_item)),
1582 'source_name' => $postarray['author-name'],
1583 'source_link' => $postarray['author-link'],
1584 'source_photo' => $postarray['author-avatar'],
1585 'verb' => ACTIVITY_POST,
1587 'parent' => $conv_parent,
1590 // only send one notification
1596 function twitter_fetchparentposts(App $a, $uid, $post, $connection, $self, $own_id)
1598 logger("twitter_fetchparentposts: Fetching for user " . $uid . " and post " . $post->id_str, LOGGER_DEBUG);
1602 while ($post->in_reply_to_status_id_str != "") {
1603 $parameters = ["trim_user" => false, "tweet_mode" => "extended", "id" => $post->in_reply_to_status_id_str];
1605 $post = $connection->get('statuses/show', $parameters);
1607 if (!count($post)) {
1608 logger("twitter_fetchparentposts: Can't fetch post " . $parameters->id, LOGGER_DEBUG);
1612 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1613 dbesc("twitter::".$post->id_str),
1624 logger("twitter_fetchparentposts: Fetching " . count($posts) . " parents", LOGGER_DEBUG);
1626 $posts = array_reverse($posts);
1628 if (count($posts)) {
1629 foreach ($posts as $post) {
1630 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1632 if (trim($postarray['body']) == "") {
1636 $item = Item::insert($postarray);
1642 $postarray["id"] = $item;
1644 logger('twitter_fetchparentpost: User ' . $self["nick"] . ' posted parent timeline item ' . $item);
1646 if ($item && !function_exists("check_item_notification")) {
1647 twitter_checknotification($a, $uid, $own_id, $item, $postarray);
1653 function twitter_fetchhometimeline(App $a, $uid)
1655 $ckey = Config::get('twitter', 'consumerkey');
1656 $csecret = Config::get('twitter', 'consumersecret');
1657 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1658 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1659 $create_user = PConfig::get($uid, 'twitter', 'create_user');
1660 $mirror_posts = PConfig::get($uid, 'twitter', 'mirror_posts');
1662 logger("twitter_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG);
1664 $application_name = Config::get('twitter', 'application_name');
1666 if ($application_name == "") {
1667 $application_name = $a->get_hostname();
1670 require_once 'include/items.php';
1672 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1674 $own_contact = twitter_fetch_own_contact($a, $uid);
1676 $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1677 intval($own_contact),
1681 $own_id = $r[0]["nick"];
1683 logger("twitter_fetchhometimeline: Own twitter contact not found for user " . $uid, LOGGER_DEBUG);
1687 $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1693 logger("twitter_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG);
1697 $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1700 logger("twitter_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG);
1704 $parameters = ["exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true, "tweet_mode" => "extended"];
1705 //$parameters["count"] = 200;
1706 // Fetching timeline
1707 $lastid = PConfig::get($uid, 'twitter', 'lasthometimelineid');
1709 $first_time = ($lastid == "");
1711 if ($lastid != "") {
1712 $parameters["since_id"] = $lastid;
1715 $items = $connection->get('statuses/home_timeline', $parameters);
1717 if (!is_array($items)) {
1718 logger("twitter_fetchhometimeline: Error fetching home timeline: " . print_r($items, true), LOGGER_DEBUG);
1722 $posts = array_reverse($items);
1724 logger("twitter_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1726 if (count($posts)) {
1727 foreach ($posts as $post) {
1728 if ($post->id_str > $lastid) {
1729 $lastid = $post->id_str;
1730 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1737 if (stristr($post->source, $application_name) && $post->user->screen_name == $own_id) {
1738 logger("twitter_fetchhometimeline: Skip previously sended post", LOGGER_DEBUG);
1742 if ($mirror_posts && $post->user->screen_name == $own_id && $post->in_reply_to_status_id_str == "") {
1743 logger("twitter_fetchhometimeline: Skip post that will be mirrored", LOGGER_DEBUG);
1747 if ($post->in_reply_to_status_id_str != "") {
1748 twitter_fetchparentposts($a, $uid, $post, $connection, $self, $own_id);
1751 $postarray = twitter_createpost($a, $uid, $post, $self, $create_user, true, false);
1753 if (trim($postarray['body']) == "") {
1759 if ($postarray['uri'] == $postarray['parent-uri']) {
1760 $contact = dba::selectFirst('contact', [], ['id' => $postarray['contact-id'], 'self' => false]);
1761 if (DBM::is_result($contact)) {
1762 $notify = Item::isRemoteSelf($contact, $postarray);
1766 $item = Item::insert($postarray, false, $notify);
1767 $postarray["id"] = $item;
1769 logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1771 if ($item && !function_exists("check_item_notification")) {
1772 twitter_checknotification($a, $uid, $own_id, $item, $postarray);
1776 PConfig::set($uid, 'twitter', 'lasthometimelineid', $lastid);
1778 // Fetching mentions
1779 $lastid = PConfig::get($uid, 'twitter', 'lastmentionid');
1781 $first_time = ($lastid == "");
1783 if ($lastid != "") {
1784 $parameters["since_id"] = $lastid;
1787 $items = $connection->get('statuses/mentions_timeline', $parameters);
1789 if (!is_array($items)) {
1790 logger("twitter_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG);
1794 $posts = array_reverse($items);
1796 logger("twitter_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1798 if (count($posts)) {
1799 foreach ($posts as $post) {
1800 if ($post->id_str > $lastid) {
1801 $lastid = $post->id_str;
1808 if ($post->in_reply_to_status_id_str != "") {
1809 twitter_fetchparentposts($a, $uid, $post, $connection, $self, $own_id);
1812 $postarray = twitter_createpost($a, $uid, $post, $self, false, false, false);
1814 if (trim($postarray['body']) == "") {
1818 $item = Item::insert($postarray);
1819 $postarray["id"] = $item;
1821 if ($item && function_exists("check_item_notification")) {
1822 check_item_notification($item, $uid, NOTIFY_TAGSELF);
1825 if (!isset($postarray["parent"]) || ($postarray["parent"] == 0)) {
1826 $postarray["parent"] = $item;
1829 logger('twitter_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1832 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1833 dbesc($postarray['uri']),
1837 $item = $r[0]['id'];
1838 $parent_id = $r[0]['parent'];
1841 $parent_id = $postarray['parent'];
1844 if (($item != 0) && !function_exists("check_item_notification")) {
1845 require_once 'include/enotify.php';
1847 'type' => NOTIFY_TAGSELF,
1848 'notify_flags' => $u[0]['notify-flags'],
1849 'language' => $u[0]['language'],
1850 'to_name' => $u[0]['username'],
1851 'to_email' => $u[0]['email'],
1852 'uid' => $u[0]['uid'],
1853 'item' => $postarray,
1854 'link' => $a->get_baseurl() . '/display/' . urlencode(Item::getGuidById($item)),
1855 'source_name' => $postarray['author-name'],
1856 'source_link' => $postarray['author-link'],
1857 'source_photo' => $postarray['author-avatar'],
1858 'verb' => ACTIVITY_TAG,
1860 'parent' => $parent_id
1866 PConfig::set($uid, 'twitter', 'lastmentionid', $lastid);
1869 function twitter_fetch_own_contact(App $a, $uid)
1871 $ckey = Config::get('twitter', 'consumerkey');
1872 $csecret = Config::get('twitter', 'consumersecret');
1873 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1874 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1876 $own_id = PConfig::get($uid, 'twitter', 'own_id');
1880 if ($own_id == "") {
1881 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1883 // Fetching user data
1884 $user = $connection->get('account/verify_credentials');
1886 PConfig::set($uid, 'twitter', 'own_id', $user->id_str);
1888 $contact_id = twitter_fetch_contact($uid, $user, true);
1890 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1892 dbesc("twitter::" . $own_id));
1894 $contact_id = $r[0]["id"];
1896 PConfig::delete($uid, 'twitter', 'own_id');
1903 function twitter_is_retweet(App $a, $uid, $body)
1905 $body = trim($body);
1907 // Skip if it isn't a pure repeated messages
1908 // Does it start with a share?
1909 if (strpos($body, "[share") > 0) {
1913 // Does it end with a share?
1914 if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1918 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1919 // Skip if there is no shared message in there
1920 if ($body == $attributes) {
1925 preg_match("/link='(.*?)'/ism", $attributes, $matches);
1926 if ($matches[1] != "") {
1927 $link = $matches[1];
1930 preg_match('/link="(.*?)"/ism', $attributes, $matches);
1931 if ($matches[1] != "") {
1932 $link = $matches[1];
1935 $id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link);
1940 logger('twitter_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG);
1942 $ckey = Config::get('twitter', 'consumerkey');
1943 $csecret = Config::get('twitter', 'consumersecret');
1944 $otoken = PConfig::get($uid, 'twitter', 'oauthtoken');
1945 $osecret = PConfig::get($uid, 'twitter', 'oauthsecret');
1947 $connection = new TwitterOAuth($ckey, $csecret, $otoken, $osecret);
1948 $result = $connection->post('statuses/retweet/' . $id);
1950 logger('twitter_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);
1952 return !isset($result->errors);