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'] );
179 set_pconfig(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
181 notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
185 goaway($a->get_baseurl().'/settings/connectors');
187 if (isset($_POST['statusnet-consumersecret'])) {
188 // check if we can reach the API of the StatusNet server
189 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
190 // resign quickly after this one try to fix the path ;-)
191 $apibase = $_POST['statusnet-baseapi'];
192 $c = fetch_url( $apibase . 'statusnet/version.xml' );
193 if (strlen($c) > 0) {
194 // ok the API path is correct, let's save the settings
195 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
196 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
197 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
198 set_pconfig(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
200 // the API path is not correct, maybe missing trailing / ?
201 $apibase = $apibase . '/';
202 $c = fetch_url( $apibase . 'statusnet/version.xml' );
203 if (strlen($c) > 0) {
204 // ok the API path is now correct, let's save the settings
205 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
206 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
207 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
209 // still not the correct API base, let's do noting
210 notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
213 goaway($a->get_baseurl().'/settings/connectors');
215 if (isset($_POST['statusnet-pin'])) {
216 // if the user supplied us with a PIN from StatusNet, let the magic of OAuth happen
217 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
218 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
219 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
220 // the token and secret for which the PIN was generated were hidden in the settings
221 // form as token and token2, we need a new connection to Twitter using these token
222 // and secret to request a Access Token with the PIN
223 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
224 $token = $connection->getAccessToken( $_POST['statusnet-pin'] );
225 // ok, now that we have the Access Token, save them in the user config
226 set_pconfig(local_user(),'statusnet', 'oauthtoken', $token['oauth_token']);
227 set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
228 set_pconfig(local_user(),'statusnet', 'post', 1);
229 set_pconfig(local_user(),'statusnet', 'post_taglinks', 1);
230 // reload the Addon Settings page, if we don't do it see Bug #42
231 goaway($a->get_baseurl().'/settings/connectors');
233 // if no PIN is supplied in the POST variables, the user has changed the setting
234 // to post a dent for every new __public__ posting to the wall
235 set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
236 set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
237 set_pconfig(local_user(),'statusnet','post_taglinks',intval($_POST['statusnet-sendtaglinks']));
238 set_pconfig(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
239 set_pconfig(local_user(), 'statusnet', 'intelligent_shortening', intval($_POST['statusnet-shortening']));
240 info( t('StatusNet settings updated.') . EOL);
243 function statusnet_settings(&$a,&$s) {
246 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
248 * 1) Check that we have a base api url and a consumer key & secret
249 * 2) If no OAuthtoken & stuff is present, generate button to get some
250 * allow the user to cancel the connection process at this step
251 * 3) Checkbox for "Send public notices (respect size limitation)
253 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
254 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
255 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
256 $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken' );
257 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
258 $enabled = get_pconfig(local_user(), 'statusnet', 'post');
259 $checked = (($enabled) ? ' checked="checked" ' : '');
260 $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
261 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
262 $linksenabled = get_pconfig(local_user(),'statusnet','post_taglinks');
263 $linkschecked = (($linksenabled) ? ' checked="checked" ' : '');
265 $mirrorenabled = get_pconfig(local_user(),'statusnet','mirror_posts');
266 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
267 $shorteningenabled = get_pconfig(local_user(),'statusnet','intelligent_shortening');
268 $shorteningchecked = (($shorteningenabled) ? ' checked="checked" ' : '');
270 $s .= '<div class="settings-block">';
271 $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
273 if ( (!$ckey) && (!$csecret) ) {
277 $globalsn = get_config('statusnet', 'sites');
279 * lets check if we have one or more globally configured StatusNet
280 * server OAuth credentials in the configuration. If so offer them
281 * with a little explanation to the user as choice - otherwise
282 * ignore this option entirely.
284 if (! $globalsn == null) {
285 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
286 $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>';
287 $s .= '<div id="statusnet-preconf-wrapper">';
288 foreach ($globalsn as $asn) {
289 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<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>';
294 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
295 $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>';
296 $s .= '<div id="statusnet-consumer-wrapper">';
297 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
298 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
299 $s .= '<div class="clear"></div>';
300 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
301 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
302 $s .= '<div class="clear"></div>';
303 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
304 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
305 $s .= '<p></p><div class="clear"></div></div>';
306 $s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('StatusNet application name').'</label>';
307 $s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
308 $s .= '<p></p><div class="clear"></div></div>';
309 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
312 * ok we have a consumer key pair now look into the OAuth stuff
314 if ( (!$otoken) && (!$osecret) ) {
316 * the user has not yet connected the account to statusnet
317 * get a temporary OAuth key/secret pair and display a button with
318 * which the user can request a PIN to connect the account to a
319 * account at statusnet
321 $connection = new StatusNetOAuth($api, $ckey, $csecret);
322 $request_token = $connection->getRequestToken('oob');
323 $token = $request_token['oauth_token'];
325 * make some nice form
327 $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>';
328 $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
329 $s .= '<div id="statusnet-pin-wrapper">';
330 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
331 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
332 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
333 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
334 $s .= '</div><div class="clear"></div>';
335 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
336 $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
337 $s .= '<div id="statusnet-cancel-wrapper">';
338 $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
339 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
340 $s .= '<input id="statusnet-cancel" 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>';
345 * we have an OAuth key / secret pair for the user
346 * so let's give a chance to disable the postings to statusnet
348 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
349 $details = $connection->get('account/verify_credentials');
350 $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>';
351 $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>';
352 if ($a->user['hidewall']) {
353 $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>';
355 $s .= '<div id="statusnet-enable-wrapper">';
356 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
357 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
358 $s .= '<div class="clear"></div>';
359 $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
360 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
361 $s .= '<div class="clear"></div>';
363 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from statusnet that are no replies or repeated messages').'</label>';
364 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
365 $s .= '<div class="clear"></div>';
367 $s .= '<label id="statusnet-shortening-label" for="statusnet-shortening">'.t('Shortening method that optimizes the post').'</label>';
368 $s .= '<input id="statusnet-shortening" type="checkbox" name="statusnet-shortening" value="1" '. $shorteningchecked . '/>';
369 $s .= '<div class="clear"></div>';
371 $s .= '<label id="statusnet-sendtaglinks-label" for="statusnet-sendtaglinks">'.t('Send linked #-tags and @-names to StatusNet').'</label>';
372 $s .= '<input id="statusnet-sendtaglinks" type="checkbox" name="statusnet-sendtaglinks" value="1" '. $linkschecked . '/>';
373 $s .= '</div><div class="clear"></div>';
375 $s .= '<div id="statusnet-disconnect-wrapper">';
376 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
377 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
378 $s .= '</div><div class="clear"></div>';
379 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
382 $s .= '</div><div class="clear"></div></div>';
386 function statusnet_post_local(&$a,&$b) {
390 if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
392 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
393 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
395 // if API is used, default to the chosen settings
396 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
397 $statusnet_enable = 1;
399 if(! $statusnet_enable)
402 if(strlen($b['postopts']))
403 $b['postopts'] .= ',';
404 $b['postopts'] .= 'statusnet';
408 if (! function_exists( 'short_link' )) {
409 function short_link($url) {
410 require_once('library/slinky.php');
411 $slinky = new Slinky( $url );
412 $yourls_url = get_config('yourls','url1');
414 $yourls_username = get_config('yourls','username1');
415 $yourls_password = get_config('yourls', 'password1');
416 $yourls_ssl = get_config('yourls', 'ssl1');
417 $yourls = new Slinky_YourLS();
418 $yourls->set( 'username', $yourls_username );
419 $yourls->set( 'password', $yourls_password );
420 $yourls->set( 'ssl', $yourls_ssl );
421 $yourls->set( 'yourls-url', $yourls_url );
422 $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
425 // setup a cascade of shortening services
426 // try to get a short link from these services
427 // in the order ur1.ca, trim, id.gd, tinyurl
428 $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
430 return $slinky->short();
433 function statusnet_shortenmsg($b, $max_char) {
434 require_once("include/bbcode.php");
435 require_once("include/html2plain.php");
437 // Looking for the first image
439 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
440 $image = $matches[3];
443 if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
444 $image = $matches[1];
446 $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
448 // When saved into the database the content is sent through htmlspecialchars
449 // That means that we have to decode all image-urls
450 $image = htmlspecialchars_decode($image);
453 if ($b["title"] != "")
454 $body = $b["title"]."\n\n".$body;
456 if (strpos($body, "[bookmark") !== false) {
457 // splitting the text in two parts:
458 // before and after the bookmark
459 $pos = strpos($body, "[bookmark");
460 $body1 = substr($body, 0, $pos);
461 $body2 = substr($body, $pos);
463 // Removing all quotes after the bookmark
464 // they are mostly only the content after the bookmark.
465 $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
466 $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
467 $body = $body1.$body2;
470 // Add some newlines so that the message could be cut better
471 $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
472 array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
474 // remove the recycle signs and the names since they aren't helpful on twitter
476 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
477 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
479 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
480 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
482 // remove the share element
483 $body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
485 // At first convert the text to html
486 $html = bbcode($body, false, false);
488 // Then convert it to plain text
489 //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
490 $msg = trim(html2plain($html, 0, true));
491 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
493 // Removing multiple newlines
494 while (strpos($msg, "\n\n\n") !== false)
495 $msg = str_replace("\n\n\n", "\n\n", $msg);
497 // Removing multiple spaces
498 while (strpos($msg, " ") !== false)
499 $msg = str_replace(" ", " ", $msg);
504 $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
509 // look for bookmark-bbcode and handle it with priority
510 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
513 $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
515 // If there is no bookmark element then take the first link
517 $links = collecturls($html);
518 if (sizeof($links) > 0) {
520 $link = current($links);
522 $multiplelinks = (sizeof($links) > 1);
527 $msglink = $b["plink"];
528 else if ($link != "")
530 else if ($multipleimages)
531 $msglink = $b["plink"];
532 else if ($image != "")
535 if (($msglink == "") and strlen($msg) > $max_char)
536 $msglink = $b["plink"];
538 // If the message is short enough then don't modify it. (if the link exists in the original message)
539 if ((strlen(trim($origmsg)) <= $max_char) AND (strpos($origmsg, $msglink) OR ($msglink == "")))
540 return(array("msg"=>trim($origmsg), "image"=>""));
542 if (strlen($msglink) > 20)
543 $msglink = short_link($msglink);
545 if (strlen(trim($msg." ".$msglink)) > $max_char) {
546 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
547 $lastchar = substr($msg, -1);
548 $msg = substr($msg, 0, -1);
549 $pos = strrpos($msg, "\n");
551 $msg = substr($msg, 0, $pos);
552 else if ($lastchar != "\n")
553 $msg = substr($msg, 0, -3)."...";
555 $msg = str_replace("\n", " ", $msg);
557 // Removing multiple spaces - again
558 while (strpos($msg, " ") !== false)
559 $msg = str_replace(" ", " ", $msg);
561 return(array("msg"=>trim($msg." ".$msglink), "image"=>$image));
564 function statusnet_post_hook(&$a,&$b) {
570 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
573 if(! strstr($b['postopts'],'statusnet'))
576 if($b['parent'] != $b['id'])
579 // if posts comes from statusnet don't send it back
580 if($b['app'] == "StatusNet")
583 logger('statusnet post invoked');
585 load_pconfig($b['uid'], 'statusnet');
587 $api = get_pconfig($b['uid'], 'statusnet', 'baseapi');
588 $ckey = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
589 $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
590 $otoken = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
591 $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
592 $intelligent_shortening = get_pconfig($b['uid'], 'statusnet', 'intelligent_shortening');
594 // Global setting overrides this
595 if (get_config('statusnet','intelligent_shortening'))
596 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
598 if($ckey && $csecret && $otoken && $osecret) {
600 require_once('include/bbcode.php');
601 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
602 $max_char = $dent->get_maxlength(); // max. length for a dent
603 // we will only work with up to two times the length of the dent
604 // we can later send to StatusNet. This way we can "gain" some
605 // information during shortening of potential links but do not
606 // shorten all the links in a 200000 character long essay.
609 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
610 if (!$intelligent_shortening) {
611 if (! $b['title']=='') {
612 $tmp = $b['title'].": \n".$b['body'];
613 // $tmp = substr($tmp, 0, 4*$max_char);
615 $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
617 // if [url=bla][img]blub.png[/img][/url] get blub.png
618 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
619 // preserve links to images, videos and audios
620 $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
621 $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
622 $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
623 $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
624 $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
625 $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
626 $linksenabled = get_pconfig($b['uid'],'statusnet','post_taglinks');
627 // if a #tag is linked, don't send the [url] over to SN
628 // that is, don't send if the option is not set in the
629 // connector settings
630 if ($linksenabled=='0') {
632 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
634 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
636 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
637 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
639 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
640 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
642 // preserve links to webpages
643 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
644 $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
645 // find all http or https links in the body of the entry and
646 // apply the shortener if the link is longer then 20 characters
647 if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
648 preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls );
649 foreach ($allurls as $url) {
650 foreach ($url as $u) {
652 $sl = short_link($u);
653 $tmp = str_replace( $u, $sl, $tmp );
658 // ok, all the links we want to send out are save, now strip
659 // away the remaining bbcode
660 //$msg = strip_tags(bbcode($tmp, false, false));
661 $msg = bbcode($tmp, false, false);
662 $msg = str_replace(array('<br>','<br />'),"\n",$msg);
663 $msg = strip_tags($msg);
665 // quotes not working - let's try this
666 $msg = html_entity_decode($msg);
668 if (( strlen($msg) > $max_char) && $max_char > 0) {
669 $shortlink = short_link( $b['plink'] );
670 // the new message will be shortened such that "... $shortlink"
671 // will fit into the character limit
672 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
673 $msg = str_replace(array('<br>','<br />'),' ',$msg);
674 $e = explode(' ', $msg);
675 // remove the last word from the cut down message to
676 // avoid sending cut words to the MicroBlog
678 $msg = implode(' ', $e);
679 $msg .= '... ' . $shortlink;
683 $postdata = array('status' => $msg);
685 $msgarr = statusnet_shortenmsg($b, $max_char);
686 $msg = $msgarr["msg"];
687 $image = $msgarr["image"];
689 $imagedata = file_get_contents($image);
690 $tempfile = tempnam(get_config("system","temppath"), "upload");
691 file_put_contents($tempfile, $imagedata);
692 $postdata = array("status"=>$msg, "media"=>"@".$tempfile);
694 $postdata = array("status"=>$msg);
697 // and now dent it :-)
699 //$result = $dent->post('statuses/update', array('status' => $msg));
700 $result = $dent->post('statuses/update', $postdata);
701 logger('statusnet_post send, result: ' . print_r($result, true).
702 "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
703 if ($result->error) {
704 logger('Send to StatusNet failed: "' . $result->error . '"');
712 function statusnet_plugin_admin_post(&$a){
716 foreach($_POST['sitename'] as $id=>$sitename){
717 $sitename=trim($sitename);
718 $apiurl=trim($_POST['apiurl'][$id]);
719 $secret=trim($_POST['secret'][$id]);
720 $key=trim($_POST['key'][$id]);
721 $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
726 !x($_POST['delete'][$id])){
729 'sitename' => $sitename,
731 'consumersecret' => $secret,
732 'consumerkey' => $key,
733 'applicationname' => $applicationname
738 $sites = set_config('statusnet','sites', $sites);
742 function statusnet_plugin_admin(&$a, &$o){
744 $sites = get_config('statusnet','sites');
746 if (is_array($sites)){
747 foreach($sites as $id=>$s){
748 $sitesform[] = Array(
749 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
750 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
751 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
752 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
753 'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
754 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
758 /* empty form to add new site */
760 $sitesform[] = Array(
761 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
762 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
763 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
764 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
765 'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
768 $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
769 $o = replace_macros($t, array(
770 '$submit' => t('Submit'),
771 '$sites' => $sitesform,
775 function statusnet_cron($a,$b) {
776 $last = get_config('statusnet','last_poll');
778 $poll_interval = intval(get_config('statusnet','poll_interval'));
780 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
783 $next = $last + ($poll_interval * 60);
785 logger('statusnet: poll intervall not reached');
789 logger('statusnet: cron_start');
791 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
794 logger('statusnet: fetching for user '.$rr['uid']);
795 statusnet_fetchtimeline($a, $rr['uid']);
799 logger('statusnet: cron_end');
801 set_config('statusnet','last_poll', time());
804 function statusnet_fetchtimeline($a, $uid) {
805 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
806 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
807 $api = get_pconfig($uid, 'statusnet', 'baseapi');
808 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
809 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
810 $lastid = get_pconfig($uid, 'statusnet', 'lastid');
812 // get the application name for the SN app
813 // 1st try personal config, then system config and fallback to the
814 // hostname of the node if neither one is set.
815 $application_name = get_pconfig( $uid, 'statusnet', 'application_name');
816 if ($application_name == "")
817 $application_name = get_config('statusnet', 'application_name');
818 if ($application_name == "")
819 $application_name = $a->get_hostname();
821 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
823 $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
825 $first_time = ($lastid == "");
828 $parameters["since_id"] = $lastid;
830 $items = $connection->get('statuses/user_timeline', $parameters);
832 if (!is_array($items))
835 $posts = array_reverse($items);
838 foreach ($posts as $post) {
839 if ($post->id > $lastid)
845 if (is_object($post->retweeted_status))
848 if ($post->in_reply_to_status_id != "")
851 if (!strpos($post->source, $application_name)) {
852 $_SESSION["authenticated"] = true;
853 $_SESSION["uid"] = $uid;
855 $_REQUEST["type"] = "wall";
856 $_REQUEST["api_source"] = true;
857 $_REQUEST["profile_uid"] = $uid;
858 $_REQUEST["source"] = "StatusNet";
860 //$_REQUEST["date"] = $post->created_at;
862 $_REQUEST["body"] = $post->text;
863 if (is_string($post->place->name))
864 $_REQUEST["location"] = $post->place->name;
866 if (is_string($post->place->full_name))
867 $_REQUEST["location"] = $post->place->full_name;
869 if (is_array($post->geo->coordinates))
870 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
872 if (is_array($post->coordinates->coordinates))
873 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
875 //print_r($_REQUEST);
876 if ($_REQUEST["body"] != "") {
877 logger('statusnet: posting for user '.$uid);
879 require_once('mod/item.php');
885 set_pconfig($uid, 'statusnet', 'lastid', $lastid);