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