]> git.mxchange.org Git - friendica-addons.git/blob - statusnet/statusnet.php
Merge remote branch 'upstream/master'
[friendica-addons.git] / statusnet / statusnet.php
1 <?php
2 /**
3  * Name: StatusNet Connector
4  * Description: Relay public postings to a connected StatusNet account
5  * Version: 1.0.5
6  * Author: Tobias Diekershoff <http://diekershoff.homeunix.net/friendika/profile/tobias>
7  */
8  
9 /*   StatusNet Plugin for Friendica
10  *
11  *   Author: Tobias Diekershoff
12  *           tobias.diekershoff@gmx.net
13  *
14  *   License:3-clause BSD license
15  *
16  *   Configuration:
17  *     To activate the plugin itself add it to the $a->config['system']['addon']
18  *     setting. After this, your user can configure their Twitter account settings
19  *     from "Settings -> Plugin Settings".
20  *
21  *     Requirements: PHP5, curl [Slinky library]
22  *
23  *     Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/StatusNet_Plugin
24  */
25
26 /***
27  * We have to alter the TwitterOAuth class a little bit to work with any StatusNet
28  * installation abroad. Basically it's only make the API path variable and be happy.
29  *
30  * Thank you guys for the Twitter compatible API!
31  */
32
33 require_once('library/twitteroauth.php');
34
35 class StatusNetOAuth extends TwitterOAuth {
36     function get_maxlength() {
37         $config = $this->get($this->host . 'statusnet/config.json');
38         return $config->site->textlimit;
39     }
40     function accessTokenURL()  { return $this->host.'oauth/access_token'; }
41     function authenticateURL() { return $this->host.'oauth/authenticate'; } 
42     function authorizeURL() { return $this->host.'oauth/authorize'; }
43     function requestTokenURL() { return $this->host.'oauth/request_token'; }
44     function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
45         parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
46         $this->host = $apipath;
47     }
48   /**
49    * Make an HTTP request
50    *
51    * @return API results
52    *
53    * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
54    */
55   function http($url, $method, $postfields = NULL) {
56     $this->http_info = array();
57     $ci = curl_init();
58     /* Curl settings */
59     $prx = get_config('system','proxy');
60     if(strlen($prx)) {
61         curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
62         curl_setopt($ci, CURLOPT_PROXY, $prx);
63         $prxusr = get_config('system','proxyuser');
64         if(strlen($prxusr))
65             curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
66     }
67     curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
68     curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
69     curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
70     curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
71     curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
72     curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
73     curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
74     curl_setopt($ci, CURLOPT_HEADER, FALSE);
75
76     switch ($method) {
77       case 'POST':
78         curl_setopt($ci, CURLOPT_POST, TRUE);
79         if (!empty($postfields)) {
80           curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
81         }
82         break;
83       case 'DELETE':
84         curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
85         if (!empty($postfields)) {
86           $url = "{$url}?{$postfields}";
87         }
88     }
89
90     curl_setopt($ci, CURLOPT_URL, $url);
91     $response = curl_exec($ci);
92     $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
93     $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
94     $this->url = $url;
95     curl_close ($ci);
96     return $response;
97   }
98 }
99
100 function statusnet_install() {
101         //  we need some hooks, for the configuration and for sending tweets
102         register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
103         register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
104         register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
105         register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
106         register_hook('jot_networks',    'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
107         logger("installed statusnet");
108 }
109
110
111 function statusnet_uninstall() {
112         unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
113         unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
114         unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
115         unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
116         unregister_hook('jot_networks',    'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
117
118         // old setting - remove only
119         unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
120         unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
121         unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
122
123 }
124
125 function statusnet_jot_nets(&$a,&$b) {
126         if(! local_user())
127                 return;
128
129         $statusnet_post = get_pconfig(local_user(),'statusnet','post');
130         if(intval($statusnet_post) == 1) {
131                 $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default');
132                 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
133                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> ' 
134                         . t('Post to StatusNet') . '</div>';    
135         }
136 }
137
138
139
140
141 function statusnet_settings_post ($a,$post) {
142         if(! local_user())
143             return;
144         // don't check statusnet settings if statusnet submit button is not clicked
145         if (!x($_POST,'statusnet-submit')) return;
146         
147         if (isset($_POST['statusnet-disconnect'])) {
148             /***
149              * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
150              */
151             del_pconfig( local_user(), 'statusnet', 'consumerkey'  );
152             del_pconfig( local_user(), 'statusnet', 'consumersecret' );
153             del_pconfig( local_user(), 'statusnet', 'post' );
154             del_pconfig( local_user(), 'statusnet', 'post_by_default' );
155             del_pconfig( local_user(), 'statusnet', 'oauthtoken' );
156             del_pconfig( local_user(), 'statusnet', 'oauthsecret' );
157             del_pconfig( local_user(), 'statusnet', 'baseapi' );
158             del_pconfig( local_user(), 'statusnet', 'post_taglinks');
159         } else {
160             if (isset($_POST['statusnet-preconf-apiurl'])) {
161                 /***
162                  * If the user used one of the preconfigured StatusNet server credentials
163                  * use them. All the data are available in the global config.
164                  * Check the API Url never the less and blame the admin if it's not working ^^
165                  */
166                 $globalsn = get_config('statusnet', 'sites');
167                 foreach ( $globalsn as $asn) {
168                     if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
169                         $apibase = $asn['apiurl'];
170                         $c = fetch_url( $apibase . 'statusnet/version.xml' );
171                         if (strlen($c) > 0) {
172                             set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
173                             set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
174                             set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
175                         } else {
176                             notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
177                         }
178                     }
179                 }
180                 goaway($a->get_baseurl().'/settings/connectors');
181             } else {
182             if (isset($_POST['statusnet-consumersecret'])) {
183                 //  check if we can reach the API of the StatusNet server
184                 //  we'll check the API Version for that, if we don't get one we'll try to fix the path but will
185                 //  resign quickly after this one try to fix the path ;-)
186                 $apibase = $_POST['statusnet-baseapi'];
187                 $c = fetch_url( $apibase . 'statusnet/version.xml' );
188                 if (strlen($c) > 0) {
189                     //  ok the API path is correct, let's save the settings
190                     set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
191                     set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
192                     set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
193                 } else {
194                     //  the API path is not correct, maybe missing trailing / ?
195                     $apibase = $apibase . '/';
196                     $c = fetch_url( $apibase . 'statusnet/version.xml' );
197                     if (strlen($c) > 0) {
198                         //  ok the API path is now correct, let's save the settings
199                         set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
200                         set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
201                         set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
202                     } else {
203                         //  still not the correct API base, let's do noting
204                         notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
205                     }
206                 }
207                 goaway($a->get_baseurl().'/settings/connectors');
208             } else {
209                 if (isset($_POST['statusnet-pin'])) {
210                         //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
211                     $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
212                                         $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey'  );
213                                         $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
214                                         //  the token and secret for which the PIN was generated were hidden in the settings
215                                         //  form as token and token2, we need a new connection to Twitter using these token
216                                         //  and secret to request a Access Token with the PIN
217                                         $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
218                                         $token   = $connection->getAccessToken( $_POST['statusnet-pin'] );
219                                         //  ok, now that we have the Access Token, save them in the user config
220                                         set_pconfig(local_user(),'statusnet', 'oauthtoken',  $token['oauth_token']);
221                                         set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
222                                         set_pconfig(local_user(),'statusnet', 'post', 1);
223                                         set_pconfig(local_user(),'statusnet', 'post_taglinks', 1);
224                     //  reload the Addon Settings page, if we don't do it see Bug #42
225                     goaway($a->get_baseurl().'/settings/connectors');
226                                 } else {
227                                         //  if no PIN is supplied in the POST variables, the user has changed the setting
228                                         //  to post a dent for every new __public__ posting to the wall
229                                         set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
230                                         set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
231                                         set_pconfig(local_user(),'statusnet','post_taglinks',intval($_POST['statusnet-sendtaglinks']));
232                                         info( t('StatusNet settings updated.') . EOL);
233                 }}}}
234 }
235 function statusnet_settings(&$a,&$s) {
236         if(! local_user())
237                 return;
238         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
239         /***
240          * 1) Check that we have a base api url and a consumer key & secret
241          * 2) If no OAuthtoken & stuff is present, generate button to get some
242          *    allow the user to cancel the connection process at this step
243          * 3) Checkbox for "Send public notices (respect size limitation)
244          */
245         $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
246         $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
247         $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
248         $otoken  = get_pconfig(local_user(), 'statusnet', 'oauthtoken'  );
249         $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
250         $enabled = get_pconfig(local_user(), 'statusnet', 'post');
251         $checked = (($enabled) ? ' checked="checked" ' : '');
252         $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
253         $defchecked = (($defenabled) ? ' checked="checked" ' : '');
254         $linksenabled = get_pconfig(local_user(),'statusnet','post_taglinks');
255         $linkschecked = (($linksenabled) ? ' checked="checked" ' : '');
256         $s .= '<div class="settings-block">';
257         $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
258
259         if ( (!$ckey) && (!$csecret) ) {
260                 /***
261                  * no consumer keys
262                  */
263             $globalsn = get_config('statusnet', 'sites');
264             /***
265              * lets check if we have one or more globally configured StatusNet
266              * server OAuth credentials in the configuration. If so offer them
267              * with a little explanation to the user as choice - otherwise
268              * ignore this option entirely.
269              */
270             if (! $globalsn == null) {
271                 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
272                 $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>';
273                 $s .= '<div id="statusnet-preconf-wrapper">';
274                 foreach ($globalsn as $asn) {
275                     $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
276                 }
277                 $s .= '<p></p><div class="clear"></div></div>';
278                 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
279             }
280             $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
281             $s .= '<p>'. t('No consumer key pair for StatusNet found. Register your Friendica 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 Friendica installation at your favorited StatusNet installation.') .'</p>';
282             $s .= '<div id="statusnet-consumer-wrapper">';
283             $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
284             $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
285             $s .= '<div class="clear"></div>';
286             $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
287             $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
288             $s .= '<div class="clear"></div>';
289             $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
290             $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
291             $s .= '<p></p><div class="clear"></div></div>';
292             $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
293         } else {
294                 /***
295                  * ok we have a consumer key pair now look into the OAuth stuff
296                  */
297                 if ( (!$otoken) && (!$osecret) ) {
298                         /***
299                          * the user has not yet connected the account to statusnet
300                          * get a temporary OAuth key/secret pair and display a button with
301                          * which the user can request a PIN to connect the account to a
302                          * account at statusnet
303                          */
304                         $connection = new StatusNetOAuth($api, $ckey, $csecret);
305                         $request_token = $connection->getRequestToken('oob');
306                         $token = $request_token['oauth_token'];
307                         /***
308                          *  make some nice form
309                          */
310                         $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>';
311                         $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
312                         $s .= '<div id="statusnet-pin-wrapper">';
313                         $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
314                         $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
315                         $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
316                         $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
317                         $s .= '</div><div class="clear"></div>';
318                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
319                         $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
320                         $s .= '<div id="statusnet-cancel-wrapper">';
321                         $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
322                         $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
323                         $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
324                         $s .= '</div><div class="clear"></div>';
325                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
326                 } else {
327                         /***
328                          *  we have an OAuth key / secret pair for the user
329                          *  so let's give a chance to disable the postings to statusnet
330                          */
331                         $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
332                         $details = $connection->get('account/verify_credentials');
333                         $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>';
334                         $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>';
335                         if ($a->user['hidewall']) {
336                             $s .= '<p>'. t('<strong>Note</strong>: Due your privacy settings (<em>Hide your profile details from unknown viewers?</em>) the link potentially included in public postings relayed to StatusNet will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') .'</p>';
337                         }
338                         $s .= '<div id="statusnet-enable-wrapper">';
339                         $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
340                         $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
341                         $s .= '<div class="clear"></div>';
342                         $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
343                         $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
344                         $s .= '<div class="clear"></div>';
345                         $s .= '<label id="statusnet-sendtaglinks-label" for="statusnet-sendtaglinks">'.t('Send linked #-tags and @-names to StatusNet').'</label>';
346                         $s .= '<input id="statusnet-sendtaglinks" type="checkbox" name="statusnet-sendtaglinks" value="1" '. $linkschecked . '/>';
347                         $s .= '</div><div class="clear"></div>';
348
349                         $s .= '<div id="statusnet-disconnect-wrapper">';
350                         $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
351                         $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
352                         $s .= '</div><div class="clear"></div>';
353                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
354                 }
355         }
356         $s .= '</div><div class="clear"></div></div>';
357 }
358
359
360 function statusnet_post_local(&$a,&$b) {
361         if($b['edit'])
362                 return;
363
364         if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
365
366                 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
367                 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
368
369                 // if API is used, default to the chosen settings
370                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
371                         $statusnet_enable = 1;
372
373        if(! $statusnet_enable)
374             return;
375
376        if(strlen($b['postopts']))
377            $b['postopts'] .= ',';
378        $b['postopts'] .= 'statusnet';
379     }
380 }
381
382 if (! function_exists( 'short_link' )) {
383 function short_link($url) {
384     require_once('library/slinky.php');
385     $slinky = new Slinky( $url );
386     $yourls_url = get_config('yourls','url1');
387     if ($yourls_url) {
388             $yourls_username = get_config('yourls','username1');
389             $yourls_password = get_config('yourls', 'password1');
390             $yourls_ssl = get_config('yourls', 'ssl1');
391             $yourls = new Slinky_YourLS();
392             $yourls->set( 'username', $yourls_username );
393             $yourls->set( 'password', $yourls_password );
394             $yourls->set( 'ssl', $yourls_ssl );
395             $yourls->set( 'yourls-url', $yourls_url );
396             $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
397     }
398     else {
399             // setup a cascade of shortening services
400             // try to get a short link from these services
401             // in the order ur1.ca, trim, id.gd, tinyurl
402             $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
403     }
404     return $slinky->short();
405 } };
406
407 function statusnet_post_hook(&$a,&$b) {
408
409         /**
410          * Post to statusnet
411          */
412
413         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
414                 return;
415
416         if(! strstr($b['postopts'],'statusnet'))
417                 return;
418
419         load_pconfig($b['uid'], 'statusnet');
420             
421         $api     = get_pconfig($b['uid'], 'statusnet', 'baseapi');
422         $ckey    = get_pconfig($b['uid'], 'statusnet', 'consumerkey'  );
423         $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret' );
424         $otoken  = get_pconfig($b['uid'], 'statusnet', 'oauthtoken'  );
425         $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret' );
426
427         if($ckey && $csecret && $otoken && $osecret) {
428
429                 require_once('include/bbcode.php');
430                 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
431                 $max_char = $dent->get_maxlength(); // max. length for a dent
432                 // we will only work with up to two times the length of the dent 
433                 // we can later send to StatusNet. This way we can "gain" some
434                 // information during shortening of potential links but do not
435                 // shorten all the links in a 200000 character long essay.
436                 if (! $b['title']=='') {
437                         $tmp = $b['title'].": \n".$b['body'];
438 //                    $tmp = substr($tmp, 0, 4*$max_char);
439                 } else {
440                     $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
441                 }
442                 // if [url=bla][img]blub.png[/img][/url] get blub.png
443                 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
444                 // preserve links to images, videos and audios
445                 $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
446                 $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
447                 $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
448                 $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
449                 $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
450                 $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
451                 $linksenabled = get_pconfig($b['uid'],'statusnet','post_taglinks');
452                 // if a #tag is linked, don't send the [url] over to SN
453                 // that is, don't send if the option is not set in the 
454                 // connector settings
455                 if ($linksenabled=='0') {
456                         // #-tags
457                         $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
458                         // @-mentions
459                         $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
460                         // recycle 1
461                         $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
462                         $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
463                         // recycle 2 (test)
464                         $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
465                         $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
466                 }
467                 // preserve links to webpages
468                 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
469                 $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
470                 // find all http or https links in the body of the entry and 
471                 // apply the shortener if the link is longer then 20 characters 
472                 if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
473                     preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls  );
474                     foreach ($allurls as $url) {
475                         foreach ($url as $u) {
476                             if (strlen($u)>20) {
477                                 $sl = short_link($u);
478                                 $tmp = str_replace( $u, $sl, $tmp );
479                             }
480                         }
481                     }
482                 }
483                 // ok, all the links we want to send out are save, now strip 
484                 // away the remaining bbcode
485                 //$msg = strip_tags(bbcode($tmp, false, false));
486                 $msg = bbcode($tmp, false, false);
487                 $msg = str_replace(array('<br>','<br />'),"\n",$msg);
488                 $msg = strip_tags($msg);
489
490                 // quotes not working - let's try this
491                 $msg = html_entity_decode($msg);
492
493                 if (( strlen($msg) > $max_char) && $max_char > 0) {
494                         $shortlink = short_link( $b['plink'] );
495                         // the new message will be shortened such that "... $shortlink"
496                         // will fit into the character limit
497                         $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
498                         $msg = str_replace(array('<br>','<br />'),' ',$msg);
499                         $e = explode(' ', $msg);
500                         //  remove the last word from the cut down message to 
501                         //  avoid sending cut words to the MicroBlog
502                         array_pop($e);
503                         $msg = implode(' ', $e);
504                         $msg .= '... ' . $shortlink;
505                 }
506
507                 $msg = trim($msg);
508
509                 // and now dent it :-)
510                 if(strlen($msg)) {
511                     $result = $dent->post('statuses/update', array('status' => $msg));
512                     logger('statusnet_post send, result: ' . print_r($result, true).
513                            "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b));
514                     if ($result->error) {
515                         logger('Send to StatusNet failed: "' . $result->error . '"');
516                     }
517                 }
518         }
519 }
520
521 function statusnet_plugin_admin_post(&$a){
522         
523         $sites = array();
524         
525         foreach($_POST['sitename'] as $id=>$sitename){
526                 $sitename=trim($sitename);
527                 $apiurl=trim($_POST['apiurl'][$id]);
528                 $secret=trim($_POST['secret'][$id]);
529                 $key=trim($_POST['key'][$id]);
530                 if ($sitename!="" &&
531                         $apiurl!="" &&
532                         $secret!="" &&
533                         $key!="" &&
534                         !x($_POST['delete'][$id])){
535                                 
536                                 $sites[] = Array(
537                                         'sitename' => $sitename,
538                                         'apiurl' => $apiurl,
539                                         'consumersecret' => $secret,
540                                         'consumerkey' => $key
541                                 );
542                 }
543         }
544         
545         $sites = set_config('statusnet','sites', $sites);
546         
547 }
548
549 function statusnet_plugin_admin(&$a, &$o){
550
551         $sites = get_config('statusnet','sites');
552         $sitesform=array();
553         if (is_array($sites)){
554                 foreach($sites as $id=>$s){
555                         $sitesform[] = Array(
556                                 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
557                                 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
558                                 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
559                                 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
560                                 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
561                         );
562                 }
563         }
564         /* empty form to add new site */
565         $id++;
566         $sitesform[] = Array(
567                 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
568                 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
569                 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
570                 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
571         );
572
573         
574         $t = file_get_contents( dirname(__file__). "/admin.tpl" );
575         $o = replace_macros($t, array(
576                 '$submit' => t('Submit'),
577                                                         
578                 '$sites' => $sitesform,
579                 
580         ));
581         
582         
583 }