]> git.mxchange.org Git - friendica-addons.git/blob - twitter/twitter.php
Twitter addon: applied SN addon changes for better content of the last days
[friendica-addons.git] / twitter / twitter.php
1 <?php
2 /**
3  * Name: Twitter Connector
4  * Description: Relay public postings to a connected StatusNet account
5  * Version: 1.0.2
6  * Author: Tobias Diekershoff <https://diekershoff.homeunix.net/friendika/profile/tobias>
7  */
8
9
10 /*   Twitter Plugin for Friendica
11  *
12  *   Author: Tobias Diekershoff
13  *           tobias.diekershoff@gmx.net
14  *
15  *   License:3-clause BSD license
16  *
17  *   Configuration:
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
20  *
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.
24  *
25  *     Add this key pair to your global .htconfig.php or use the admin panel.
26  *
27  *     $a->config['twitter']['consumerkey'] = 'your consumer_key here';
28  *     $a->config['twitter']['consumersecret'] = 'your consumer_secret here';
29  *
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".
33  *
34  *     Requirements: PHP5, curl [Slinky library]
35  *
36  *     Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/Twitter_Plugin
37  */
38
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");
47 }
48
49
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');
56
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');
61
62 }
63
64 function twitter_jot_nets(&$a,&$b) {
65         if(! local_user())
66                 return;
67
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>';      
74         }
75
76
77 }
78
79 function twitter_settings_post ($a,$post) {
80         if(! local_user())
81                 return;
82         // don't check twitter settings if twitter submit button is not clicked 
83         if (!x($_POST,'twitter-submit')) return;
84         
85         if (isset($_POST['twitter-disconnect'])) {
86                 /***
87                  * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
88                  * from the user configuration
89                  */
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' );
96         } else {
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');
114         } else {
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);
120         }}
121 }
122 function twitter_settings(&$a,&$s) {
123         if(! local_user())
124                 return;
125         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
126         /***
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)
130          */
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" ' : '');
139
140         $s .= '<div class="settings-block">';
141         $s .= '<h3>'. t('Twitter Posting Settings') .'</h3>';
142
143         if ( (!$ckey) && (!$csecret) ) {
144                 /***
145                  * no global consumer keys
146                  * display warning and skip personal config
147                  */
148                 $s .= '<p>'. t('No consumer key pair for Twitter found. Please contact your site administrator.') .'</p>';
149         } else {
150                 /***
151                  * ok we have a consumer key pair now look into the OAuth stuff
152                  */
153                 if ( (!$otoken) && (!$osecret) ) {
154                         /***
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.
159                          */
160                         require_once('library/twitteroauth.php');
161                         $connection = new TwitterOAuth($ckey, $csecret);
162                         $request_token = $connection->getRequestToken();
163                         $token = $request_token['oauth_token'];
164                         /***
165                          *  make some nice form
166                          */
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>';
176                 } else {
177                         /***
178                          *  we have an OAuth key / secret pair for the user
179                          *  so let's give a chance to disable the postings to Twitter
180                          */
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                         $s .= '<div id="twitter-enable-wrapper">';
187                         $s .= '<label id="twitter-enable-label" for="twitter-checkbox">'. t('Allow posting to Twitter'). '</label>';
188                         $s .= '<input id="twitter-checkbox" type="checkbox" name="twitter-enable" value="1" ' . $checked . '/>';
189                         $s .= '<div class="clear"></div>';
190                         $s .= '<label id="twitter-default-label" for="twitter-default">'. t('Send public postings to Twitter by default') .'</label>';
191                         $s .= '<input id="twitter-default" type="checkbox" name="twitter-default" value="1" ' . $defchecked . '/>';
192                         $s .= '</div><div class="clear"></div>';
193
194                         $s .= '<div id="twitter-disconnect-wrapper">';
195                         $s .= '<label id="twitter-disconnect-label" for="twitter-disconnect">'. t('Clear OAuth configuration') .'</label>';
196                         $s .= '<input id="twitter-disconnect" type="checkbox" name="twitter-disconnect" value="1" />';
197                         $s .= '</div><div class="clear"></div>';
198                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
199                 }
200         }
201         $s .= '</div><div class="clear"></div></div>';
202 }
203
204
205 function twitter_post_local(&$a,&$b) {
206
207         if($b['edit'])
208                 return;
209
210         if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (! $b['parent']) ) {
211
212                 $twitter_post = intval(get_pconfig(local_user(),'twitter','post'));
213                 $twitter_enable = (($twitter_post && x($_REQUEST,'twitter_enable')) ? intval($_REQUEST['twitter_enable']) : 0);
214
215                 // if API is used, default to the chosen settings
216                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'twitter','post_by_default')))
217                         $twitter_enable = 1;
218
219         if(! $twitter_enable)
220             return;
221
222         if(strlen($b['postopts']))
223             $b['postopts'] .= ',';
224         $b['postopts'] .= 'twitter';
225         }
226 }
227
228 if (! function_exists('short_link')) {
229 function short_link ($url) {
230     require_once('library/slinky.php');
231     $slinky = new Slinky( $url );
232     $yourls_url = get_config('yourls','url1');
233     if ($yourls_url) {
234             $yourls_username = get_config('yourls','username1');
235             $yourls_password = get_config('yourls', 'password1');
236             $yourls_ssl = get_config('yourls', 'ssl1');
237             $yourls = new Slinky_YourLS();
238             $yourls->set( 'username', $yourls_username );
239             $yourls->set( 'password', $yourls_password );
240             $yourls->set( 'ssl', $yourls_ssl );
241             $yourls->set( 'yourls-url', $yourls_url );
242             $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
243     }
244     else {
245             // setup a cascade of shortening services
246             // try to get a short link from these services
247             // in the order ur1.ca, trim, id.gd, tinyurl
248             $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
249     }
250     return $slinky->short();
251 } };
252
253 function twitter_post_hook(&$a,&$b) {
254
255         /**
256          * Post to Twitter
257          */
258
259         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
260         return;
261
262         if(! strstr($b['postopts'],'twitter'))
263                 return;
264
265         if($b['parent'] != $b['id'])
266                 return;
267
268         logger('twitter post invoked');
269
270
271         load_pconfig($b['uid'], 'twitter');
272
273         $ckey    = get_config('twitter', 'consumerkey'  );
274         $csecret = get_config('twitter', 'consumersecret' );
275         $otoken  = get_pconfig($b['uid'], 'twitter', 'oauthtoken'  );
276         $osecret = get_pconfig($b['uid'], 'twitter', 'oauthsecret' );
277
278         if($ckey && $csecret && $otoken && $osecret) {
279                 logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
280
281                 require_once('library/twitteroauth.php');
282                 require_once('include/bbcode.php');     
283                 $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
284                 // in theory max char is 140 but T. uses t.co to make links 
285                 // longer so we give them 10 characters extra
286                 $max_char = 130; // max. length for a tweet
287                 // we will only work with up to two times the length of the dent 
288                 // we can later send to StatusNet. This way we can "gain" some 
289                 // information during shortening of potential links but do not 
290                 // shorten all the links in a 200000 character long essay.
291                 $tmp = substr($b['body'], 0, 2*$max_char);
292                 // if [url=bla][img]blub.png[/img][/url] get blub.png
293                 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
294                 // preserve links to images, videos and audios
295                 $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
296                 $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
297                 $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
298                 $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
299                 $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
300                 $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
301                 // if a #tag is linked, don't send the [url] over to SN
302                 //   this is commented out by default as it means backlinks
303                 //   to friendica, if you don't like this feel free to
304                 //   uncomment the following line
305 //                $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
306                 // preserve links to webpages
307                 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
308                 $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
309                 // find all http or https links in the body of the entry and 
310                 // apply the shortener if the link is longer then 20 characters 
311                 if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
312                     preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls  );
313                     foreach ($allurls as $url) {
314                         foreach ($url as $u) {
315                             if (strlen($u)>20) {
316                                 $sl = short_link($u);
317                                 $tmp = str_replace( $u, $sl, $tmp );
318                             }
319                         }
320                     }
321                 }
322                 // ok, all the links we want to send out are save, now strip 
323                 // away the remaining bbcode
324                 $msg = strip_tags(bbcode($tmp));
325                 // quotes not working - let's try this
326                 $msg = html_entity_decode($msg);
327                 if (( strlen($msg) > $max_char) && $max_char > 0) {
328                         $shortlink = short_link( $b['plink'] );
329                         // the new message will be shortened such that "... $shortlink"
330                         // will fit into the character limit
331                         $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
332                         $msg .= '... ' . $shortlink;
333                 }
334                 // and now tweet it :-)
335                 if(strlen($msg)) {
336                         $result = $tweet->post('statuses/update', array('status' => $msg));
337                         logger('twitter_post send' , LOGGER_DEBUG);
338                 }
339         }
340 }
341
342 function twitter_plugin_admin_post(&$a){
343         $consumerkey    =       ((x($_POST,'consumerkey'))              ? notags(trim($_POST['consumerkey']))   : '');
344         $consumersecret =       ((x($_POST,'consumersecret'))   ? notags(trim($_POST['consumersecret'])): '');
345         set_config('twitter','consumerkey',$consumerkey);
346         set_config('twitter','consumersecret',$consumersecret);
347         info( t('Settings updated.'). EOL );
348 }
349 function twitter_plugin_admin(&$a, &$o){
350         $t = file_get_contents( dirname(__file__). "/admin.tpl" );
351         $o = replace_macros($t, array(
352                 '$submit' => t('Submit'),
353                                                                 // name, label, value, help, [extra values]
354                 '$consumerkey' => array('consumerkey', t('Consumer key'),  get_config('twitter', 'consumerkey' ), ''),
355                 '$consumersecret' => array('consumersecret', t('Consumer secret'),  get_config('twitter', 'consumersecret' ), '')
356         ));
357 }