]> git.mxchange.org Git - friendica-addons.git/blob - twitter/twitter.php
modified: statusnet.tgz First url shortener is a custom YourLS url âshortener...
[friendica-addons.git] / twitter / twitter.php
1 <?php
2 /**
3  * Name: Twitter Connector
4  * Version: 1.0.1
5  * Author: Tobias Diekershoff <https://diekershoff.homeunix.net/friendika/profile/tobias>
6  */
7
8
9 /*   Twitter Plugin for Friendica
10  *
11  *   Author: Tobias Diekershoff
12  *           tobias.diekershoff@gmx.net
13  *
14  *   License:3-clause BSD license
15  *
16  *   Configuration:
17  *     To use this plugin you need a OAuth Consumer key pair (key & secret)
18  *     you can get it from Twitter at https://twitter.com/apps
19  *
20  *     Register your Friendica site as "Client" application with "Read & Write" access
21  *     we do not need "Twitter as login". When you've registered the app you get the
22  *     OAuth Consumer key and secret pair for your application/site.
23  *
24  *     Add this key pair to your global .htconfig.php or use the admin panel.
25  *
26  *     $a->config['twitter']['consumerkey'] = 'your consumer_key here';
27  *     $a->config['twitter']['consumersecret'] = 'your consumer_secret here';
28  *
29  *     To activate the plugin itself add it to the $a->config['system']['addon']
30  *     setting. After this, your user can configure their Twitter account settings
31  *     from "Settings -> Plugin Settings".
32  *
33  *     Requirements: PHP5, curl [Slinky library]
34  *
35  *     Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/Twitter_Plugin
36  */
37
38 /*   __TODO__
39  *
40  *   - what about multimedia content?
41  *     so far we just strip HTML tags from the message
42  */
43
44 function twitter_install() {
45         //  we need some hooks, for the configuration and for sending tweets
46         register_hook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
47         register_hook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
48         register_hook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
49         register_hook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
50         register_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
51         logger("installed twitter");
52 }
53
54
55 function twitter_uninstall() {
56         unregister_hook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
57         unregister_hook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
58         unregister_hook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
59         unregister_hook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
60         unregister_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
61
62         // old setting - remove only
63         unregister_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
64         unregister_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
65         unregister_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
66
67 }
68
69 function twitter_jot_nets(&$a,&$b) {
70         if(! local_user())
71                 return;
72
73         $tw_post = get_pconfig(local_user(),'twitter','post');
74         if(intval($tw_post) == 1) {
75                 $tw_defpost = get_pconfig(local_user(),'twitter','post_by_default');
76                 $selected = ((intval($tw_defpost) == 1) ? ' checked="checked" ' : '');
77                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="twitter_enable"' . $selected . ' value="1" /> ' 
78                         . t('Post to Twitter') . '</div>';      
79         }
80
81
82 }
83
84 function twitter_settings_post ($a,$post) {
85         if(! local_user())
86                 return;
87         // don't check twitter settings if twitter submit button is not clicked 
88         if (!x($_POST,'twitter-submit')) return;
89         
90         if (isset($_POST['twitter-disconnect'])) {
91                 /***
92                  * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
93                  * from the user configuration
94                  */
95                 del_pconfig( local_user(), 'twitter', 'consumerkey'  );
96                 del_pconfig( local_user(), 'twitter', 'consumersecret' );
97                 del_pconfig( local_user(), 'twitter', 'oauthtoken'  );  
98                 del_pconfig( local_user(), 'twitter', 'oauthsecret'  );  
99                 del_pconfig( local_user(), 'twitter', 'post' );
100                 del_pconfig( local_user(), 'twitter', 'post_by_default' );
101         } else {
102         if (isset($_POST['twitter-pin'])) {
103                 //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
104                 logger('got a Twitter PIN');
105                 require_once('library/twitteroauth.php');
106                 $ckey    = get_config('twitter', 'consumerkey'  );
107                 $csecret = get_config('twitter', 'consumersecret' );
108                 //  the token and secret for which the PIN was generated were hidden in the settings
109                 //  form as token and token2, we need a new connection to Twitter using these token
110                 //  and secret to request a Access Token with the PIN
111                 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
112                 $token   = $connection->getAccessToken( $_POST['twitter-pin'] );
113                 //  ok, now that we have the Access Token, save them in the user config
114                 set_pconfig(local_user(),'twitter', 'oauthtoken',  $token['oauth_token']);
115                 set_pconfig(local_user(),'twitter', 'oauthsecret', $token['oauth_token_secret']);
116                 set_pconfig(local_user(),'twitter', 'post', 1);
117                 //  reload the Addon Settings page, if we don't do it see Bug #42
118                 goaway($a->get_baseurl().'/settings/connectors');
119         } else {
120                 //  if no PIN is supplied in the POST variables, the user has changed the setting
121                 //  to post a tweet for every new __public__ posting to the wall
122                 set_pconfig(local_user(),'twitter','post',intval($_POST['twitter-enable']));
123                 set_pconfig(local_user(),'twitter','post_by_default',intval($_POST['twitter-default']));
124                 info( t('Twitter settings updated.') . EOL);
125         }}
126 }
127 function twitter_settings(&$a,&$s) {
128         if(! local_user())
129                 return;
130         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
131         /***
132          * 1) Check that we have global consumer key & secret
133          * 2) If no OAuthtoken & stuff is present, generate button to get some
134          * 3) Checkbox for "Send public notices (140 chars only)
135          */
136         $ckey    = get_config('twitter', 'consumerkey' );
137         $csecret = get_config('twitter', 'consumersecret' );
138         $otoken  = get_pconfig(local_user(), 'twitter', 'oauthtoken'  );
139         $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' );
140         $enabled = get_pconfig(local_user(), 'twitter', 'post');
141         $checked = (($enabled) ? ' checked="checked" ' : '');
142         $defenabled = get_pconfig(local_user(),'twitter','post_by_default');
143         $defchecked = (($defenabled) ? ' checked="checked" ' : '');
144
145         $s .= '<div class="settings-block">';
146         $s .= '<h3>'. t('Twitter Posting Settings') .'</h3>';
147
148         if ( (!$ckey) && (!$csecret) ) {
149                 /***
150                  * no global consumer keys
151                  * display warning and skip personal config
152                  */
153                 $s .= '<p>'. t('No consumer key pair for Twitter found. Please contact your site administrator.') .'</p>';
154         } else {
155                 /***
156                  * ok we have a consumer key pair now look into the OAuth stuff
157                  */
158                 if ( (!$otoken) && (!$osecret) ) {
159                         /***
160                          * the user has not yet connected the account to twitter...
161                          * get a temporary OAuth key/secret pair and display a button with
162                          * which the user can request a PIN to connect the account to a
163                          * account at Twitter.
164                          */
165                         require_once('library/twitteroauth.php');
166                         $connection = new TwitterOAuth($ckey, $csecret);
167                         $request_token = $connection->getRequestToken();
168                         $token = $request_token['oauth_token'];
169                         /***
170                          *  make some nice form
171                          */
172                         $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>';
173                         $s .= '<a href="'.$connection->getAuthorizeURL($token).'" target="_twitter"><img src="addon/twitter/lighter.png" alt="'.t('Log in with Twitter').'"></a>';
174                         $s .= '<div id="twitter-pin-wrapper">';
175                         $s .= '<label id="twitter-pin-label" for="twitter-pin">'. t('Copy the PIN from Twitter here') .'</label>';
176                         $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
177                         $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="'.$token.'" />';
178                         $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="'.$request_token['oauth_token_secret'].'" />';
179             $s .= '</div><div class="clear"></div>';
180             $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
181                 } else {
182                         /***
183                          *  we have an OAuth key / secret pair for the user
184                          *  so let's give a chance to disable the postings to Twitter
185                          */
186                         require_once('library/twitteroauth.php');
187                         $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
188                         $details = $connection->get('account/verify_credentials');
189                         $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>';
190                         $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>';
191                         $s .= '<div id="twitter-enable-wrapper">';
192                         $s .= '<label id="twitter-enable-label" for="twitter-checkbox">'. t('Allow posting to Twitter'). '</label>';
193                         $s .= '<input id="twitter-checkbox" type="checkbox" name="twitter-enable" value="1" ' . $checked . '/>';
194                         $s .= '<div class="clear"></div>';
195                         $s .= '<label id="twitter-default-label" for="twitter-default">'. t('Send public postings to Twitter by default') .'</label>';
196                         $s .= '<input id="twitter-default" type="checkbox" name="twitter-default" value="1" ' . $defchecked . '/>';
197                         $s .= '</div><div class="clear"></div>';
198
199                         $s .= '<div id="twitter-disconnect-wrapper">';
200                         $s .= '<label id="twitter-disconnect-label" for="twitter-disconnect">'. t('Clear OAuth configuration') .'</label>';
201                         $s .= '<input id="twitter-disconnect" type="checkbox" name="twitter-disconnect" value="1" />';
202                         $s .= '</div><div class="clear"></div>';
203                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
204                 }
205         }
206         $s .= '</div><div class="clear"></div></div>';
207 }
208
209
210 function twitter_post_local(&$a,&$b) {
211
212         if($b['edit'])
213                 return;
214
215         if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (! $b['parent']) ) {
216
217                 $twitter_post = intval(get_pconfig(local_user(),'twitter','post'));
218                 $twitter_enable = (($twitter_post && x($_REQUEST,'twitter_enable')) ? intval($_REQUEST['twitter_enable']) : 0);
219
220                 // if API is used, default to the chosen settings
221                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'twitter','post_by_default')))
222                         $twitter_enable = 1;
223
224         if(! $twitter_enable)
225             return;
226
227         if(strlen($b['postopts']))
228             $b['postopts'] .= ',';
229         $b['postopts'] .= 'twitter';
230         }
231 }
232
233
234 function twitter_post_hook(&$a,&$b) {
235
236         /**
237          * Post to Twitter
238          */
239
240         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
241         return;
242
243         if(! strstr($b['postopts'],'twitter'))
244                 return;
245
246         if($b['parent'] != $b['id'])
247                 return;
248
249         logger('twitter post invoked');
250
251
252         load_pconfig($b['uid'], 'twitter');
253
254         $ckey    = get_config('twitter', 'consumerkey'  );
255         $csecret = get_config('twitter', 'consumersecret' );
256         $otoken  = get_pconfig($b['uid'], 'twitter', 'oauthtoken'  );
257         $osecret = get_pconfig($b['uid'], 'twitter', 'oauthsecret' );
258
259         if($ckey && $csecret && $otoken && $osecret) {
260                 logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
261
262                 require_once('library/twitteroauth.php');
263                 require_once('include/bbcode.php');     
264                 $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
265                 $max_char = 138; // max. length for a tweet
266                 $msg = strip_tags(bbcode($b['body']));
267                 if ( strlen($msg) > $max_char) {
268                         logger('Twitter: have to shorten the message to fit 140 chars', LOGGER_DEBUG);
269                         $shortlink = "";
270                         require_once('library/slinky.php');
271                         $slinky = new Slinky( $b['plink'] );
272             $yourls_url = get_config('yourls','url1');
273             if ($yourls_url) {
274                                 $max_char = 135;
275                     $yourls_username = get_config('yourls','username1');
276                 $yourls_password = get_config('yourls', 'password1');
277                 $yourls_ssl = get_config('yourls', 'ssl1');
278                 $yourls = new Slinky_YourLS();
279                 $yourls->set( 'username', $yourls_username );
280                 $yourls->set( 'password', $yourls_password );
281                 $yourls->set( 'ssl', $yourls_ssl );
282                 $yourls->set( 'yourls-url', $yourls_url );
283                 $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
284             }
285             else {
286                                 // setup a cascade of shortening services
287                                 // try to get a short link from these services
288                                 // in the order ur1.ca, trim, id.gd, tinyurl
289                                 $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
290                         }
291                         $shortlink = $slinky->short();
292                         // the new message will be shortened such that "... $shortlink"
293                         // will fit into the character limit
294                         $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
295                         $msg .= '... ' . $shortlink;
296                 }
297                 // and now tweet it :-)
298                 if(strlen($msg)) {
299                         $result = $tweet->post('statuses/update', array('status' => $msg));
300                         logger('twitter_post send' , LOGGER_DEBUG);
301                 }
302         }
303 }
304
305 function twitter_plugin_admin_post(&$a){
306         $consumerkey    =       ((x($_POST,'consumerkey'))              ? notags(trim($_POST['consumerkey']))   : '');
307         $consumersecret =       ((x($_POST,'consumersecret'))   ? notags(trim($_POST['consumersecret'])): '');
308         set_config('twitter','consumerkey',$consumerkey);
309         set_config('twitter','consumersecret',$consumersecret);
310         info( t('Settings updated.'). EOL );
311 }
312 function twitter_plugin_admin(&$a, &$o){
313         $t = file_get_contents( dirname(__file__). "/admin.tpl" );
314         $o = replace_macros($t, array(
315                 '$submit' => t('Submit'),
316                                                                 // name, label, value, help, [extra values]
317                 '$consumerkey' => array('consumerkey', t('Consumer key'),  get_config('twitter', 'consumerkey' ), ''),
318                 '$consumersecret' => array('consumersecret', t('Consumer secret'),  get_config('twitter', 'consumersecret' ), '')
319         ));
320 }