]> git.mxchange.org Git - friendica.git/blob - addon/statusnet/statusnet.php
add info() function. Works like notice() but show messages in a div with class info...
[friendica.git] / addon / statusnet / statusnet.php
1 <?php
2
3 /*   StatusNet 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 activate the plugin itself add it to the $a->config['system']['addon']
12  *     setting. After this, your user can configure their Twitter account settings
13  *     from "Settings -> Plugin Settings".
14  *
15  *     Requirements: PHP5, curl [Slinky library]
16  *
17  *     Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/StatusNet_Plugin
18  */
19
20 /*   __TODO__
21  *
22  *   - what about multimedia content?
23  *     so far we just strip HTML tags from the message
24  */
25
26
27 /***
28  * We have to alter the TwitterOAuth class a little bit to work with any StatusNet
29  * installation abroad. Basically it's only make the API path variable and be happy.
30  *
31  * Thank you guys for the Twitter compatible API!
32  */
33
34 require_once('library/twitteroauth.php');
35
36 class StatusNetOAuth extends TwitterOAuth {
37     function get_maxlength() {
38         $config = $this->get($this->host . 'statusnet/config.json');
39         return $config->site->textlimit;
40     }
41     function accessTokenURL()  { return $this->host.'oauth/access_token'; }
42     function authenticateURL() { return $this->host.'oauth/authenticate'; } 
43     function authorizeURL() { return $this->host.'oauth/authorize'; }
44     function requestTokenURL() { return $this->host.'oauth/request_token'; }
45     function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
46         parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
47         $this->host = $apipath;
48     }
49 }
50
51 function statusnet_install() {
52         //  we need some hooks, for the configuration and for sending tweets
53         register_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
54         register_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
55         register_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
56         register_hook('jot_networks',    'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
57
58         logger("installed statusnet");
59 }
60
61
62 function statusnet_uninstall() {
63         unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
64         unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
65         unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
66         unregister_hook('jot_networks',    'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
67 }
68
69 function statusnet_jot_nets(&$a,&$b) {
70         if(! local_user())
71                 return;
72
73         $statusnet_post = get_pconfig(local_user(),'statusnet','post');
74         if(intval($statusnet_post) == 1) {
75                 $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default');
76                 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
77                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . 'value="1" /> ' 
78                         . t('Post to StatusNet') . '</div>';    
79         }
80 }
81
82
83
84
85 function statusnet_settings_post ($a,$post) {
86         if(! local_user())
87             return;
88         if (isset($_POST['statusnet-disconnect'])) {
89             /***
90              * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
91              * TODO can we revoke the access tokens at Twitter and do we need to do so?
92              */
93             del_pconfig( local_user(), 'statusnet', 'consumerkey'  );
94             del_pconfig( local_user(), 'statusnet', 'consumersecret' );
95             del_pconfig( local_user(), 'statusnet', 'post' );
96             del_pconfig( local_user(), 'statusnet', 'post_by_default' );
97             del_pconfig( local_user(), 'statusnet', 'oauthtoken' );
98             del_pconfig( local_user(), 'statusnet', 'oauthsecret' );
99             del_pconfig( local_user(), 'statusnet', 'baseapi' );
100         } else {
101             if (isset($_POST['statusnet-preconf-apiurl'])) {
102                 /***
103                  * If the user used one of the preconfigured StatusNet server credentials
104                  * use them. All the data are available in the global config.
105                  * Check the API Url never the less and blame the admin if it's not working ^^
106                  */
107                 $globalsn = get_config('statusnet', 'sites');
108                 foreach ( $globalsn as $asn) {
109                     if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
110                         $apibase = $asn['apiurl'];
111                         $c = fetch_url( $apibase . 'statusnet/version.xml' );
112                         if (strlen($c) > 0) {
113                             set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
114                             set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
115                             set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
116                         } else {
117                             notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
118                         }
119                     }
120                 }
121                 goaway($a->get_baseurl().'/settings/addon');
122             } else {
123             if (isset($_POST['statusnet-consumersecret'])) {
124                 //  check if we can reach the API of the StatusNet server
125                 //  we'll check the API Version for that, if we don't get one we'll try to fix the path but will
126                 //  resign quickly after this one try to fix the path ;-)
127                 $apibase = $_POST['statusnet-baseapi'];
128                 $c = fetch_url( $apibase . 'statusnet/version.xml' );
129                 if (strlen($c) > 0) {
130                     //  ok the API path is correct, let's save the settings
131                     set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
132                     set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
133                     set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
134                 } else {
135                     //  the API path is not correct, maybe missing trailing / ?
136                     $apibase = $apibase . '/';
137                     $c = fetch_url( $apibase . 'statusnet/version.xml' );
138                     if (strlen($c) > 0) {
139                         //  ok the API path is now correct, let's save the settings
140                         set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
141                         set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
142                         set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
143                     } else {
144                         //  still not the correct API base, let's do noting
145                         notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
146                     }
147                 }
148                 goaway($a->get_baseurl().'/settings/addon');
149             } else {
150                 if (isset($_POST['statusnet-pin'])) {
151                     //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
152                     logger('got a StatusNet security code');
153                     $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
154                     $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey'  );
155                     $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
156                     //  the token and secret for which the PIN was generated were hidden in the settings
157                     //  form as token and token2, we need a new connection to Twitter using these token
158                     //  and secret to request a Access Token with the PIN
159                     $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
160                     $token   = $connection->getAccessToken( $_POST['statusnet-pin'] );
161                     //  ok, now that we have the Access Token, save them in the user config
162                     set_pconfig(local_user(),'statusnet', 'oauthtoken',  $token['oauth_token']);
163                     set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
164                     set_pconfig(local_user(),'statusnet', 'post', 1);
165                     //  reload the Addon Settings page, if we don't do it see Bug #42
166                     goaway($a->get_baseurl().'/settings/addon');
167                 } else {
168                     //  if no PIN is supplied in the POST variables, the user has changed the setting
169                     //  to post a tweet for every new __public__ posting to the wall
170                     set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
171                     set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
172                         info( t('StatusNet settings updated.') . EOL);
173                 }}}}
174 }
175 function statusnet_settings(&$a,&$s) {
176         if(! local_user())
177                 return;
178         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
179         /***
180          * 1) Check that we have a base api url and a consumer key & secret
181          * 2) If no OAuthtoken & stuff is present, generate button to get some
182          *    allow the user to cancel the connection process at this step
183          * 3) Checkbox for "Send public notices (respect size limitation)
184          */
185         $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
186         $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
187         $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
188         $otoken  = get_pconfig(local_user(), 'statusnet', 'oauthtoken'  );
189         $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
190         $enabled = get_pconfig(local_user(), 'statusnet', 'post');
191         $checked = (($enabled) ? ' checked="checked" ' : '');
192         $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
193         $defchecked = (($defenabled) ? ' checked="checked" ' : '');
194         $s .= '<div class="settings-block">';
195         $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
196
197         if ( (!$ckey) && (!$csecret) ) {
198                 /***
199                  * no consumer keys
200                  */
201             $globalsn = get_config('statusnet', 'sites');
202             /***
203              * lets check if we have one or more globally configured StatusNet
204              * server OAuth credentials in the configuration. If so offer them
205              * with a little explanation to the user as choice - otherwise
206              * ignore this option entirely.
207              */
208             if (! $globalsn == null) {
209                 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
210                 $s .= '<p>'. t('There are preconfigured OAuth key pairs for some StatusNet servers available. If you are useing one of them, please use these credentials. If not feel free to connect to any other StatusNet instance (see below).') .'</p>';
211                 $s .= '<div id="statusnet-preconf-wrapper">';
212                 foreach ($globalsn as $asn) {
213                     $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
214                 }
215                 $s .= '<p></p><div class="clear"></div></div>';
216                 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
217             }
218             $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
219             $s .= '<p>'. t('No consumer key pair for StatusNet found. Register your Friendika Account as an desktop client on your StatusNet account, copy the consumer key pair here and enter the API base root.<br />Before you register your own OAuth key pair ask the administrator if there is already a key pair for this Friendika installation at your favorited StatusNet installation.') .'</p>';
220             $s .= '<div id="statusnet-consumer-wrapper">';
221             $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
222             $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
223             $s .= '<div class="clear"></div>';
224             $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
225             $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
226             $s .= '<div class="clear"></div>';
227             $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
228             $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
229             $s .= '<p></p><div class="clear"></div></div>';
230             $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
231         } else {
232                 /***
233                  * ok we have a consumer key pair now look into the OAuth stuff
234                  */
235                 if ( (!$otoken) && (!$osecret) ) {
236                         /***
237                          * the user has not yet connected the account to statusnet
238                          * get a temporary OAuth key/secret pair and display a button with
239                          * which the user can request a PIN to connect the account to a
240                          * account at statusnet
241                          */
242                         $connection = new StatusNetOAuth($api, $ckey, $csecret);
243                         $request_token = $connection->getRequestToken('oob');
244                         $token = $request_token['oauth_token'];
245                         /***
246                          *  make some nice form
247                          */
248                         $s .= '<p>'. t('To connect to your StatusNet account click the button below to get a security code from StatusNet which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to StatusNet.') .'</p>';
249                         $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
250                         $s .= '<div id="statusnet-pin-wrapper">';
251                         $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
252                         $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
253                         $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
254                         $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
255                         $s .= '</div><div class="clear"></div>';
256                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
257                         $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
258                         $s .= '<div id="statusnet-cancel-wrapper">';
259                         $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
260                         $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
261                         $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
262                         $s .= '</div><div class="clear"></div>';
263                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
264                 } else {
265                         /***
266                          *  we have an OAuth key / secret pair for the user
267                          *  so let's give a chance to disable the postings to statusnet
268                          */
269                         $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
270                         $details = $connection->get('account/verify_credentials');
271                         $s .= '<div id="statusnet-info" ><img id="statusnet-avatar" src="'.$details->profile_image_url.'" /><p id="statusnet-info-block">'. t('Currently connected to: ') .'<a href="'.$details->statusnet_profile_url.'" target="_statusnet">'.$details->screen_name.'</a><br /><em>'.$details->description.'</em></p></div>';
272                         $s .= '<p>'. t('If enabled all your <strong>public</strong> postings will be posted to the associated StatusNet account.') .'</p>';
273                         $s .= '<div id="statusnet-enable-wrapper">';
274                         $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
275                         $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
276                         $s .= '<div class="clear"></div>';
277                         $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
278                         $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
279                         $s .= '</div><div class="clear"></div>';
280
281                         $s .= '<div id="statusnet-disconnect-wrapper">';
282                         $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
283                         $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
284                         $s .= '</div><div class="clear"></div>';
285                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
286                 }
287         }
288         $s .= '</div><div class="clear"></div></div>';
289 }
290
291
292 function statusnet_post_hook(&$a,&$b) {
293
294         /**
295          * Post to statusnet
296          */
297
298         logger('StatusNet post invoked');
299
300         if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (!$b['parent']) ) {
301
302                 load_pconfig(local_user(), 'statusnet');
303             
304                 $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
305                 $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey'  );
306                 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
307                 $otoken  = get_pconfig(local_user(), 'statusnet', 'oauthtoken'  );
308                 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
309
310                 if($ckey && $csecret && $otoken && $osecret) {
311
312                         $statusnet_post = get_pconfig(local_user(),'statusnet','post');
313                         $statusnet_enable = (($statusnet_post && x($_POST,'statusnet_enable')) ? intval($_POST['statusnet_enable']) : 0);
314
315                         if($statusnet_enable && $statusnet_post) {
316                                 require_once('include/bbcode.php');     
317                                 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
318                                 $max_char = $dent->get_maxlength(); // max. length for a dent
319                                 $msg = strip_tags(bbcode($b['body']));
320                                 if ( strlen($msg) > $max_char) {
321                                         $shortlink = "";
322                                         require_once('library/slinky.php');
323                                         // post url = base url + /display/ + owner + post id
324                                         // we construct this from the Owner link and replace
325                                         // profile by display - this will cause an error when
326                                         // /profile/ is in the owner url twice but I don't
327                                         // think this will be very common...
328                                         $posturl = str_replace('/profile/','/display/',$b['owner-link']).'/'.$b['id'];
329                                         $slinky = new Slinky( $posturl );
330                                         // setup a cascade of shortening services
331                                         // try to get a short link from these services
332                                         // in the order ur1.ca, trim, id.gd, tinyurl
333                                         $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
334                                         $shortlink = $slinky->short();
335                                         // the new message will be shortened such that "... $shortlink"
336                                         // will fit into the character limit
337                                         $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
338                                         $msg .= '... ' . $shortlink;
339                                 }
340                                 // and now tweet it :-)
341                                 if(strlen($msg))
342                                         $dent->post('statuses/update', array('status' => $msg));
343                         }
344                 }
345     }
346 }
347