]> git.mxchange.org Git - friendica.git/blob - addon/twitter/twitter.php
Merge branch 'master' of git://github.com/friendika/friendika
[friendica.git] / addon / twitter / twitter.php
1 <?php
2
3 /*   Twitter Plugin for Friendika
4  *
5  *   Author: Tobias Diekershoff
6  *           tobias.diekershoff@gmx.net
7  *
8  *   License:3-clause BSD license (same as Friendika)
9  *
10  *   Configuration:
11  *     To use this plugin you need a OAuth Consumer key pair (key & secret)
12  *     you can get it from Twitter at https://twitter.com/apps
13  *
14  *     Register your Friendika site as "Client" application with "Read & Write" access
15  *     we do not need "Twitter as login". When you've registered the app you get the
16  *     OAuth Consumer key and secret pair for your application/site.
17  *
18  *     Add this key pair to your global .htconfig.php
19  *
20  *     $a->config['twitter']['consumerkey'] = 'your consumer_key here';
21  *     $a->config['twitter']['consumersecret'] = 'your consumer_secret here';
22  *
23  *     To activate the plugin itself add it to the $a->config['system']['addon']
24  *     setting. After this, your user can configure their Twitter account settings
25  *     from "Settings -> Plugin Settings".
26  *
27  *     Requirements: PHP5, curl [Slinky library]
28  *
29  *     Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/Twitter_Plugin
30  */
31
32 /*   __TODO__
33  *
34  *   - what about multimedia content?
35  *     so far we just strip HTML tags from the message
36  */
37
38 function twitter_install() {
39         //  we need some hooks, for the configuration and for sending tweets
40         register_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
41         register_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
42         register_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
43         register_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
44         logger("installed twitter");
45 }
46
47
48 function twitter_uninstall() {
49         unregister_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
50         unregister_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
51         unregister_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
52         unregister_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
53 }
54
55 function twitter_jot_nets(&$a,&$b) {
56         if(! local_user())
57                 return;
58
59         $tw_post = get_pconfig(local_user(),'twitter','post');
60         if(intval($tw_post) == 1) {
61                 $tw_defpost = get_pconfig(local_user(),'twitter','post_by_default');
62                 $selected = ((intval($tw_defpost) == 1) ? ' checked="checked" ' : '');
63                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="twitter_enable"' . $selected . 'value="1" /> ' 
64                         . t('Post to Twitter') . '</div>';      
65         }
66
67
68 }
69
70 function twitter_settings_post ($a,$post) {
71         if(! local_user())
72                 return;
73         if (isset($_POST['twitter-disconnect'])) {
74                 /***
75                  * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
76                  * from the user configuration
77                  * TODO can we revoke the access tokens at Twitter and do we need to do so?
78                  */
79                 del_pconfig( local_user(), 'twitter', 'consumerkey'  );
80                 del_pconfig( local_user(), 'twitter', 'consumersecret' );
81                 del_pconfig( local_user(), 'twitter', 'post' );
82         } else {
83         if (isset($_POST['twitter-pin'])) {
84                 //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
85                 logger('got a Twitter PIN');
86                 require_once('library/twitteroauth.php');
87                 $ckey    = get_config('twitter', 'consumerkey'  );
88                 $csecret = get_config('twitter', 'consumersecret' );
89                 //  the token and secret for which the PIN was generated were hidden in the settings
90                 //  form as token and token2, we need a new connection to Twitter using these token
91                 //  and secret to request a Access Token with the PIN
92                 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
93                 $token   = $connection->getAccessToken( $_POST['twitter-pin'] );
94                 //  ok, now that we have the Access Token, save them in the user config
95                 set_pconfig(local_user(),'twitter', 'oauthtoken',  $token['oauth_token']);
96                 set_pconfig(local_user(),'twitter', 'oauthsecret', $token['oauth_token_secret']);
97                 set_pconfig(local_user(),'twitter', 'post', 1);
98                 //  reload the Addon Settings page, if we don't do it see Bug #42
99                 header('Location: '.$a->get_baseurl().'/settings/addon');
100         } else {
101                 //  if no PIN is supplied in the POST variables, the user has changed the setting
102                 //  to post a tweet for every new __public__ posting to the wall
103                 set_pconfig(local_user(),'twitter','post',intval($_POST['twitter-enable']));
104         }}
105 }
106 function twitter_settings(&$a,&$s) {
107         if(! local_user())
108                 return;
109         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
110         /***
111          * 1) Check that we have global consumer key & secret
112          * 2) If no OAuthtoken & stuff is present, generate button to get some
113          * 3) Checkbox for "Send public notices (140 chars only)
114          */
115         $ckey    = get_config('twitter', 'consumerkey' );
116         $csecret = get_config('twitter', 'consumersecret' );
117         $otoken  = get_pconfig(local_user(), 'twitter', 'oauthtoken'  );
118         $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' );
119         $enabled = get_pconfig(local_user(), 'twitter', 'post');
120         $checked = (($enabled) ? ' checked="checked" ' : '');
121         $s .= '<div class="settings-block">';
122         $s .= '<h3>'. t('Twitter Posting Settings') .'</h3>';
123
124         if ( (!$ckey) && (!$csecret) ) {
125                 /***
126                  * no global consumer keys
127                  * display warning and skip personal config
128                  */
129                 $s .= '<p>'. t('No consumer key pair for Twitter found. Please contact your site administrator.') .'</p>';
130         } else {
131                 /***
132                  * ok we have a consumer key pair now look into the OAuth stuff
133                  */
134                 if ( (!$otoken) && (!$osecret) ) {
135                         /***
136                          * the user has not yet connected the account to twitter...
137                          * get a temporary OAuth key/secret pair and display a button with
138                          * which the user can request a PIN to connect the account to a
139                          * account at Twitter.
140                          */
141 <<<<<<< HEAD
142                         require_once('library/twitteroauth.php');
143 =======
144                         require_once('library/twitteroauth.php');
145 >>>>>>> a912a0d3cae0ae9c873dcb5c45624a725bd2c2d6
146                         $connection = new TwitterOAuth($ckey, $csecret);
147                         $request_token = $connection->getRequestToken();
148                         $token = $request_token['oauth_token'];
149                         /***
150                          *  make some nice form
151                          */
152                         $s .= '<p>'. t('At this Friendika 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>';
153                         $s .= '<a href="'.$connection->getAuthorizeURL($token).'" target="_twitter"><img src="addon/twitter/lighter.png" alt="'.t('Log in with Twitter').'"></a>';
154                         $s .= '<div id="twitter-pin-wrapper">';
155                         $s .= '<label id="twitter-pin-label" for="twitter-pin">'. t('Copy the PIN from Twitter here') .'</label>';
156                         $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
157                         $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="'.$token.'" />';
158                         $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="'.$request_token['oauth_token_secret'].'" />';
159             $s .= '</div><div class="clear"></div>';
160             $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
161                 } else {
162                         /***
163                          *  we have an OAuth key / secret pair for the user
164                          *  so let's give a chance to disable the postings to Twitter
165                          */
166                         require_once('library/twitteroauth.php');
167                         $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
168                         $details = $connection->get('account/verify_credentials');
169                         $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>';
170                         $s .= '<p>'. t('If enabled all your <strong>public</strong> postings will be posted to the associated Twitter account as well.') .'</p>';
171                         $s .= '<div id="twitter-enable-wrapper">';
172                         $s .= '<label id="twitter-enable-label" for="twitter-checkbox">'. t('Send public postings to Twitter'). '</label>';
173                         $s .= '<input id="twitter-checkbox" type="checkbox" name="twitter-enable" value="1" ' . $checked . '/>';
174                         $s .= '</div><div class="clear"></div>';
175                         $s .= '<div id="twitter-disconnect-wrapper">';
176                         $s .= '<label id="twitter-disconnect-label" for="twitter-disconnect">'. t('Clear OAuth configuration') .'</label>';
177                         $s .= '<input id="twitter-disconnect" type="checkbox" name="twitter-disconnect" value="1" />';
178                         $s .= '</div><div class="clear"></div>';
179                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
180                 }
181         }
182         $s .= '</div><div class="clear"></div></div>';
183 }
184
185
186 function twitter_post_hook(&$a,&$b) {
187
188         /**
189          * Post to Twitter
190          */
191
192         logger('twitter post invoked');
193
194         if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (! $b['parent']) ) {
195
196                 load_pconfig(local_user(), 'twitter');
197
198                 $ckey    = get_config('twitter', 'consumerkey'  );
199                 $csecret = get_config('twitter', 'consumersecret' );
200                 $otoken  = get_pconfig(local_user(), 'twitter', 'oauthtoken'  );
201                 $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' );
202
203                 if($ckey && $csecret && $otoken && $osecret) {
204
205                         $twitter_post = intval(get_pconfig(local_user(),'twitter','post'));
206                         $twitter_enable = (($twitter_post && x($_POST,'twitter_enable')) ? intval($_POST['twitter_enable']) : 0);
207
208                         if($twitter_post && $twitter_enable) {
209                                 require_once('library/twitteroauth.php');
210                                 require_once('include/bbcode.php');     
211                                 $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
212                                 $max_char = 140; // max. length for a tweet
213                                 $msg = strip_tags(bbcode($b['body']));
214                                 if ( strlen($msg) > $max_char) {
215                                         $shortlink = "";
216                                         require_once('library/slinky.php');
217                                         // post url = base url + /display/ + owner + post id
218                                         // we construct this from the Owner link and replace
219                                         // profile by display - this will cause an error when
220                                         // /profile/ is in the owner url twice but I don't
221                                         // think this will be very common...
222                                         $posturl = str_replace('/profile/','/display/',$b['owner-link']).'/'.$b['id'];
223                                         $slinky = new Slinky( $posturl );
224                                         // setup a cascade of shortening services
225                                         // try to get a short link from these services
226                                         // in the order ur1.ca, trim, id.gd, tinyurl
227                                         $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
228                                         $shortlink = $slinky->short();
229                                         // the new message will be shortened such that "... $shortlink"
230                                         // will fit into the character limit
231                                         $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
232                                         $msg .= '... ' . $shortlink;
233                                 }
234                 // and now tweet it :-)
235                                 if(strlen($msg))
236                                         $tweet->post('statuses/update', array('status' => $msg));
237                         }
238                 }
239         }
240 }
241