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