]> git.mxchange.org Git - friendica-addons.git/blob - statusnet/statusnet.php
SN addon: added handling for [bookmark] tag
[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                         $s .= '<div id="statusnet-enable-wrapper">';
331                         $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
332                         $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
333                         $s .= '<div class="clear"></div>';
334                         $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
335                         $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
336                         $s .= '</div><div class="clear"></div>';
337
338                         $s .= '<div id="statusnet-disconnect-wrapper">';
339                         $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
340                         $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
341                         $s .= '</div><div class="clear"></div>';
342                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
343                 }
344         }
345         $s .= '</div><div class="clear"></div></div>';
346 }
347
348
349 function statusnet_post_local(&$a,&$b) {
350         if($b['edit'])
351                 return;
352
353         if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
354
355                 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
356                 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
357
358                 // if API is used, default to the chosen settings
359                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
360                         $statusnet_enable = 1;
361
362        if(! $statusnet_enable)
363             return;
364
365        if(strlen($b['postopts']))
366            $b['postopts'] .= ',';
367        $b['postopts'] .= 'statusnet';
368     }
369 }
370
371 function statusnet_post_hook(&$a,&$b) {
372
373         /**
374          * Post to statusnet
375          */
376
377         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
378                 return;
379
380         if(! strstr($b['postopts'],'statusnet'))
381                 return;
382
383         load_pconfig($b['uid'], 'statusnet');
384             
385         $api     = get_pconfig($b['uid'], 'statusnet', 'baseapi');
386         $ckey    = get_pconfig($b['uid'], 'statusnet', 'consumerkey'  );
387         $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret' );
388         $otoken  = get_pconfig($b['uid'], 'statusnet', 'oauthtoken'  );
389         $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret' );
390
391         if($ckey && $csecret && $otoken && $osecret) {
392
393                 require_once('include/bbcode.php');     
394                 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
395                 $max_char = $dent->get_maxlength(); // max. length for a dent
396                 $tmp = $b['body'];
397                 // if [url=bla][img]blub.png[/img][/url] get blub.png
398                 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
399                 logger($tmp);
400 //                $tmp = preg_replace( '/\[url\=(\w+.*?)\]\[img\](\w+.*?)\[\/img\]\[\/url\]/i', '$2', $tmp);
401                 // preserve links to images, videos and audios
402                 $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
403                 $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
404                 $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
405                 $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
406                 $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
407                 $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
408                 // if a #tag is linked, don't send the [url] over to SN
409                 //   this is commented out by default as it means backlinks
410                 //   to friendica, if you don't like this feel free to
411                 //   uncomment the following line
412 //                $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
413                 // preserve links to webpages
414                 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
415                 $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
416                 // TODO apply the shortener to the URLs in the releyed dent
417                 $msg = strip_tags(bbcode($tmp));
418                 // quotes not working - let's try this
419                 $msg = html_entity_decode($msg);
420                 if (( strlen($msg) > $max_char) && $max_char > 0) {
421                         $shortlink = "";
422                         require_once('library/slinky.php');
423                         $slinky = new Slinky( $b['plink'] );
424                         $yourls_url = get_config('yourls','url1');
425                         if ($yourls_url) {
426                                 $yourls_username = get_config('yourls','username1');
427                                 $yourls_password = get_config('yourls', 'password1');
428                                 $yourls_ssl = get_config('yourls', 'ssl1');
429                                 $yourls = new Slinky_YourLS();
430                                 $yourls->set( 'username', $yourls_username );
431                                 $yourls->set( 'password', $yourls_password );
432                                 $yourls->set( 'ssl', $yourls_ssl );
433                                 $yourls->set( 'yourls-url', $yourls_url );
434                                 $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
435                         }
436                         else {
437                                 // setup a cascade of shortening services
438                                 // try to get a short link from these services
439                                 // in the order ur1.ca, trim, id.gd, tinyurl
440                                 $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
441                         }
442                         $shortlink = $slinky->short();
443                         // the new message will be shortened such that "... $shortlink"
444                         // will fit into the character limit
445                         $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
446                         $msg .= '... ' . $shortlink;
447                 }
448                 // and now tweet it :-)
449                 if(strlen($msg))
450                         $dent->post('statuses/update', array('status' => $msg));
451         }
452 }
453
454 function statusnet_plugin_admin_post(&$a){
455         
456         $sites = array();
457         
458         foreach($_POST['sitename'] as $id=>$sitename){
459                 $sitename=trim($sitename);
460                 $apiurl=trim($_POST['apiurl'][$id]);
461                 $secret=trim($_POST['secret'][$id]);
462                 $key=trim($_POST['key'][$id]);
463                 if ($sitename!="" &&
464                         $apiurl!="" &&
465                         $secret!="" &&
466                         $key!="" &&
467                         !x($_POST['delete'][$id])){
468                                 
469                                 $sites[] = Array(
470                                         'sitename' => $sitename,
471                                         'apiurl' => $apiurl,
472                                         'consumersecret' => $secret,
473                                         'consumerkey' => $key
474                                 );
475                 }
476         }
477         
478         $sites = set_config('statusnet','sites', $sites);
479         
480 }
481
482 function statusnet_plugin_admin(&$a, &$o){
483
484         $sites = get_config('statusnet','sites');
485         $sitesform=array();
486         if (is_array($sites)){
487                 foreach($sites as $id=>$s){
488                         $sitesform[] = Array(
489                                 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
490                                 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
491                                 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
492                                 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
493                                 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
494                         );
495                 }
496         }
497         /* empty form to add new site */
498         $id++;
499         $sitesform[] = Array(
500                 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
501                 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
502                 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
503                 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
504         );
505
506         
507         $t = file_get_contents( dirname(__file__). "/admin.tpl" );
508         $o = replace_macros($t, array(
509                 '$submit' => t('Submit'),
510                                                         
511                 '$sites' => $sitesform,
512                 
513         ));
514         
515         
516 }