]> git.mxchange.org Git - friendica-addons.git/blob - statusnet/statusnet.php
added hint to SN/T connector settings about colliding privacy settings
[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.3
6  * Author: Tobias Diekershoff <https://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         } else {
159             if (isset($_POST['statusnet-preconf-apiurl'])) {
160                 /***
161                  * If the user used one of the preconfigured StatusNet server credentials
162                  * use them. All the data are available in the global config.
163                  * Check the API Url never the less and blame the admin if it's not working ^^
164                  */
165                 $globalsn = get_config('statusnet', 'sites');
166                 foreach ( $globalsn as $asn) {
167                     if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
168                         $apibase = $asn['apiurl'];
169                         $c = fetch_url( $apibase . 'statusnet/version.xml' );
170                         if (strlen($c) > 0) {
171                             set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
172                             set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
173                             set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
174                         } else {
175                             notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
176                         }
177                     }
178                 }
179                 goaway($a->get_baseurl().'/settings/connectors');
180             } else {
181             if (isset($_POST['statusnet-consumersecret'])) {
182                 //  check if we can reach the API of the StatusNet server
183                 //  we'll check the API Version for that, if we don't get one we'll try to fix the path but will
184                 //  resign quickly after this one try to fix the path ;-)
185                 $apibase = $_POST['statusnet-baseapi'];
186                 $c = fetch_url( $apibase . 'statusnet/version.xml' );
187                 if (strlen($c) > 0) {
188                     //  ok the API path is correct, let's save the settings
189                     set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
190                     set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
191                     set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
192                 } else {
193                     //  the API path is not correct, maybe missing trailing / ?
194                     $apibase = $apibase . '/';
195                     $c = fetch_url( $apibase . 'statusnet/version.xml' );
196                     if (strlen($c) > 0) {
197                         //  ok the API path is now correct, let's save the settings
198                         set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
199                         set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
200                         set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
201                     } else {
202                         //  still not the correct API base, let's do noting
203                         notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
204                     }
205                 }
206                 goaway($a->get_baseurl().'/settings/connectors');
207             } else {
208                 if (isset($_POST['statusnet-pin'])) {
209                         //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
210                     $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
211                                         $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey'  );
212                                         $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
213                                         //  the token and secret for which the PIN was generated were hidden in the settings
214                                         //  form as token and token2, we need a new connection to Twitter using these token
215                                         //  and secret to request a Access Token with the PIN
216                                         $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
217                                         $token   = $connection->getAccessToken( $_POST['statusnet-pin'] );
218                                         //  ok, now that we have the Access Token, save them in the user config
219                                         set_pconfig(local_user(),'statusnet', 'oauthtoken',  $token['oauth_token']);
220                                         set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
221                     set_pconfig(local_user(),'statusnet', 'post', 1);
222                     //  reload the Addon Settings page, if we don't do it see Bug #42
223                     goaway($a->get_baseurl().'/settings/connectors');
224                                 } else {
225                                         //  if no PIN is supplied in the POST variables, the user has changed the setting
226                                         //  to post a tweet for every new __public__ posting to the wall
227                                         set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
228                                         set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
229                                         info( t('StatusNet settings updated.') . EOL);
230                 }}}}
231 }
232 function statusnet_settings(&$a,&$s) {
233         if(! local_user())
234                 return;
235         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
236         /***
237          * 1) Check that we have a base api url and a consumer key & secret
238          * 2) If no OAuthtoken & stuff is present, generate button to get some
239          *    allow the user to cancel the connection process at this step
240          * 3) Checkbox for "Send public notices (respect size limitation)
241          */
242         $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
243         $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
244         $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
245         $otoken  = get_pconfig(local_user(), 'statusnet', 'oauthtoken'  );
246         $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
247         $enabled = get_pconfig(local_user(), 'statusnet', 'post');
248         $checked = (($enabled) ? ' checked="checked" ' : '');
249         $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
250         $defchecked = (($defenabled) ? ' checked="checked" ' : '');
251         $s .= '<div class="settings-block">';
252         $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
253
254         if ( (!$ckey) && (!$csecret) ) {
255                 /***
256                  * no consumer keys
257                  */
258             $globalsn = get_config('statusnet', 'sites');
259             /***
260              * lets check if we have one or more globally configured StatusNet
261              * server OAuth credentials in the configuration. If so offer them
262              * with a little explanation to the user as choice - otherwise
263              * ignore this option entirely.
264              */
265             if (! $globalsn == null) {
266                 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
267                 $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>';
268                 $s .= '<div id="statusnet-preconf-wrapper">';
269                 foreach ($globalsn as $asn) {
270                     $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
271                 }
272                 $s .= '<p></p><div class="clear"></div></div>';
273                 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
274             }
275             $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
276             $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>';
277             $s .= '<div id="statusnet-consumer-wrapper">';
278             $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
279             $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
280             $s .= '<div class="clear"></div>';
281             $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
282             $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
283             $s .= '<div class="clear"></div>';
284             $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
285             $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
286             $s .= '<p></p><div class="clear"></div></div>';
287             $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
288         } else {
289                 /***
290                  * ok we have a consumer key pair now look into the OAuth stuff
291                  */
292                 if ( (!$otoken) && (!$osecret) ) {
293                         /***
294                          * the user has not yet connected the account to statusnet
295                          * get a temporary OAuth key/secret pair and display a button with
296                          * which the user can request a PIN to connect the account to a
297                          * account at statusnet
298                          */
299                         $connection = new StatusNetOAuth($api, $ckey, $csecret);
300                         $request_token = $connection->getRequestToken('oob');
301                         $token = $request_token['oauth_token'];
302                         /***
303                          *  make some nice form
304                          */
305                         $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>';
306                         $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
307                         $s .= '<div id="statusnet-pin-wrapper">';
308                         $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
309                         $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
310                         $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
311                         $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
312                         $s .= '</div><div class="clear"></div>';
313                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
314                         $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
315                         $s .= '<div id="statusnet-cancel-wrapper">';
316                         $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
317                         $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
318                         $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
319                         $s .= '</div><div class="clear"></div>';
320                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
321                 } else {
322                         /***
323                          *  we have an OAuth key / secret pair for the user
324                          *  so let's give a chance to disable the postings to statusnet
325                          */
326                         $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
327                         $details = $connection->get('account/verify_credentials');
328                         $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>';
329                         $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>';
330                         if ($a->user['hidewall']) {
331                             $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>';
332                         }
333                         $s .= '<div id="statusnet-enable-wrapper">';
334                         $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
335                         $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
336                         $s .= '<div class="clear"></div>';
337                         $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
338                         $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
339                         $s .= '</div><div class="clear"></div>';
340
341                         $s .= '<div id="statusnet-disconnect-wrapper">';
342                         $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
343                         $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
344                         $s .= '</div><div class="clear"></div>';
345                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
346                 }
347         }
348         $s .= '</div><div class="clear"></div></div>';
349 }
350
351
352 function statusnet_post_local(&$a,&$b) {
353         if($b['edit'])
354                 return;
355
356         if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
357
358                 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
359                 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
360
361                 // if API is used, default to the chosen settings
362                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
363                         $statusnet_enable = 1;
364
365        if(! $statusnet_enable)
366             return;
367
368        if(strlen($b['postopts']))
369            $b['postopts'] .= ',';
370        $b['postopts'] .= 'statusnet';
371     }
372 }
373
374 if (! function_exists( 'short_link' )) {
375 function short_link($url) {
376     require_once('library/slinky.php');
377     $slinky = new Slinky( $url );
378     $yourls_url = get_config('yourls','url1');
379     if ($yourls_url) {
380             $yourls_username = get_config('yourls','username1');
381             $yourls_password = get_config('yourls', 'password1');
382             $yourls_ssl = get_config('yourls', 'ssl1');
383             $yourls = new Slinky_YourLS();
384             $yourls->set( 'username', $yourls_username );
385             $yourls->set( 'password', $yourls_password );
386             $yourls->set( 'ssl', $yourls_ssl );
387             $yourls->set( 'yourls-url', $yourls_url );
388             $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
389     }
390     else {
391             // setup a cascade of shortening services
392             // try to get a short link from these services
393             // in the order ur1.ca, trim, id.gd, tinyurl
394             $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
395     }
396     return $slinky->short();
397 } };
398
399 function statusnet_post_hook(&$a,&$b) {
400
401         /**
402          * Post to statusnet
403          */
404
405         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
406                 return;
407
408         if(! strstr($b['postopts'],'statusnet'))
409                 return;
410
411         load_pconfig($b['uid'], 'statusnet');
412             
413         $api     = get_pconfig($b['uid'], 'statusnet', 'baseapi');
414         $ckey    = get_pconfig($b['uid'], 'statusnet', 'consumerkey'  );
415         $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret' );
416         $otoken  = get_pconfig($b['uid'], 'statusnet', 'oauthtoken'  );
417         $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret' );
418
419         if($ckey && $csecret && $otoken && $osecret) {
420
421                 require_once('include/bbcode.php');     
422                 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
423                 $max_char = $dent->get_maxlength(); // max. length for a dent
424                 // we will only work with up to two times the length of the dent 
425                 // we can later send to StatusNet. This way we can "gain" some 
426                 // information during shortening of potential links but do not 
427                 // shorten all the links in a 200000 character long essay.
428                 $tmp = substr($b['body'], 0, 2*$max_char);
429                 // if [url=bla][img]blub.png[/img][/url] get blub.png
430                 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
431                 // preserve links to images, videos and audios
432                 $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
433                 $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
434                 $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
435                 $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
436                 $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
437                 $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
438                 // if a #tag is linked, don't send the [url] over to SN
439                 //   this is commented out by default as it means backlinks
440                 //   to friendica, if you don't like this feel free to
441                 //   uncomment the following line
442 //                $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
443                 // preserve links to webpages
444                 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
445                 $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
446                 // find all http or https links in the body of the entry and 
447                 // apply the shortener if the link is longer then 20 characters 
448                 if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
449                     preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls  );
450                     foreach ($allurls as $url) {
451                         foreach ($url as $u) {
452                             if (strlen($u)>20) {
453                                 $sl = short_link($u);
454                                 $tmp = str_replace( $u, $sl, $tmp );
455                             }
456                         }
457                     }
458                 }
459                 // ok, all the links we want to send out are save, now strip 
460                 // away the remaining bbcode
461                 $msg = strip_tags(bbcode($tmp));
462                 // quotes not working - let's try this
463                 $msg = html_entity_decode($msg);
464                 if (( strlen($msg) > $max_char) && $max_char > 0) {
465                         $shortlink = short_link( $b['plink'] );
466                         // the new message will be shortened such that "... $shortlink"
467                         // will fit into the character limit
468                         $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
469                         $msg .= '... ' . $shortlink;
470                 }
471                 // and now tweet it :-)
472                 if(strlen($msg))
473                         $dent->post('statuses/update', array('status' => $msg));
474         }
475 }
476
477 function statusnet_plugin_admin_post(&$a){
478         
479         $sites = array();
480         
481         foreach($_POST['sitename'] as $id=>$sitename){
482                 $sitename=trim($sitename);
483                 $apiurl=trim($_POST['apiurl'][$id]);
484                 $secret=trim($_POST['secret'][$id]);
485                 $key=trim($_POST['key'][$id]);
486                 if ($sitename!="" &&
487                         $apiurl!="" &&
488                         $secret!="" &&
489                         $key!="" &&
490                         !x($_POST['delete'][$id])){
491                                 
492                                 $sites[] = Array(
493                                         'sitename' => $sitename,
494                                         'apiurl' => $apiurl,
495                                         'consumersecret' => $secret,
496                                         'consumerkey' => $key
497                                 );
498                 }
499         }
500         
501         $sites = set_config('statusnet','sites', $sites);
502         
503 }
504
505 function statusnet_plugin_admin(&$a, &$o){
506
507         $sites = get_config('statusnet','sites');
508         $sitesform=array();
509         if (is_array($sites)){
510                 foreach($sites as $id=>$s){
511                         $sitesform[] = Array(
512                                 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
513                                 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
514                                 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
515                                 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
516                                 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
517                         );
518                 }
519         }
520         /* empty form to add new site */
521         $id++;
522         $sitesform[] = Array(
523                 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
524                 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
525                 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
526                 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
527         );
528
529         
530         $t = file_get_contents( dirname(__file__). "/admin.tpl" );
531         $o = replace_macros($t, array(
532                 '$submit' => t('Submit'),
533                                                         
534                 '$sites' => $sitesform,
535                 
536         ));
537         
538         
539 }