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 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
35 require_once('library/twitteroauth.php');
37 class StatusNetOAuth extends TwitterOAuth {
38 function get_maxlength() {
39 $config = $this->get($this->host . 'statusnet/config.json');
40 return $config->site->textlimit;
42 function accessTokenURL() { return $this->host.'oauth/access_token'; }
43 function authenticateURL() { return $this->host.'oauth/authenticate'; }
44 function authorizeURL() { return $this->host.'oauth/authorize'; }
45 function requestTokenURL() { return $this->host.'oauth/request_token'; }
46 function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
47 parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
48 $this->host = $apipath;
51 * Make an HTTP request
55 * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
57 function http($url, $method, $postfields = NULL) {
58 $this->http_info = array();
61 $prx = get_config('system','proxy');
63 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
64 curl_setopt($ci, CURLOPT_PROXY, $prx);
65 $prxusr = get_config('system','proxyuser');
67 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
69 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
70 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
71 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
72 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
73 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
74 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
75 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
76 curl_setopt($ci, CURLOPT_HEADER, FALSE);
80 curl_setopt($ci, CURLOPT_POST, TRUE);
81 if (!empty($postfields)) {
82 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
86 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
87 if (!empty($postfields)) {
88 $url = "{$url}?{$postfields}";
92 curl_setopt($ci, CURLOPT_URL, $url);
93 $response = curl_exec($ci);
94 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
95 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
102 function statusnet_install() {
103 // we need some hooks, for the configuration and for sending tweets
104 register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
105 register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
106 register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
107 register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
108 register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
109 register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
110 logger("installed statusnet");
114 function statusnet_uninstall() {
115 unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
116 unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
117 unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
118 unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
119 unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
120 unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
122 // old setting - remove only
123 unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
124 unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
125 unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
129 function statusnet_jot_nets(&$a,&$b) {
133 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
134 if(intval($statusnet_post) == 1) {
135 $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default');
136 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
137 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
138 . t('Post to StatusNet') . '</div>';
142 function statusnet_settings_post ($a,$post) {
145 // don't check statusnet settings if statusnet submit button is not clicked
146 if (!x($_POST,'statusnet-submit')) return;
148 if (isset($_POST['statusnet-disconnect'])) {
150 * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
152 del_pconfig(local_user(), 'statusnet', 'consumerkey');
153 del_pconfig(local_user(), 'statusnet', 'consumersecret');
154 del_pconfig(local_user(), 'statusnet', 'post');
155 del_pconfig(local_user(), 'statusnet', 'post_by_default');
156 del_pconfig(local_user(), 'statusnet', 'oauthtoken');
157 del_pconfig(local_user(), 'statusnet', 'oauthsecret');
158 del_pconfig(local_user(), 'statusnet', 'baseapi');
159 del_pconfig(local_user(), 'statusnet', 'post_taglinks');
160 del_pconfig(local_user(), 'statusnet', 'lastid');
161 del_pconfig(local_user(), 'statusnet', 'mirror_posts');
162 del_pconfig(local_user(), 'statusnet', 'intelligent_shortening');
164 if (isset($_POST['statusnet-preconf-apiurl'])) {
166 * If the user used one of the preconfigured StatusNet server credentials
167 * use them. All the data are available in the global config.
168 * Check the API Url never the less and blame the admin if it's not working ^^
170 $globalsn = get_config('statusnet', 'sites');
171 foreach ( $globalsn as $asn) {
172 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
173 $apibase = $asn['apiurl'];
174 $c = fetch_url( $apibase . 'statusnet/version.xml' );
175 if (strlen($c) > 0) {
176 set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
177 set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
178 set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
180 notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
184 goaway($a->get_baseurl().'/settings/connectors');
186 if (isset($_POST['statusnet-consumersecret'])) {
187 // check if we can reach the API of the StatusNet server
188 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
189 // resign quickly after this one try to fix the path ;-)
190 $apibase = $_POST['statusnet-baseapi'];
191 $c = fetch_url( $apibase . 'statusnet/version.xml' );
192 if (strlen($c) > 0) {
193 // ok the API path is correct, let's save the settings
194 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
195 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
196 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
198 // the API path is not correct, maybe missing trailing / ?
199 $apibase = $apibase . '/';
200 $c = fetch_url( $apibase . 'statusnet/version.xml' );
201 if (strlen($c) > 0) {
202 // ok the API path is now correct, let's save the settings
203 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
204 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
205 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
207 // still not the correct API base, let's do noting
208 notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
211 goaway($a->get_baseurl().'/settings/connectors');
213 if (isset($_POST['statusnet-pin'])) {
214 // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
215 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
216 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
217 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
218 // the token and secret for which the PIN was generated were hidden in the settings
219 // form as token and token2, we need a new connection to Twitter using these token
220 // and secret to request a Access Token with the PIN
221 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
222 $token = $connection->getAccessToken( $_POST['statusnet-pin'] );
223 // ok, now that we have the Access Token, save them in the user config
224 set_pconfig(local_user(),'statusnet', 'oauthtoken', $token['oauth_token']);
225 set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
226 set_pconfig(local_user(),'statusnet', 'post', 1);
227 set_pconfig(local_user(),'statusnet', 'post_taglinks', 1);
228 // reload the Addon Settings page, if we don't do it see Bug #42
229 goaway($a->get_baseurl().'/settings/connectors');
231 // if no PIN is supplied in the POST variables, the user has changed the setting
232 // to post a dent for every new __public__ posting to the wall
233 set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
234 set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
235 set_pconfig(local_user(),'statusnet','post_taglinks',intval($_POST['statusnet-sendtaglinks']));
236 set_pconfig(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
237 set_pconfig(local_user(), 'statusnet', 'intelligent_shortening', intval($_POST['statusnet-shortening']));
238 info( t('StatusNet settings updated.') . EOL);
241 function statusnet_settings(&$a,&$s) {
244 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
246 * 1) Check that we have a base api url and a consumer key & secret
247 * 2) If no OAuthtoken & stuff is present, generate button to get some
248 * allow the user to cancel the connection process at this step
249 * 3) Checkbox for "Send public notices (respect size limitation)
251 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
252 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
253 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
254 $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken' );
255 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
256 $enabled = get_pconfig(local_user(), 'statusnet', 'post');
257 $checked = (($enabled) ? ' checked="checked" ' : '');
258 $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
259 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
260 $linksenabled = get_pconfig(local_user(),'statusnet','post_taglinks');
261 $linkschecked = (($linksenabled) ? ' checked="checked" ' : '');
263 $mirrorenabled = get_pconfig(local_user(),'statusnet','mirror_posts');
264 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
265 $shorteningenabled = get_pconfig(local_user(),'statusnet','intelligent_shortening');
266 $shorteningchecked = (($shorteningenabled) ? ' checked="checked" ' : '');
268 $s .= '<div class="settings-block">';
269 $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
271 if ( (!$ckey) && (!$csecret) ) {
275 $globalsn = get_config('statusnet', 'sites');
277 * lets check if we have one or more globally configured StatusNet
278 * server OAuth credentials in the configuration. If so offer them
279 * with a little explanation to the user as choice - otherwise
280 * ignore this option entirely.
282 if (! $globalsn == null) {
283 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
284 $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>';
285 $s .= '<div id="statusnet-preconf-wrapper">';
286 foreach ($globalsn as $asn) {
287 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
289 $s .= '<p></p><div class="clear"></div></div>';
290 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
292 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
293 $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>';
294 $s .= '<div id="statusnet-consumer-wrapper">';
295 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
296 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
297 $s .= '<div class="clear"></div>';
298 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
299 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
300 $s .= '<div class="clear"></div>';
301 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
302 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
303 $s .= '<p></p><div class="clear"></div></div>';
304 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
307 * ok we have a consumer key pair now look into the OAuth stuff
309 if ( (!$otoken) && (!$osecret) ) {
311 * the user has not yet connected the account to statusnet
312 * get a temporary OAuth key/secret pair and display a button with
313 * which the user can request a PIN to connect the account to a
314 * account at statusnet
316 $connection = new StatusNetOAuth($api, $ckey, $csecret);
317 $request_token = $connection->getRequestToken('oob');
318 $token = $request_token['oauth_token'];
320 * make some nice form
322 $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>';
323 $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
324 $s .= '<div id="statusnet-pin-wrapper">';
325 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
326 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
327 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
328 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
329 $s .= '</div><div class="clear"></div>';
330 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
331 $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
332 $s .= '<div id="statusnet-cancel-wrapper">';
333 $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
334 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
335 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
336 $s .= '</div><div class="clear"></div>';
337 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
340 * we have an OAuth key / secret pair for the user
341 * so let's give a chance to disable the postings to statusnet
343 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
344 $details = $connection->get('account/verify_credentials');
345 $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>';
346 $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>';
347 if ($a->user['hidewall']) {
348 $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>';
350 $s .= '<div id="statusnet-enable-wrapper">';
351 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
352 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
353 $s .= '<div class="clear"></div>';
354 $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
355 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
356 $s .= '<div class="clear"></div>';
358 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from statusnet that are no replies or repeated messages').'</label>';
359 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
360 $s .= '<div class="clear"></div>';
362 $s .= '<label id="statusnet-shortening-label" for="statusnet-shortening">'.t('Shortening method that optimizes the post').'</label>';
363 $s .= '<input id="statusnet-shortening" type="checkbox" name="statusnet-shortening" value="1" '. $shorteningchecked . '/>';
364 $s .= '<div class="clear"></div>';
366 $s .= '<label id="statusnet-sendtaglinks-label" for="statusnet-sendtaglinks">'.t('Send linked #-tags and @-names to StatusNet').'</label>';
367 $s .= '<input id="statusnet-sendtaglinks" type="checkbox" name="statusnet-sendtaglinks" value="1" '. $linkschecked . '/>';
368 $s .= '</div><div class="clear"></div>';
370 $s .= '<div id="statusnet-disconnect-wrapper">';
371 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
372 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
373 $s .= '</div><div class="clear"></div>';
374 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
377 $s .= '</div><div class="clear"></div></div>';
381 function statusnet_post_local(&$a,&$b) {
385 if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
387 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
388 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
390 // if API is used, default to the chosen settings
391 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
392 $statusnet_enable = 1;
394 if(! $statusnet_enable)
397 if(strlen($b['postopts']))
398 $b['postopts'] .= ',';
399 $b['postopts'] .= 'statusnet';
403 if (! function_exists( 'short_link' )) {
404 function short_link($url) {
405 require_once('library/slinky.php');
406 $slinky = new Slinky( $url );
407 $yourls_url = get_config('yourls','url1');
409 $yourls_username = get_config('yourls','username1');
410 $yourls_password = get_config('yourls', 'password1');
411 $yourls_ssl = get_config('yourls', 'ssl1');
412 $yourls = new Slinky_YourLS();
413 $yourls->set( 'username', $yourls_username );
414 $yourls->set( 'password', $yourls_password );
415 $yourls->set( 'ssl', $yourls_ssl );
416 $yourls->set( 'yourls-url', $yourls_url );
417 $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
420 // setup a cascade of shortening services
421 // try to get a short link from these services
422 // in the order ur1.ca, trim, id.gd, tinyurl
423 $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
425 return $slinky->short();
428 function statusnet_shortenmsg($b, $max_char) {
429 require_once("include/bbcode.php");
430 require_once("include/html2plain.php");
432 // Looking for the first image
434 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
435 $image = $matches[3];
438 if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
439 $image = $matches[1];
441 $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
443 // When saved into the database the content is sent through htmlspecialchars
444 // That means that we have to decode all image-urls
445 $image = htmlspecialchars_decode($image);
448 if ($b["title"] != "")
449 $body = $b["title"]."\n\n".$body;
451 if (strpos($body, "[bookmark") !== false) {
452 // splitting the text in two parts:
453 // before and after the bookmark
454 $pos = strpos($body, "[bookmark");
455 $body1 = substr($body, 0, $pos);
456 $body2 = substr($body, $pos);
458 // Removing all quotes after the bookmark
459 // they are mostly only the content after the bookmark.
460 $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
461 $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
462 $body = $body1.$body2;
465 // Add some newlines so that the message could be cut better
466 $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
467 array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
469 // remove the recycle signs and the names since they aren't helpful on twitter
471 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
472 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
474 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
475 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
477 // remove the share element
478 $body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
480 // At first convert the text to html
481 $html = bbcode($body, false, false);
483 // Then convert it to plain text
484 //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
485 $msg = trim(html2plain($html, 0, true));
486 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
488 // Removing multiple newlines
489 while (strpos($msg, "\n\n\n") !== false)
490 $msg = str_replace("\n\n\n", "\n\n", $msg);
492 // Removing multiple spaces
493 while (strpos($msg, " ") !== false)
494 $msg = str_replace(" ", " ", $msg);
497 $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
502 // look for bookmark-bbcode and handle it with priority
503 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
506 $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
508 // If there is no bookmark element then take the first link
510 $links = collecturls($html);
511 if (sizeof($links) > 0) {
513 $link = current($links);
515 $multiplelinks = (sizeof($links) > 1);
520 $msglink = $b["plink"];
521 else if ($link != "")
523 else if ($multipleimages)
524 $msglink = $b["plink"];
525 else if ($image != "")
528 if (($msglink == "") and strlen($msg) > $max_char)
529 $msglink = $b["plink"];
531 if (strlen($msglink) > 20)
532 $msglink = short_link($msglink);
534 if (strlen(trim($msg." ".$msglink)) > $max_char) {
535 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
536 $lastchar = substr($msg, -1);
537 $msg = substr($msg, 0, -1);
538 $pos = strrpos($msg, "\n");
540 $msg = substr($msg, 0, $pos);
541 else if ($lastchar != "\n")
542 $msg = substr($msg, 0, -3)."...";
544 $msg = str_replace("\n", " ", $msg);
546 // Removing multiple spaces - again
547 while (strpos($msg, " ") !== false)
548 $msg = str_replace(" ", " ", $msg);
550 return(array("msg"=>trim($msg." ".$msglink), "image"=>$image));
553 function statusnet_post_hook(&$a,&$b) {
559 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
562 if(! strstr($b['postopts'],'statusnet'))
565 // if posts comes from statusnet don't send it back
566 if($b['app'] == "StatusNet")
569 logger('statusnet post invoked');
571 load_pconfig($b['uid'], 'statusnet');
573 $api = get_pconfig($b['uid'], 'statusnet', 'baseapi');
574 $ckey = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
575 $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
576 $otoken = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
577 $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
578 $intelligent_shortening = get_pconfig($b['uid'], 'statusnet', 'intelligent_shortening');
580 // Global setting overrides this
581 if (get_config('statusnet','intelligent_shortening'))
582 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
584 if($ckey && $csecret && $otoken && $osecret) {
586 require_once('include/bbcode.php');
587 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
588 $max_char = $dent->get_maxlength(); // max. length for a dent
589 // we will only work with up to two times the length of the dent
590 // we can later send to StatusNet. This way we can "gain" some
591 // information during shortening of potential links but do not
592 // shorten all the links in a 200000 character long essay.
595 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
596 if (!$intelligent_shortening) {
597 if (! $b['title']=='') {
598 $tmp = $b['title'].": \n".$b['body'];
599 // $tmp = substr($tmp, 0, 4*$max_char);
601 $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
603 // if [url=bla][img]blub.png[/img][/url] get blub.png
604 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
605 // preserve links to images, videos and audios
606 $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
607 $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
608 $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
609 $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
610 $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
611 $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
612 $linksenabled = get_pconfig($b['uid'],'statusnet','post_taglinks');
613 // if a #tag is linked, don't send the [url] over to SN
614 // that is, don't send if the option is not set in the
615 // connector settings
616 if ($linksenabled=='0') {
618 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
620 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
622 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
623 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
625 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
626 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
628 // preserve links to webpages
629 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
630 $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
631 // find all http or https links in the body of the entry and
632 // apply the shortener if the link is longer then 20 characters
633 if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
634 preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls );
635 foreach ($allurls as $url) {
636 foreach ($url as $u) {
638 $sl = short_link($u);
639 $tmp = str_replace( $u, $sl, $tmp );
644 // ok, all the links we want to send out are save, now strip
645 // away the remaining bbcode
646 //$msg = strip_tags(bbcode($tmp, false, false));
647 $msg = bbcode($tmp, false, false);
648 $msg = str_replace(array('<br>','<br />'),"\n",$msg);
649 $msg = strip_tags($msg);
651 // quotes not working - let's try this
652 $msg = html_entity_decode($msg);
654 if (( strlen($msg) > $max_char) && $max_char > 0) {
655 $shortlink = short_link( $b['plink'] );
656 // the new message will be shortened such that "... $shortlink"
657 // will fit into the character limit
658 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
659 $msg = str_replace(array('<br>','<br />'),' ',$msg);
660 $e = explode(' ', $msg);
661 // remove the last word from the cut down message to
662 // avoid sending cut words to the MicroBlog
664 $msg = implode(' ', $e);
665 $msg .= '... ' . $shortlink;
669 $postdata = array('status' => $msg);
671 $msgarr = statusnet_shortenmsg($b, $max_char);
672 $msg = $msgarr["msg"];
673 $image = $msgarr["image"];
675 $imagedata = file_get_contents($image);
676 $tempfile = tempnam(get_config("system","temppath"), "upload");
677 file_put_contents($tempfile, $imagedata);
678 $postdata = array("status"=>$msg, "media"=>"@".$tempfile);
680 $postdata = array("status"=>$msg);
683 // and now dent it :-)
685 //$result = $dent->post('statuses/update', array('status' => $msg));
686 $result = $dent->post('statuses/update', $postdata);
687 logger('statusnet_post send, result: ' . print_r($result, true).
688 "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
689 if ($result->error) {
690 logger('Send to StatusNet failed: "' . $result->error . '"');
698 function statusnet_plugin_admin_post(&$a){
702 foreach($_POST['sitename'] as $id=>$sitename){
703 $sitename=trim($sitename);
704 $apiurl=trim($_POST['apiurl'][$id]);
705 $secret=trim($_POST['secret'][$id]);
706 $key=trim($_POST['key'][$id]);
711 !x($_POST['delete'][$id])){
714 'sitename' => $sitename,
716 'consumersecret' => $secret,
717 'consumerkey' => $key
722 $sites = set_config('statusnet','sites', $sites);
726 function statusnet_plugin_admin(&$a, &$o){
728 $sites = get_config('statusnet','sites');
730 if (is_array($sites)){
731 foreach($sites as $id=>$s){
732 $sitesform[] = Array(
733 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
734 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
735 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
736 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
737 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
741 /* empty form to add new site */
743 $sitesform[] = Array(
744 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
745 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
746 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
747 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
750 $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
751 $o = replace_macros($t, array(
752 '$submit' => t('Submit'),
753 '$sites' => $sitesform,
757 function statusnet_cron($a,$b) {
758 $last = get_config('statusnet','last_poll');
760 $poll_interval = intval(get_config('statusnet','poll_interval'));
762 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
765 $next = $last + ($poll_interval * 60);
767 logger('statusnet: poll intervall not reached');
771 logger('statusnet: cron_start');
773 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
776 logger('statusnet: fetching for user '.$rr['uid']);
777 statusnet_fetchtimeline($a, $rr['uid']);
781 logger('statusnet: cron_end');
783 set_config('statusnet','last_poll', time());
786 function statusnet_fetchtimeline($a, $uid) {
787 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
788 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
789 $api = get_pconfig($uid, 'statusnet', 'baseapi');
790 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
791 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
792 $lastid = get_pconfig($uid, 'statusnet', 'lastid');
794 $application_name = get_config('statusnet', 'application_name');
796 if ($application_name == "")
797 $application_name = $a->get_hostname();
799 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
801 $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
803 $first_time = ($lastid == "");
806 $parameters["since_id"] = $lastid;
808 $items = $connection->get('statuses/user_timeline', $parameters);
810 if (!is_array($items))
813 $posts = array_reverse($items);
816 foreach ($posts as $post) {
817 if ($post->id > $lastid)
823 if (is_object($post->retweeted_status))
826 if ($post->in_reply_to_status_id != "")
829 if (!strpos($post->source, $application_name)) {
830 $_SESSION["authenticated"] = true;
831 $_SESSION["uid"] = $uid;
833 $_REQUEST["type"] = "wall";
834 $_REQUEST["api_source"] = true;
835 $_REQUEST["profile_uid"] = $uid;
836 $_REQUEST["source"] = "StatusNet";
838 //$_REQUEST["date"] = $post->created_at;
840 $_REQUEST["body"] = $post->text;
841 if (is_string($post->place->name))
842 $_REQUEST["location"] = $post->place->name;
844 if (is_string($post->place->full_name))
845 $_REQUEST["location"] = $post->place->full_name;
847 if (is_array($post->geo->coordinates))
848 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
850 if (is_array($post->coordinates->coordinates))
851 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
853 //print_r($_REQUEST);
854 if ($_REQUEST["body"] != "") {
855 logger('statusnet: posting for user '.$uid);
857 require_once('mod/item.php');
863 set_pconfig($uid, 'statusnet', 'lastid', $lastid);