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