3 * Name: Twitter Connector
4 * Description: Relay public postings to a connected Twitter account
6 * Author: Tobias Diekershoff <https://diekershoff.homeunix.net/friendika/profile/tobias>
10 /* Twitter Plugin for Friendica
12 * Author: Tobias Diekershoff
13 * tobias.diekershoff@gmx.net
15 * License:3-clause BSD license
18 * To use this plugin you need a OAuth Consumer key pair (key & secret)
19 * you can get it from Twitter at https://twitter.com/apps
21 * Register your Friendica site as "Client" application with "Read & Write" access
22 * we do not need "Twitter as login". When you've registered the app you get the
23 * OAuth Consumer key and secret pair for your application/site.
25 * Add this key pair to your global .htconfig.php or use the admin panel.
27 * $a->config['twitter']['consumerkey'] = 'your consumer_key here';
28 * $a->config['twitter']['consumersecret'] = 'your consumer_secret here';
30 * To activate the plugin itself add it to the $a->config['system']['addon']
31 * setting. After this, your user can configure their Twitter account settings
32 * from "Settings -> Plugin Settings".
34 * Requirements: PHP5, curl [Slinky library]
36 * Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/Twitter_Plugin
39 function twitter_install() {
40 // we need some hooks, for the configuration and for sending tweets
41 register_hook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings');
42 register_hook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
43 register_hook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
44 register_hook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
45 register_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
46 logger("installed twitter");
50 function twitter_uninstall() {
51 unregister_hook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings');
52 unregister_hook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
53 unregister_hook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
54 unregister_hook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
55 unregister_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
57 // old setting - remove only
58 unregister_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
59 unregister_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings');
60 unregister_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
64 function twitter_jot_nets(&$a,&$b) {
68 $tw_post = get_pconfig(local_user(),'twitter','post');
69 if(intval($tw_post) == 1) {
70 $tw_defpost = get_pconfig(local_user(),'twitter','post_by_default');
71 $selected = ((intval($tw_defpost) == 1) ? ' checked="checked" ' : '');
72 $b .= '<div class="profile-jot-net"><input type="checkbox" name="twitter_enable"' . $selected . ' value="1" /> '
73 . t('Post to Twitter') . '</div>';
79 function twitter_settings_post ($a,$post) {
82 // don't check twitter settings if twitter submit button is not clicked
83 if (!x($_POST,'twitter-submit')) return;
85 if (isset($_POST['twitter-disconnect'])) {
87 * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
88 * from the user configuration
90 del_pconfig( local_user(), 'twitter', 'consumerkey' );
91 del_pconfig( local_user(), 'twitter', 'consumersecret' );
92 del_pconfig( local_user(), 'twitter', 'oauthtoken' );
93 del_pconfig( local_user(), 'twitter', 'oauthsecret' );
94 del_pconfig( local_user(), 'twitter', 'post' );
95 del_pconfig( local_user(), 'twitter', 'post_by_default' );
97 if (isset($_POST['twitter-pin'])) {
98 // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
99 logger('got a Twitter PIN');
100 require_once('library/twitteroauth.php');
101 $ckey = get_config('twitter', 'consumerkey' );
102 $csecret = get_config('twitter', 'consumersecret' );
103 // the token and secret for which the PIN was generated were hidden in the settings
104 // form as token and token2, we need a new connection to Twitter using these token
105 // and secret to request a Access Token with the PIN
106 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
107 $token = $connection->getAccessToken( $_POST['twitter-pin'] );
108 // ok, now that we have the Access Token, save them in the user config
109 set_pconfig(local_user(),'twitter', 'oauthtoken', $token['oauth_token']);
110 set_pconfig(local_user(),'twitter', 'oauthsecret', $token['oauth_token_secret']);
111 set_pconfig(local_user(),'twitter', 'post', 1);
112 // reload the Addon Settings page, if we don't do it see Bug #42
113 goaway($a->get_baseurl().'/settings/connectors');
115 // if no PIN is supplied in the POST variables, the user has changed the setting
116 // to post a tweet for every new __public__ posting to the wall
117 set_pconfig(local_user(),'twitter','post',intval($_POST['twitter-enable']));
118 set_pconfig(local_user(),'twitter','post_by_default',intval($_POST['twitter-default']));
119 info( t('Twitter settings updated.') . EOL);
122 function twitter_settings(&$a,&$s) {
125 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
127 * 1) Check that we have global consumer key & secret
128 * 2) If no OAuthtoken & stuff is present, generate button to get some
129 * 3) Checkbox for "Send public notices (140 chars only)
131 $ckey = get_config('twitter', 'consumerkey' );
132 $csecret = get_config('twitter', 'consumersecret' );
133 $otoken = get_pconfig(local_user(), 'twitter', 'oauthtoken' );
134 $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' );
135 $enabled = get_pconfig(local_user(), 'twitter', 'post');
136 $checked = (($enabled) ? ' checked="checked" ' : '');
137 $defenabled = get_pconfig(local_user(),'twitter','post_by_default');
138 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
140 $s .= '<div class="settings-block">';
141 $s .= '<h3>'. t('Twitter Posting Settings') .'</h3>';
143 if ( (!$ckey) && (!$csecret) ) {
145 * no global consumer keys
146 * display warning and skip personal config
148 $s .= '<p>'. t('No consumer key pair for Twitter found. Please contact your site administrator.') .'</p>';
151 * ok we have a consumer key pair now look into the OAuth stuff
153 if ( (!$otoken) && (!$osecret) ) {
155 * the user has not yet connected the account to twitter...
156 * get a temporary OAuth key/secret pair and display a button with
157 * which the user can request a PIN to connect the account to a
158 * account at Twitter.
160 require_once('library/twitteroauth.php');
161 $connection = new TwitterOAuth($ckey, $csecret);
162 $request_token = $connection->getRequestToken();
163 $token = $request_token['oauth_token'];
165 * make some nice form
167 $s .= '<p>'. t('At this Friendica instance the Twitter plugin 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>';
168 $s .= '<a href="'.$connection->getAuthorizeURL($token).'" target="_twitter"><img src="addon/twitter/lighter.png" alt="'.t('Log in with Twitter').'"></a>';
169 $s .= '<div id="twitter-pin-wrapper">';
170 $s .= '<label id="twitter-pin-label" for="twitter-pin">'. t('Copy the PIN from Twitter here') .'</label>';
171 $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
172 $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="'.$token.'" />';
173 $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="'.$request_token['oauth_token_secret'].'" />';
174 $s .= '</div><div class="clear"></div>';
175 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
178 * we have an OAuth key / secret pair for the user
179 * so let's give a chance to disable the postings to Twitter
181 require_once('library/twitteroauth.php');
182 $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
183 $details = $connection->get('account/verify_credentials');
184 $s .= '<div id="twitter-info" ><img id="twitter-avatar" src="'.$details->profile_image_url.'" /><p id="twitter-info-block">'. t('Currently connected to: ') .'<a href="https://twitter.com/'.$details->screen_name.'" target="_twitter">'.$details->screen_name.'</a><br /><em>'.$details->description.'</em></p></div>';
185 $s .= '<p>'. 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.') .'</p>';
186 if ($a->user['hidewall']) {
187 $s .= '<p>'. t('<strong>Note</strong>: Due 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>';
189 $s .= '<div id="twitter-enable-wrapper">';
190 $s .= '<label id="twitter-enable-label" for="twitter-checkbox">'. t('Allow posting to Twitter'). '</label>';
191 $s .= '<input id="twitter-checkbox" type="checkbox" name="twitter-enable" value="1" ' . $checked . '/>';
192 $s .= '<div class="clear"></div>';
193 $s .= '<label id="twitter-default-label" for="twitter-default">'. t('Send public postings to Twitter by default') .'</label>';
194 $s .= '<input id="twitter-default" type="checkbox" name="twitter-default" value="1" ' . $defchecked . '/>';
195 $s .= '</div><div class="clear"></div>';
197 $s .= '<div id="twitter-disconnect-wrapper">';
198 $s .= '<label id="twitter-disconnect-label" for="twitter-disconnect">'. t('Clear OAuth configuration') .'</label>';
199 $s .= '<input id="twitter-disconnect" type="checkbox" name="twitter-disconnect" value="1" />';
200 $s .= '</div><div class="clear"></div>';
201 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
204 $s .= '</div><div class="clear"></div></div>';
208 function twitter_post_local(&$a,&$b) {
213 if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (! $b['parent']) ) {
215 $twitter_post = intval(get_pconfig(local_user(),'twitter','post'));
216 $twitter_enable = (($twitter_post && x($_REQUEST,'twitter_enable')) ? intval($_REQUEST['twitter_enable']) : 0);
218 // if API is used, default to the chosen settings
219 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'twitter','post_by_default')))
222 if(! $twitter_enable)
225 if(strlen($b['postopts']))
226 $b['postopts'] .= ',';
227 $b['postopts'] .= 'twitter';
231 if (! function_exists('short_link')) {
232 function short_link ($url) {
233 require_once('library/slinky.php');
234 $slinky = new Slinky( $url );
235 $yourls_url = get_config('yourls','url1');
237 $yourls_username = get_config('yourls','username1');
238 $yourls_password = get_config('yourls', 'password1');
239 $yourls_ssl = get_config('yourls', 'ssl1');
240 $yourls = new Slinky_YourLS();
241 $yourls->set( 'username', $yourls_username );
242 $yourls->set( 'password', $yourls_password );
243 $yourls->set( 'ssl', $yourls_ssl );
244 $yourls->set( 'yourls-url', $yourls_url );
245 $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
248 // setup a cascade of shortening services
249 // try to get a short link from these services
250 // in the order ur1.ca, trim, id.gd, tinyurl
251 $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
253 return $slinky->short();
256 function twitter_post_hook(&$a,&$b) {
262 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
265 if(! strstr($b['postopts'],'twitter'))
268 if($b['parent'] != $b['id'])
271 logger('twitter post invoked');
274 load_pconfig($b['uid'], 'twitter');
276 $ckey = get_config('twitter', 'consumerkey' );
277 $csecret = get_config('twitter', 'consumersecret' );
278 $otoken = get_pconfig($b['uid'], 'twitter', 'oauthtoken' );
279 $osecret = get_pconfig($b['uid'], 'twitter', 'oauthsecret' );
281 if($ckey && $csecret && $otoken && $osecret) {
282 logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
284 require_once('library/twitteroauth.php');
285 require_once('include/bbcode.php');
286 $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
287 // in theory max char is 140 but T. uses t.co to make links
288 // longer so we give them 10 characters extra
289 $max_char = 130; // max. length for a tweet
290 // we will only work with up to two times the length of the dent
291 // we can later send to Twitter. This way we can "gain" some
292 // information during shortening of potential links but do not
293 // shorten all the links in a 200000 character long essay.
294 if (! $b['title']=='') {
295 $tmp = $b['title'] . ' : '. $b['body'];
296 $tmp = substr($tmp, 0, 2*$max_char);
298 $tmp = substr($b['body'], 0, 2*$max_char);
300 // if [url=bla][img]blub.png[/img][/url] get blub.png
301 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
302 // preserve links to images, videos and audios
303 $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
304 $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
305 $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
306 $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
307 $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
308 $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
309 // if a #tag is linked, don't send the [url] over to SN
310 // this is commented out by default as it means backlinks
311 // to friendica, if you don't like this feel free to
312 // uncomment the following line
313 // $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
314 // preserve links to webpages
315 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
316 $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
317 // find all http or https links in the body of the entry and
318 // apply the shortener if the link is longer then 20 characters
319 if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
320 preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls );
321 foreach ($allurls as $url) {
322 foreach ($url as $u) {
324 $sl = short_link($u);
325 $tmp = str_replace( $u, $sl, $tmp );
330 // ok, all the links we want to send out are save, now strip
331 // away the remaining bbcode
332 $msg = strip_tags(bbcode($tmp));
333 // quotes not working - let's try this
334 $msg = html_entity_decode($msg);
335 if (( strlen($msg) > $max_char) && $max_char > 0) {
336 $shortlink = short_link( $b['plink'] );
337 // the new message will be shortened such that "... $shortlink"
338 // will fit into the character limit
339 $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
340 $msg .= '... ' . $shortlink;
342 // and now tweet it :-)
344 $result = $tweet->post('statuses/update', array('status' => $msg));
345 logger('twitter_post send' , LOGGER_DEBUG);
350 function twitter_plugin_admin_post(&$a){
351 $consumerkey = ((x($_POST,'consumerkey')) ? notags(trim($_POST['consumerkey'])) : '');
352 $consumersecret = ((x($_POST,'consumersecret')) ? notags(trim($_POST['consumersecret'])): '');
353 set_config('twitter','consumerkey',$consumerkey);
354 set_config('twitter','consumersecret',$consumersecret);
355 info( t('Settings updated.'). EOL );
357 function twitter_plugin_admin(&$a, &$o){
358 $t = file_get_contents( dirname(__file__). "/admin.tpl" );
359 $o = replace_macros($t, array(
360 '$submit' => t('Submit'),
361 // name, label, value, help, [extra values]
362 '$consumerkey' => array('consumerkey', t('Consumer key'), get_config('twitter', 'consumerkey' ), ''),
363 '$consumersecret' => array('consumersecret', t('Consumer secret'), get_config('twitter', 'consumersecret' ), '')