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