]> git.mxchange.org Git - friendica.git/blob - addon/statusnet/statusnet.php
friendika-z initial implementation
[friendica.git] / addon / statusnet / statusnet.php
1 <?php
2 /**
3  * Name: StatusNet Connector
4  * Version: 1.0
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 (same as Friendika)
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         if (isset($_POST['statusnet-disconnect'])) {
93             /***
94              * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
95              * TODO can we revoke the access tokens at Twitter and do we need to do so?
96              */
97             del_pconfig( local_user(), 'statusnet', 'consumerkey'  );
98             del_pconfig( local_user(), 'statusnet', 'consumersecret' );
99             del_pconfig( local_user(), 'statusnet', 'post' );
100             del_pconfig( local_user(), 'statusnet', 'post_by_default' );
101             del_pconfig( local_user(), 'statusnet', 'oauthtoken' );
102             del_pconfig( local_user(), 'statusnet', 'oauthsecret' );
103             del_pconfig( local_user(), 'statusnet', 'baseapi' );
104         } else {
105             if (isset($_POST['statusnet-preconf-apiurl'])) {
106                 /***
107                  * If the user used one of the preconfigured StatusNet server credentials
108                  * use them. All the data are available in the global config.
109                  * Check the API Url never the less and blame the admin if it's not working ^^
110                  */
111                 $globalsn = get_config('statusnet', 'sites');
112                 foreach ( $globalsn as $asn) {
113                     if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
114                         $apibase = $asn['apiurl'];
115                         $c = fetch_url( $apibase . 'statusnet/version.xml' );
116                         if (strlen($c) > 0) {
117                             set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
118                             set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
119                             set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
120                         } else {
121                             notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
122                         }
123                     }
124                 }
125                 goaway($a->get_baseurl().'/settings/addon');
126             } else {
127             if (isset($_POST['statusnet-consumersecret'])) {
128                 //  check if we can reach the API of the StatusNet server
129                 //  we'll check the API Version for that, if we don't get one we'll try to fix the path but will
130                 //  resign quickly after this one try to fix the path ;-)
131                 $apibase = $_POST['statusnet-baseapi'];
132                 $c = fetch_url( $apibase . 'statusnet/version.xml' );
133                 if (strlen($c) > 0) {
134                     //  ok the API path is correct, let's save the settings
135                     set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
136                     set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
137                     set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
138                 } else {
139                     //  the API path is not correct, maybe missing trailing / ?
140                     $apibase = $apibase . '/';
141                     $c = fetch_url( $apibase . 'statusnet/version.xml' );
142                     if (strlen($c) > 0) {
143                         //  ok the API path is now correct, let's save the settings
144                         set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
145                         set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
146                         set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
147                     } else {
148                         //  still not the correct API base, let's do noting
149                         notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
150                     }
151                 }
152                 goaway($a->get_baseurl().'/settings/addon');
153             } else {
154                 if (isset($_POST['statusnet-pin'])) {
155                     //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
156                     logger('got a StatusNet security code');
157                     $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
158                     $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey'  );
159                     $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
160                     //  the token and secret for which the PIN was generated were hidden in the settings
161                     //  form as token and token2, we need a new connection to Twitter using these token
162                     //  and secret to request a Access Token with the PIN
163                     $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
164                     $token   = $connection->getAccessToken( $_POST['statusnet-pin'] );
165                     //  ok, now that we have the Access Token, save them in the user config
166                     set_pconfig(local_user(),'statusnet', 'oauthtoken',  $token['oauth_token']);
167                     set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
168                     set_pconfig(local_user(),'statusnet', 'post', 1);
169                     //  reload the Addon Settings page, if we don't do it see Bug #42
170                     goaway($a->get_baseurl().'/settings/addon');
171                 } else {
172                     //  if no PIN is supplied in the POST variables, the user has changed the setting
173                     //  to post a tweet for every new __public__ posting to the wall
174                     set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
175                     set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
176                         info( t('StatusNet settings updated.') . EOL);
177                 }}}}
178 }
179 function statusnet_settings(&$a,&$s) {
180         if(! local_user())
181                 return;
182         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
183         /***
184          * 1) Check that we have a base api url and a consumer key & secret
185          * 2) If no OAuthtoken & stuff is present, generate button to get some
186          *    allow the user to cancel the connection process at this step
187          * 3) Checkbox for "Send public notices (respect size limitation)
188          */
189         $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
190         $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
191         $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
192         $otoken  = get_pconfig(local_user(), 'statusnet', 'oauthtoken'  );
193         $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
194         $enabled = get_pconfig(local_user(), 'statusnet', 'post');
195         $checked = (($enabled) ? ' checked="checked" ' : '');
196         $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
197         $defchecked = (($defenabled) ? ' checked="checked" ' : '');
198         $s .= '<div class="settings-block">';
199         $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
200
201         if ( (!$ckey) && (!$csecret) ) {
202                 /***
203                  * no consumer keys
204                  */
205             $globalsn = get_config('statusnet', 'sites');
206             /***
207              * lets check if we have one or more globally configured StatusNet
208              * server OAuth credentials in the configuration. If so offer them
209              * with a little explanation to the user as choice - otherwise
210              * ignore this option entirely.
211              */
212             if (! $globalsn == null) {
213                 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
214                 $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>';
215                 $s .= '<div id="statusnet-preconf-wrapper">';
216                 foreach ($globalsn as $asn) {
217                     $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
218                 }
219                 $s .= '<p></p><div class="clear"></div></div>';
220                 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
221             }
222             $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
223             $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>';
224             $s .= '<div id="statusnet-consumer-wrapper">';
225             $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
226             $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
227             $s .= '<div class="clear"></div>';
228             $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
229             $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
230             $s .= '<div class="clear"></div>';
231             $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
232             $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
233             $s .= '<p></p><div class="clear"></div></div>';
234             $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
235         } else {
236                 /***
237                  * ok we have a consumer key pair now look into the OAuth stuff
238                  */
239                 if ( (!$otoken) && (!$osecret) ) {
240                         /***
241                          * the user has not yet connected the account to statusnet
242                          * get a temporary OAuth key/secret pair and display a button with
243                          * which the user can request a PIN to connect the account to a
244                          * account at statusnet
245                          */
246                         $connection = new StatusNetOAuth($api, $ckey, $csecret);
247                         $request_token = $connection->getRequestToken('oob');
248                         $token = $request_token['oauth_token'];
249                         /***
250                          *  make some nice form
251                          */
252                         $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>';
253                         $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
254                         $s .= '<div id="statusnet-pin-wrapper">';
255                         $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
256                         $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
257                         $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
258                         $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
259                         $s .= '</div><div class="clear"></div>';
260                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
261                         $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
262                         $s .= '<div id="statusnet-cancel-wrapper">';
263                         $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
264                         $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
265                         $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
266                         $s .= '</div><div class="clear"></div>';
267                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
268                 } else {
269                         /***
270                          *  we have an OAuth key / secret pair for the user
271                          *  so let's give a chance to disable the postings to statusnet
272                          */
273                         $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
274                         $details = $connection->get('account/verify_credentials');
275                         $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>';
276                         $s .= '<p>'. t('If enabled all your <strong>public</strong> postings will be posted to the associated StatusNet account.') .'</p>';
277                         $s .= '<div id="statusnet-enable-wrapper">';
278                         $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
279                         $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
280                         $s .= '<div class="clear"></div>';
281                         $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
282                         $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
283                         $s .= '</div><div class="clear"></div>';
284
285                         $s .= '<div id="statusnet-disconnect-wrapper">';
286                         $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
287                         $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
288                         $s .= '</div><div class="clear"></div>';
289                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
290                 }
291         }
292         $s .= '</div><div class="clear"></div></div>';
293 }
294
295
296 function statusnet_post_hook(&$a,&$b) {
297
298         /**
299          * Post to statusnet
300          */
301
302         logger('StatusNet post invoked');
303
304         if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (!$b['parent']) ) {
305
306                 // Status.Net is not considered a private network
307                 if($b['prvnets'])
308                         return;
309
310                 load_pconfig(local_user(), 'statusnet');
311             
312                 $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
313                 $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey'  );
314                 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
315                 $otoken  = get_pconfig(local_user(), 'statusnet', 'oauthtoken'  );
316                 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
317
318                 if($ckey && $csecret && $otoken && $osecret) {
319
320                         $statusnet_post = get_pconfig(local_user(),'statusnet','post');
321                         $statusnet_enable = (($statusnet_post && x($_POST,'statusnet_enable')) ? intval($_POST['statusnet_enable']) : 0);
322
323                         if($statusnet_enable && $statusnet_post) {
324                                 require_once('include/bbcode.php');     
325                                 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
326                                 $max_char = $dent->get_maxlength(); // max. length for a dent
327                                 $msg = strip_tags(bbcode($b['body']));
328                                 if ( strlen($msg) > $max_char) {
329                                         $shortlink = "";
330                                         require_once('library/slinky.php');
331                                         // post url = base url + /display/ + owner + post id
332                                         // we construct this from the Owner link and replace
333                                         // profile by display - this will cause an error when
334                                         // /profile/ is in the owner url twice but I don't
335                                         // think this will be very common...
336                                         $posturl = str_replace('/profile/','/display/',$b['owner-link']).'/'.$b['id'];
337                                         $slinky = new Slinky( $posturl );
338                                         // setup a cascade of shortening services
339                                         // try to get a short link from these services
340                                         // in the order ur1.ca, trim, id.gd, tinyurl
341                                         $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
342                                         $shortlink = $slinky->short();
343                                         // the new message will be shortened such that "... $shortlink"
344                                         // will fit into the character limit
345                                         $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
346                                         $msg .= '... ' . $shortlink;
347                                 }
348                                 // and now tweet it :-)
349                                 if(strlen($msg))
350                                         $dent->post('statuses/update', array('status' => $msg));
351                         }
352                 }
353     }
354 }
355
356 function statusnet_plugin_admin_post(&$a){
357         
358         $sites = array();
359         
360         foreach($_POST['sitename'] as $id=>$sitename){
361                 $sitename=trim($sitename);
362                 $apiurl=trim($_POST['apiurl'][$id]);
363                 $secret=trim($_POST['secret'][$id]);
364                 $key=trim($_POST['key'][$id]);
365                 if ($sitename!="" &&
366                         $apiurl!="" &&
367                         $secret!="" &&
368                         $key!="" &&
369                         !x($_POST['delete'][$id])){
370                                 
371                                 $sites[] = Array(
372                                         'sitename' => $sitename,
373                                         'apiurl' => $apiurl,
374                                         'consumersecret' => $secret,
375                                         'consumerkey' => $key
376                                 );
377                 }
378         }
379         
380         $sites = set_config('statusnet','sites', $sites);
381         
382 }
383
384 function statusnet_plugin_admin(&$a, &$o){
385
386         $sites = get_config('statusnet','sites');
387         $sitesform=array();
388         if (is_array($sites)){
389                 foreach($sites as $id=>$s){
390                         $sitesform[] = Array(
391                                 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
392                                 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
393                                 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
394                                 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
395                                 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
396                         );
397                 }
398         }
399         /* empty form to add new site */
400         $id++;
401         $sitesform[] = Array(
402                 'sitename' => Array("sitename[$id]", "Site name", "", ""),
403                 'apiurl' => Array("apiurl[$id]", "Api url", "", ""),
404                 'secret' => Array("secret[$id]", "Secret", "", ""),
405                 'key' => Array("key[$id]", "Key", "", ""),
406         );
407
408         
409         $t = file_get_contents( dirname(__file__). "/admin.tpl" );
410         $o = replace_macros($t, array(
411                 '$submit' => t('Submit'),
412                                                         
413                 '$sites' => $sitesform,
414                 
415         ));
416         
417         
418 }