3 * Name: StatusNet Connector
4 * Description: Relay public postings to a connected StatusNet account
6 * Author: Tobias Diekershoff <http://diekershoff.homeunix.net/friendika/profile/tobias>
9 /* StatusNet Plugin for Friendica
11 * Author: Tobias Diekershoff
12 * tobias.diekershoff@gmx.net
14 * License:3-clause BSD license
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".
21 * Requirements: PHP5, curl [Slinky library]
23 * Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/StatusNet_Plugin
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.
30 * Thank you guys for the Twitter compatible API!
33 require_once('library/twitteroauth.php');
35 class StatusNetOAuth extends TwitterOAuth {
36 function get_maxlength() {
37 $config = $this->get($this->host . 'statusnet/config.json');
38 return $config->site->textlimit;
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;
49 * Make an HTTP request
53 * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
55 function http($url, $method, $postfields = NULL) {
56 $this->http_info = array();
59 $prx = get_config('system','proxy');
61 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
62 curl_setopt($ci, CURLOPT_PROXY, $prx);
63 $prxusr = get_config('system','proxyuser');
65 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
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);
78 curl_setopt($ci, CURLOPT_POST, TRUE);
79 if (!empty($postfields)) {
80 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
84 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
85 if (!empty($postfields)) {
86 $url = "{$url}?{$postfields}";
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));
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");
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');
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');
125 function statusnet_jot_nets(&$a,&$b) {
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>';
141 function statusnet_settings_post ($a,$post) {
144 // don't check statusnet settings if statusnet submit button is not clicked
145 if (!x($_POST,'statusnet-submit')) return;
147 if (isset($_POST['statusnet-disconnect'])) {
149 * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
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');
160 if (isset($_POST['statusnet-preconf-apiurl'])) {
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 ^^
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'] );
176 notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
180 goaway($a->get_baseurl().'/settings/connectors');
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 );
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 );
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 );
207 goaway($a->get_baseurl().'/settings/connectors');
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');
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);
235 function statusnet_settings(&$a,&$s) {
238 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
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)
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>';
259 if ( (!$ckey) && (!$csecret) ) {
263 $globalsn = get_config('statusnet', 'sites');
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.
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 />';
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>';
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>';
295 * ok we have a consumer key pair now look into the OAuth stuff
297 if ( (!$otoken) && (!$osecret) ) {
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
304 $connection = new StatusNetOAuth($api, $ckey, $csecret);
305 $request_token = $connection->getRequestToken('oob');
306 $token = $request_token['oauth_token'];
308 * make some nice form
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>';
328 * we have an OAuth key / secret pair for the user
329 * so let's give a chance to disable the postings to statusnet
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>';
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>';
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>';
356 $s .= '</div><div class="clear"></div></div>';
360 function statusnet_post_local(&$a,&$b) {
364 if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
366 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
367 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
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;
373 if(! $statusnet_enable)
376 if(strlen($b['postopts']))
377 $b['postopts'] .= ',';
378 $b['postopts'] .= 'statusnet';
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');
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() ) );
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() ) );
404 return $slinky->short();
407 function statusnet_shortenmsg($b, $max_char) {
408 require_once("include/bbcode.php");
409 require_once("include/html2plain.php");
411 // Looking for the first image
413 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
414 $image = $matches[3];
417 if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
418 $image = $matches[1];
420 $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
422 // When saved into the database the content is sent through htmlspecialchars
423 // That means that we have to decode all image-urls
424 $image = htmlspecialchars_decode($image);
427 if ($b["title"] != "")
428 $body = $b["title"]."\n\n".$body;
430 // remove the recycle signs and the names since they aren't helpful on twitter
432 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
433 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
435 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
436 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
438 // At first convert the text to html
439 $html = bbcode($body, false, false);
441 // Then convert it to plain text
442 //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
443 $msg = trim(html2plain($html, 0, true));
444 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
446 // Removing multiple newlines
447 while (strpos($msg, "\n\n\n") !== false)
448 $msg = str_replace("\n\n\n", "\n\n", $msg);
450 // Removing multiple spaces
451 while (strpos($msg, " ") !== false)
452 $msg = str_replace(" ", " ", $msg);
455 $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
460 // look for bookmark-bbcode and handle it with priority
461 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
464 $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
466 // If there is no bookmark element then take the first link
468 $links = collecturls($html);
469 if (sizeof($links) > 0) {
471 $link = current($links);
473 $multiplelinks = (sizeof($links) > 1);
478 $msglink = $b["plink"];
479 else if ($link != "")
481 else if ($multipleimages)
482 $msglink = $b["plink"];
483 else if ($image != "")
486 if (($msglink == "") and strlen($msg) > $max_char)
487 $msglink = $b["plink"];
489 if (strlen($msglink) > 20)
490 $msglink = short_link($msglink);
492 if (strlen(trim($msg." ".$msglink)) > $max_char) {
493 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
494 $lastchar = substr($msg, -1);
495 $msg = substr($msg, 0, -1);
496 $pos = strrpos($msg, "\n");
498 $msg = substr($msg, 0, $pos-1);
499 else if ($lastchar != "\n")
500 $msg = substr($msg, 0, -3)."...";
502 $msg = str_replace("\n", " ", $msg);
504 // Removing multiple spaces - again
505 while (strpos($msg, " ") !== false)
506 $msg = str_replace(" ", " ", $msg);
508 return(trim($msg." ".$msglink));
511 function statusnet_post_hook(&$a,&$b) {
517 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
520 if(! strstr($b['postopts'],'statusnet'))
523 load_pconfig($b['uid'], 'statusnet');
525 $api = get_pconfig($b['uid'], 'statusnet', 'baseapi');
526 $ckey = get_pconfig($b['uid'], 'statusnet', 'consumerkey' );
527 $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret' );
528 $otoken = get_pconfig($b['uid'], 'statusnet', 'oauthtoken' );
529 $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret' );
531 if($ckey && $csecret && $otoken && $osecret) {
533 require_once('include/bbcode.php');
534 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
535 $max_char = $dent->get_maxlength(); // max. length for a dent
536 // we will only work with up to two times the length of the dent
537 // we can later send to StatusNet. This way we can "gain" some
538 // information during shortening of potential links but do not
539 // shorten all the links in a 200000 character long essay.
541 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
542 if (!$intelligent_shortening) {
543 if (! $b['title']=='') {
544 $tmp = $b['title'].": \n".$b['body'];
545 // $tmp = substr($tmp, 0, 4*$max_char);
547 $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
549 // if [url=bla][img]blub.png[/img][/url] get blub.png
550 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
551 // preserve links to images, videos and audios
552 $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
553 $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
554 $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
555 $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
556 $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
557 $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
558 $linksenabled = get_pconfig($b['uid'],'statusnet','post_taglinks');
559 // if a #tag is linked, don't send the [url] over to SN
560 // that is, don't send if the option is not set in the
561 // connector settings
562 if ($linksenabled=='0') {
564 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
566 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
568 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
569 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
571 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
572 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
574 // preserve links to webpages
575 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
576 $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
577 // find all http or https links in the body of the entry and
578 // apply the shortener if the link is longer then 20 characters
579 if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
580 preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls );
581 foreach ($allurls as $url) {
582 foreach ($url as $u) {
584 $sl = short_link($u);
585 $tmp = str_replace( $u, $sl, $tmp );
590 // ok, all the links we want to send out are save, now strip
591 // away the remaining bbcode
592 //$msg = strip_tags(bbcode($tmp, false, false));
593 $msg = bbcode($tmp, false, false);
594 $msg = str_replace(array('<br>','<br />'),"\n",$msg);
595 $msg = strip_tags($msg);
597 // quotes not working - let's try this
598 $msg = html_entity_decode($msg);
600 if (( strlen($msg) > $max_char) && $max_char > 0) {
601 $shortlink = short_link( $b['plink'] );
602 // the new message will be shortened such that "... $shortlink"
603 // will fit into the character limit
604 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
605 $msg = str_replace(array('<br>','<br />'),' ',$msg);
606 $e = explode(' ', $msg);
607 // remove the last word from the cut down message to
608 // avoid sending cut words to the MicroBlog
610 $msg = implode(' ', $e);
611 $msg .= '... ' . $shortlink;
616 $msg = statusnet_shortenmsg($b, $max_char);
618 // and now dent it :-)
620 $result = $dent->post('statuses/update', array('status' => $msg));
621 logger('statusnet_post send, result: ' . print_r($result, true).
622 "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b));
623 if ($result->error) {
624 logger('Send to StatusNet failed: "' . $result->error . '"');
630 function statusnet_plugin_admin_post(&$a){
634 foreach($_POST['sitename'] as $id=>$sitename){
635 $sitename=trim($sitename);
636 $apiurl=trim($_POST['apiurl'][$id]);
637 $secret=trim($_POST['secret'][$id]);
638 $key=trim($_POST['key'][$id]);
643 !x($_POST['delete'][$id])){
646 'sitename' => $sitename,
648 'consumersecret' => $secret,
649 'consumerkey' => $key
654 $sites = set_config('statusnet','sites', $sites);
658 function statusnet_plugin_admin(&$a, &$o){
660 $sites = get_config('statusnet','sites');
662 if (is_array($sites)){
663 foreach($sites as $id=>$s){
664 $sitesform[] = Array(
665 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
666 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
667 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
668 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
669 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
673 /* empty form to add new site */
675 $sitesform[] = Array(
676 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
677 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
678 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
679 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
683 $t = file_get_contents( dirname(__file__). "/admin.tpl" );
684 $o = replace_macros($t, array(
685 '$submit' => t('Submit'),
687 '$sites' => $sitesform,