]> git.mxchange.org Git - friendica.git/blob - addon/twitter/twitter.php
8f4f74f7f7a1bafc88c96037e898d7e2de17b858
[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  *   - deletion of the OAuth credentials does not work
35  *   - what about multimedia content?
36  *     so far we just strip HTML tags from the message
37  *   - after entering the PIN reload page propperly
38  */
39
40 function twitter_install() {
41         //  we need some hooks, for the configuration and for sending tweets
42         register_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
43         register_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
44         register_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
45         logger("installed twitter");
46 }
47
48
49 function twitter_uninstall() {
50         unregister_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
51         unregister_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
52         unregister_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
53 }
54
55 function twitter_settings_post ($a,$post) {
56         if(! local_user())
57                 return;
58         if (isset($_POST['twitter-disconnect'])) {
59                 /***
60                  * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
61                  * from the user configuration
62                  * TODO this does not work that way!?
63                  * TODO can we revoke the access tokens at Twitter and do we need to do so?
64                  */
65                 del_pconfig( local_user(), 'twitter', 'consumerkey'  );
66                 del_pconfig( local_user(), 'twitter', 'consumersecret' );
67                 del_pconfig( local_user(), 'twitter', 'post' );
68         } else {
69         if (isset($_POST['twitter-pin'])) {
70                 //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
71                 logger('got a Twitter PIN');
72                 require_once('addon/twitter/twitteroauth.php');
73                 $ckey    = get_config('twitter', 'consumerkey'  );
74                 $csecret = get_config('twitter', 'consumersecret' );
75                 //  the token and secret for which the PIN was generated were hidden in the settings
76                 //  form as token and token2, we need a new connection to Twitter using these token
77                 //  and secret to request a Access Token with the PIN
78                 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
79                 $token   = $connection->getAccessToken( $_POST['twitter-pin'] );
80                 //  ok, now that we have the Access Token, save them in the user config
81                 set_pconfig(local_user(),'twitter', 'oauthtoken',  $token['oauth_token']);
82                 set_pconfig(local_user(),'twitter', 'oauthsecret', $token['oauth_token_secret']);
83                 set_pconfig(local_user(),'twitter', 'post', 1);
84                 //  reload the Addon Settings page, if we don't do it see Bug #42
85                 header('Location: '.$a->get_baseurl().'/settings/addon');
86         } else {
87                 //  if no PIN is supplied in the POST variables, the user has changed the setting
88                 //  to post a tweet for every new __public__ posting to the wall
89                 set_pconfig(local_user(),'twitter','post',intval($_POST['twitter']));
90         }}
91 }
92 function twitter_settings(&$a,&$s) {
93         if(! local_user())
94                 return;
95         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
96         /***
97          * 1) Check that we have global consumer key & secret
98          * 2) If no OAuthtoken & stuff is present, generate button to get some
99          * 3) Checkbox for "Send public notices (140 chars only)
100          */
101         $ckey    = get_config('twitter', 'consumerkey' );
102         $csecret = get_config('twitter', 'consumersecret' );
103         $otoken  = get_pconfig(local_user(), 'twitter', 'oauthtoken'  );
104         $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' );
105         $enabled = get_pconfig(local_user(), 'twitter', 'post');
106         $checked = (($enabled) ? ' checked="checked" ' : '');
107         $s .= '<h3>'.t('Twitter Posting Settings').'</h3>';
108
109         if ( (!$ckey) && (!$csecret) ) {
110                 /***
111                  * no global consumer keys
112                  * display warning and skip personal config
113                  */
114                 $s .= '<p>'.t('No consumer key pair for Twitter found. Please contact your site administrator.').'</p>';
115         } else {
116                 /***
117                  * ok we have a consumer key pair now look into the OAuth stuff
118                  */
119                 if ( (!$otoken) && (!$osecret) ) {
120                         /***
121                          * the user has not yet connected the account to twitter...
122                          * get a temporary OAuth key/secret pair and display a button with
123                          * which the user can request a PIN to connect the account to a
124                          * account at Twitter.
125                          */
126                         require_once('addon/twitter/twitteroauth.php');
127                         $connection = new TwitterOAuth($ckey, $csecret);
128                         $request_token = $connection->getRequestToken();
129                         $token = $request_token['oauth_token'];
130                         /***
131                          *  make some nice form
132                          */
133                         $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>';
134                         $s .= '<a href="'.$connection->getAuthorizeURL($token).'" target="_twitter"><img src="addon/twitter/lighter.png" alt="'.t('Log in with Twitter').'></a>';
135                         $s .= '<div id="twitter-pin-wrapper">';
136                         $s .= '<label id="twitter-pin-label" for="twitter-pin">'.t('Copy the PIN from Twitter here').'</label>';
137                         $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
138                         $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="'.$token.'" />';
139                         $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="'.$request_token['oauth_token_secret'].'" />';
140                         $s .= '</div><div class="clear"></div>';
141                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
142                 } else {
143                         /***
144                          *  we have an OAuth key / secret pair for the user
145                          *  so let's give a chance to disable the postings to Twitter
146                          */
147                         require_once('addon/twitter/twitteroauth.php');
148                         $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
149                         $details = $connection->get('account/verify_credentials');
150                         $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>';
151                         $s .= '<p>'.t('If enabled all your <strong>public</strong> postings will be posted to the associated Twitter account as well.').'</p>';
152                         $s .= '<div id="twitter-enable-wrapper">';
153                         $s .= '<label id="twitter-enable-label" for="twitter-checkbox">'.t('Send public postings to Twitter').'</label>';
154                         $s .= '<input id="twitter-checkbox" type="checkbox" name="twitter" value="1" ' . $checked . '/>';
155                         $s .= '</div><div class="clear"></div>';
156                         $s .= '<div id="twitter-disconnect-wrapper">';
157                         $s .= '<label id="twitter-disconnect-label" for="twitter-disconnect">'.t('Clear OAuth configuration').'</label>';
158                         $s .= '<input id="twitter-disconnect" type="checkbox" name="twitter-disconnect" value="1" />';
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                 }
162         }
163         $s .= '</div><div class="clear"></div>';
164 }
165
166
167 function twitter_post_hook(&$a,&$b) {
168
169         /**
170          * Post to Twitter
171          */
172
173         logger('twitter post invoked');
174
175         if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
176
177                 load_pconfig(local_user(), 'twitter');
178
179                 $ckey    = get_config('twitter', 'consumerkey'  );
180                 $csecret = get_config('twitter', 'consumersecret' );
181                 $otoken  = get_pconfig(local_user(), 'twitter', 'oauthtoken'  );
182                 $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' );
183
184                 if($ckey && $csecret && $otoken && $osecret) {
185
186                         $twitter_post = get_pconfig(local_user(),'twitter','post');
187
188                         if($twitter_post) {
189                                 require_once('addon/twitter/twitteroauth.php');
190                                 require_once('include/bbcode.php');     
191                                 $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
192                                 $max_char = 140; // max. length for a tweet
193                                 $msg = strip_tags(bbcode($b['body']));
194                                 if ( strlen($msg) > $max_char) {
195                                         $shortlink = "";
196                                         require_once('addon/twitter/slinky.php');
197                                         // post url = base url + /display/ + owner + post id
198                                         // we construct this from the Owner link and replace
199                                         // profile by display - this will cause an error when
200                                         // /profile/ is in the owner url twice but I don't
201                                         // think this will be very common...
202                                         $posturl = str_replace('/profile/','/display/',$b['owner-link']).'/'.$b['id'];
203                                         $slinky = new Slinky( $posturl );
204                                         // setup a cascade of shortening services
205                                         // try to get a short link from these services
206                                         // in the order ur1.ca, trim, id.gd, tinyurl
207                                         $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
208                                         $shortlink = $slinky->short();
209                                         // the new message will be shortened such that "... $shortlink"
210                                         // will fit into the character limit
211                                         $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
212                                         $msg .= '... ' . $shortlink;
213                                 }
214                                 // and now tweet it :-)
215                                 $tweet->post('statuses/update', array('status' => $msg));
216                         }
217                 }
218         }
219 }
220