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>
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
10 /* StatusNet Plugin for Friendica
12 * Author: Tobias Diekershoff
13 * tobias.diekershoff@gmx.net
15 * License:3-clause BSD license
18 * To activate the plugin itself add it to the $a->config['system']['addon']
19 * setting. After this, your user can configure their Twitter account settings
20 * from "Settings -> Plugin Settings".
22 * Requirements: PHP5, curl [Slinky library]
24 * Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/StatusNet_Plugin
28 * We have to alter the TwitterOAuth class a little bit to work with any StatusNet
29 * installation abroad. Basically it's only make the API path variable and be happy.
31 * Thank you guys for the Twitter compatible API!
34 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
36 require_once('library/twitteroauth.php');
38 class StatusNetOAuth extends TwitterOAuth {
39 function get_maxlength() {
40 $config = $this->get($this->host . 'statusnet/config.json');
41 return $config->site->textlimit;
43 function accessTokenURL() { return $this->host.'oauth/access_token'; }
44 function authenticateURL() { return $this->host.'oauth/authenticate'; }
45 function authorizeURL() { return $this->host.'oauth/authorize'; }
46 function requestTokenURL() { return $this->host.'oauth/request_token'; }
47 function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
48 parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
49 $this->host = $apipath;
52 * Make an HTTP request
56 * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
58 function http($url, $method, $postfields = NULL) {
59 $this->http_info = array();
62 $prx = get_config('system','proxy');
64 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
65 curl_setopt($ci, CURLOPT_PROXY, $prx);
66 $prxusr = get_config('system','proxyuser');
68 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
70 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
71 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
72 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
73 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
74 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
75 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
76 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
77 curl_setopt($ci, CURLOPT_HEADER, FALSE);
81 curl_setopt($ci, CURLOPT_POST, TRUE);
82 if (!empty($postfields)) {
83 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
87 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
88 if (!empty($postfields)) {
89 $url = "{$url}?{$postfields}";
93 curl_setopt($ci, CURLOPT_URL, $url);
94 $response = curl_exec($ci);
95 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
96 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
103 function statusnet_install() {
104 // we need some hooks, for the configuration and for sending tweets
105 register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
106 register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
107 register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
108 register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
109 register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
110 register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
111 logger("installed statusnet");
115 function statusnet_uninstall() {
116 unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
117 unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
118 unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
119 unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
120 unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
121 unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
123 // old setting - remove only
124 unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
125 unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
126 unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
130 function statusnet_jot_nets(&$a,&$b) {
134 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
135 if(intval($statusnet_post) == 1) {
136 $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default');
137 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
138 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
139 . t('Post to StatusNet') . '</div>';
143 function statusnet_settings_post ($a,$post) {
146 // don't check statusnet settings if statusnet submit button is not clicked
147 if (!x($_POST,'statusnet-submit')) return;
149 if (isset($_POST['statusnet-disconnect'])) {
151 * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
153 del_pconfig(local_user(), 'statusnet', 'consumerkey');
154 del_pconfig(local_user(), 'statusnet', 'consumersecret');
155 del_pconfig(local_user(), 'statusnet', 'post');
156 del_pconfig(local_user(), 'statusnet', 'post_by_default');
157 del_pconfig(local_user(), 'statusnet', 'oauthtoken');
158 del_pconfig(local_user(), 'statusnet', 'oauthsecret');
159 del_pconfig(local_user(), 'statusnet', 'baseapi');
160 del_pconfig(local_user(), 'statusnet', 'post_taglinks');
161 del_pconfig(local_user(), 'statusnet', 'lastid');
162 del_pconfig(local_user(), 'statusnet', 'mirror_posts');
163 del_pconfig(local_user(), 'statusnet', 'intelligent_shortening');
165 if (isset($_POST['statusnet-preconf-apiurl'])) {
167 * If the user used one of the preconfigured StatusNet server credentials
168 * use them. All the data are available in the global config.
169 * Check the API Url never the less and blame the admin if it's not working ^^
171 $globalsn = get_config('statusnet', 'sites');
172 foreach ( $globalsn as $asn) {
173 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
174 $apibase = $asn['apiurl'];
175 $c = fetch_url( $apibase . 'statusnet/version.xml' );
176 if (strlen($c) > 0) {
177 set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
178 set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
179 set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
180 set_pconfig(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
182 notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
186 goaway($a->get_baseurl().'/settings/connectors');
188 if (isset($_POST['statusnet-consumersecret'])) {
189 // check if we can reach the API of the StatusNet server
190 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
191 // resign quickly after this one try to fix the path ;-)
192 $apibase = $_POST['statusnet-baseapi'];
193 $c = fetch_url( $apibase . 'statusnet/version.xml' );
194 if (strlen($c) > 0) {
195 // ok the API path is correct, let's save the settings
196 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
197 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
198 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
199 set_pconfig(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
201 // the API path is not correct, maybe missing trailing / ?
202 $apibase = $apibase . '/';
203 $c = fetch_url( $apibase . 'statusnet/version.xml' );
204 if (strlen($c) > 0) {
205 // ok the API path is now correct, let's save the settings
206 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
207 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
208 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
210 // still not the correct API base, let's do noting
211 notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
214 goaway($a->get_baseurl().'/settings/connectors');
216 if (isset($_POST['statusnet-pin'])) {
217 // if the user supplied us with a PIN from StatusNet, let the magic of OAuth happen
218 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
219 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
220 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
221 // the token and secret for which the PIN was generated were hidden in the settings
222 // form as token and token2, we need a new connection to Twitter using these token
223 // and secret to request a Access Token with the PIN
224 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
225 $token = $connection->getAccessToken( $_POST['statusnet-pin'] );
226 // ok, now that we have the Access Token, save them in the user config
227 set_pconfig(local_user(),'statusnet', 'oauthtoken', $token['oauth_token']);
228 set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
229 set_pconfig(local_user(),'statusnet', 'post', 1);
230 set_pconfig(local_user(),'statusnet', 'post_taglinks', 1);
231 // reload the Addon Settings page, if we don't do it see Bug #42
232 goaway($a->get_baseurl().'/settings/connectors');
234 // if no PIN is supplied in the POST variables, the user has changed the setting
235 // to post a dent for every new __public__ posting to the wall
236 set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
237 set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
238 set_pconfig(local_user(),'statusnet','post_taglinks',intval($_POST['statusnet-sendtaglinks']));
239 set_pconfig(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
240 set_pconfig(local_user(), 'statusnet', 'intelligent_shortening', intval($_POST['statusnet-shortening']));
241 info( t('StatusNet settings updated.') . EOL);
244 function statusnet_settings(&$a,&$s) {
247 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
249 * 1) Check that we have a base api url and a consumer key & secret
250 * 2) If no OAuthtoken & stuff is present, generate button to get some
251 * allow the user to cancel the connection process at this step
252 * 3) Checkbox for "Send public notices (respect size limitation)
254 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
255 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
256 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
257 $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken' );
258 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
259 $enabled = get_pconfig(local_user(), 'statusnet', 'post');
260 $checked = (($enabled) ? ' checked="checked" ' : '');
261 $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
262 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
263 $linksenabled = get_pconfig(local_user(),'statusnet','post_taglinks');
264 $linkschecked = (($linksenabled) ? ' checked="checked" ' : '');
266 $mirrorenabled = get_pconfig(local_user(),'statusnet','mirror_posts');
267 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
268 $shorteningenabled = get_pconfig(local_user(),'statusnet','intelligent_shortening');
269 $shorteningchecked = (($shorteningenabled) ? ' checked="checked" ' : '');
271 $s .= '<div class="settings-block">';
272 $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
274 if ( (!$ckey) && (!$csecret) ) {
278 $globalsn = get_config('statusnet', 'sites');
280 * lets check if we have one or more globally configured StatusNet
281 * server OAuth credentials in the configuration. If so offer them
282 * with a little explanation to the user as choice - otherwise
283 * ignore this option entirely.
285 if (! $globalsn == null) {
286 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
287 $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>';
288 $s .= '<div id="statusnet-preconf-wrapper">';
289 foreach ($globalsn as $asn) {
290 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
292 $s .= '<p></p><div class="clear"></div></div>';
293 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
295 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
296 $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>';
297 $s .= '<div id="statusnet-consumer-wrapper">';
298 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
299 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
300 $s .= '<div class="clear"></div>';
301 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
302 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
303 $s .= '<div class="clear"></div>';
304 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
305 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
306 $s .= '<p></p><div class="clear"></div></div>';
307 $s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('StatusNet application name').'</label>';
308 $s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
309 $s .= '<p></p><div class="clear"></div></div>';
310 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
313 * ok we have a consumer key pair now look into the OAuth stuff
315 if ( (!$otoken) && (!$osecret) ) {
317 * the user has not yet connected the account to statusnet
318 * get a temporary OAuth key/secret pair and display a button with
319 * which the user can request a PIN to connect the account to a
320 * account at statusnet
322 $connection = new StatusNetOAuth($api, $ckey, $csecret);
323 $request_token = $connection->getRequestToken('oob');
324 $token = $request_token['oauth_token'];
326 * make some nice form
328 $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>';
329 $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
330 $s .= '<div id="statusnet-pin-wrapper">';
331 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
332 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
333 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
334 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
335 $s .= '</div><div class="clear"></div>';
336 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
337 $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
338 $s .= '<div id="statusnet-cancel-wrapper">';
339 $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
340 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
341 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
342 $s .= '</div><div class="clear"></div>';
343 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
346 * we have an OAuth key / secret pair for the user
347 * so let's give a chance to disable the postings to statusnet
349 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
350 $details = $connection->get('account/verify_credentials');
351 $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>';
352 $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>';
353 if ($a->user['hidewall']) {
354 $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>';
356 $s .= '<div id="statusnet-enable-wrapper">';
357 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
358 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
359 $s .= '<div class="clear"></div>';
360 $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
361 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
362 $s .= '<div class="clear"></div>';
364 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from statusnet that are no replies or repeated messages').'</label>';
365 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
366 $s .= '<div class="clear"></div>';
368 $s .= '<label id="statusnet-shortening-label" for="statusnet-shortening">'.t('Shortening method that optimizes the post').'</label>';
369 $s .= '<input id="statusnet-shortening" type="checkbox" name="statusnet-shortening" value="1" '. $shorteningchecked . '/>';
370 $s .= '<div class="clear"></div>';
372 $s .= '<label id="statusnet-sendtaglinks-label" for="statusnet-sendtaglinks">'.t('Send linked #-tags and @-names to StatusNet').'</label>';
373 $s .= '<input id="statusnet-sendtaglinks" type="checkbox" name="statusnet-sendtaglinks" value="1" '. $linkschecked . '/>';
374 $s .= '</div><div class="clear"></div>';
376 $s .= '<div id="statusnet-disconnect-wrapper">';
377 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
378 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
379 $s .= '</div><div class="clear"></div>';
380 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
383 $s .= '</div><div class="clear"></div></div>';
387 function statusnet_post_local(&$a,&$b) {
391 if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
393 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
394 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
396 // if API is used, default to the chosen settings
397 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
398 $statusnet_enable = 1;
400 if(! $statusnet_enable)
403 if(strlen($b['postopts']))
404 $b['postopts'] .= ',';
405 $b['postopts'] .= 'statusnet';
409 if (! function_exists( 'short_link' )) {
410 function short_link($url) {
411 require_once('library/slinky.php');
412 $slinky = new Slinky( $url );
413 $yourls_url = get_config('yourls','url1');
415 $yourls_username = get_config('yourls','username1');
416 $yourls_password = get_config('yourls', 'password1');
417 $yourls_ssl = get_config('yourls', 'ssl1');
418 $yourls = new Slinky_YourLS();
419 $yourls->set( 'username', $yourls_username );
420 $yourls->set( 'password', $yourls_password );
421 $yourls->set( 'ssl', $yourls_ssl );
422 $yourls->set( 'yourls-url', $yourls_url );
423 $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
426 // setup a cascade of shortening services
427 // try to get a short link from these services
428 // in the order ur1.ca, trim, id.gd, tinyurl
429 $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
431 return $slinky->short();
434 function statusnet_shortenmsg($b, $max_char) {
435 require_once("include/bbcode.php");
436 require_once("include/html2plain.php");
438 // Looking for the first image
440 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
441 $image = $matches[3];
444 if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
445 $image = $matches[1];
447 $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
449 // When saved into the database the content is sent through htmlspecialchars
450 // That means that we have to decode all image-urls
451 $image = htmlspecialchars_decode($image);
454 if ($b["title"] != "")
455 $body = $b["title"]."\n\n".$body;
457 if (strpos($body, "[bookmark") !== false) {
458 // splitting the text in two parts:
459 // before and after the bookmark
460 $pos = strpos($body, "[bookmark");
461 $body1 = substr($body, 0, $pos);
462 $body2 = substr($body, $pos);
464 // Removing all quotes after the bookmark
465 // they are mostly only the content after the bookmark.
466 $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
467 $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
468 $body = $body1.$body2;
471 // Add some newlines so that the message could be cut better
472 $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
473 array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
475 // remove the recycle signs and the names since they aren't helpful on twitter
477 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
478 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
480 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
481 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
483 // remove the share element
484 $body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
486 // At first convert the text to html
487 $html = bbcode($body, false, false);
489 // Then convert it to plain text
490 //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
491 $msg = trim(html2plain($html, 0, true));
492 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
494 // Removing multiple newlines
495 while (strpos($msg, "\n\n\n") !== false)
496 $msg = str_replace("\n\n\n", "\n\n", $msg);
498 // Removing multiple spaces
499 while (strpos($msg, " ") !== false)
500 $msg = str_replace(" ", " ", $msg);
505 $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
510 // look for bookmark-bbcode and handle it with priority
511 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
514 $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
516 // If there is no bookmark element then take the first link
518 $links = collecturls($html);
519 if (sizeof($links) > 0) {
521 $link = current($links);
523 $multiplelinks = (sizeof($links) > 1);
528 $msglink = $b["plink"];
529 else if ($link != "")
531 else if ($multipleimages)
532 $msglink = $b["plink"];
533 else if ($image != "")
536 if (($msglink == "") and strlen($msg) > $max_char)
537 $msglink = $b["plink"];
539 // If the message is short enough then don't modify it. (if the link exists in the original message)
540 if ((strlen(trim($origmsg)) <= $max_char) AND (strpos($origmsg, $msglink) OR ($msglink == "")))
541 return(array("msg"=>trim($origmsg), "image"=>""));
543 if (strlen($msglink) > 20)
544 $msglink = short_link($msglink);
546 if (strlen(trim($msg." ".$msglink)) > $max_char) {
547 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
548 $lastchar = substr($msg, -1);
549 $msg = substr($msg, 0, -1);
550 $pos = strrpos($msg, "\n");
552 $msg = substr($msg, 0, $pos);
553 else if ($lastchar != "\n")
554 $msg = substr($msg, 0, -3)."...";
556 $msg = str_replace("\n", " ", $msg);
558 // Removing multiple spaces - again
559 while (strpos($msg, " ") !== false)
560 $msg = str_replace(" ", " ", $msg);
562 return(array("msg"=>trim($msg." ".$msglink), "image"=>$image));
565 function statusnet_post_hook(&$a,&$b) {
571 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
574 if(! strstr($b['postopts'],'statusnet'))
577 if($b['parent'] != $b['id'])
580 // if posts comes from statusnet don't send it back
581 if($b['app'] == "StatusNet")
584 logger('statusnet post invoked');
586 load_pconfig($b['uid'], 'statusnet');
588 $api = get_pconfig($b['uid'], 'statusnet', 'baseapi');
589 $ckey = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
590 $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
591 $otoken = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
592 $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
593 $intelligent_shortening = get_pconfig($b['uid'], 'statusnet', 'intelligent_shortening');
595 // Global setting overrides this
596 if (get_config('statusnet','intelligent_shortening'))
597 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
599 if($ckey && $csecret && $otoken && $osecret) {
601 require_once('include/bbcode.php');
602 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
603 $max_char = $dent->get_maxlength(); // max. length for a dent
604 // we will only work with up to two times the length of the dent
605 // we can later send to StatusNet. This way we can "gain" some
606 // information during shortening of potential links but do not
607 // shorten all the links in a 200000 character long essay.
610 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
611 if (!$intelligent_shortening) {
612 if (! $b['title']=='') {
613 $tmp = $b['title'].": \n".$b['body'];
614 // $tmp = substr($tmp, 0, 4*$max_char);
616 $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
618 // if [url=bla][img]blub.png[/img][/url] get blub.png
619 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
620 // preserve links to images, videos and audios
621 $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
622 $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
623 $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
624 $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
625 $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
626 $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
627 $linksenabled = get_pconfig($b['uid'],'statusnet','post_taglinks');
628 // if a #tag is linked, don't send the [url] over to SN
629 // that is, don't send if the option is not set in the
630 // connector settings
631 if ($linksenabled=='0') {
633 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
635 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
637 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
638 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
640 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
641 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
643 // preserve links to webpages
644 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
645 $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
646 // find all http or https links in the body of the entry and
647 // apply the shortener if the link is longer then 20 characters
648 if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
649 preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls );
650 foreach ($allurls as $url) {
651 foreach ($url as $u) {
653 $sl = short_link($u);
654 $tmp = str_replace( $u, $sl, $tmp );
659 // ok, all the links we want to send out are save, now strip
660 // away the remaining bbcode
661 //$msg = strip_tags(bbcode($tmp, false, false));
662 $msg = bbcode($tmp, false, false, true);
663 $msg = str_replace(array('<br>','<br />'),"\n",$msg);
664 $msg = strip_tags($msg);
666 // quotes not working - let's try this
667 $msg = html_entity_decode($msg);
669 if (( strlen($msg) > $max_char) && $max_char > 0) {
670 $shortlink = short_link( $b['plink'] );
671 // the new message will be shortened such that "... $shortlink"
672 // will fit into the character limit
673 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
674 $msg = str_replace(array('<br>','<br />'),' ',$msg);
675 $e = explode(' ', $msg);
676 // remove the last word from the cut down message to
677 // avoid sending cut words to the MicroBlog
679 $msg = implode(' ', $e);
680 $msg .= '... ' . $shortlink;
684 $postdata = array('status' => $msg);
686 $msgarr = statusnet_shortenmsg($b, $max_char);
687 $msg = $msgarr["msg"];
688 $image = $msgarr["image"];
690 $imagedata = file_get_contents($image);
691 $tempfile = tempnam(get_config("system","temppath"), "upload");
692 file_put_contents($tempfile, $imagedata);
693 $postdata = array("status"=>$msg, "media"=>"@".$tempfile);
695 $postdata = array("status"=>$msg);
698 // and now dent it :-)
700 //$result = $dent->post('statuses/update', array('status' => $msg));
701 $result = $dent->post('statuses/update', $postdata);
702 logger('statusnet_post send, result: ' . print_r($result, true).
703 "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
704 if ($result->error) {
705 logger('Send to StatusNet failed: "' . $result->error . '"');
713 function statusnet_plugin_admin_post(&$a){
717 foreach($_POST['sitename'] as $id=>$sitename){
718 $sitename=trim($sitename);
719 $apiurl=trim($_POST['apiurl'][$id]);
720 $secret=trim($_POST['secret'][$id]);
721 $key=trim($_POST['key'][$id]);
722 $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
727 !x($_POST['delete'][$id])){
730 'sitename' => $sitename,
732 'consumersecret' => $secret,
733 'consumerkey' => $key,
734 'applicationname' => $applicationname
739 $sites = set_config('statusnet','sites', $sites);
743 function statusnet_plugin_admin(&$a, &$o){
745 $sites = get_config('statusnet','sites');
747 if (is_array($sites)){
748 foreach($sites as $id=>$s){
749 $sitesform[] = Array(
750 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
751 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
752 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
753 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
754 'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
755 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
759 /* empty form to add new site */
761 $sitesform[] = Array(
762 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
763 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
764 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
765 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
766 'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
769 $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
770 $o = replace_macros($t, array(
771 '$submit' => t('Submit'),
772 '$sites' => $sitesform,
776 function statusnet_cron($a,$b) {
777 $last = get_config('statusnet','last_poll');
779 $poll_interval = intval(get_config('statusnet','poll_interval'));
781 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
784 $next = $last + ($poll_interval * 60);
786 logger('statusnet: poll intervall not reached');
790 logger('statusnet: cron_start');
792 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
795 logger('statusnet: fetching for user '.$rr['uid']);
796 statusnet_fetchtimeline($a, $rr['uid']);
800 logger('statusnet: cron_end');
802 set_config('statusnet','last_poll', time());
805 function statusnet_fetchtimeline($a, $uid) {
806 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
807 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
808 $api = get_pconfig($uid, 'statusnet', 'baseapi');
809 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
810 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
811 $lastid = get_pconfig($uid, 'statusnet', 'lastid');
813 // get the application name for the SN app
814 // 1st try personal config, then system config and fallback to the
815 // hostname of the node if neither one is set.
816 $application_name = get_pconfig( $uid, 'statusnet', 'application_name');
817 if ($application_name == "")
818 $application_name = get_config('statusnet', 'application_name');
819 if ($application_name == "")
820 $application_name = $a->get_hostname();
822 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
824 $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
826 $first_time = ($lastid == "");
829 $parameters["since_id"] = $lastid;
831 $items = $connection->get('statuses/user_timeline', $parameters);
833 if (!is_array($items))
836 $posts = array_reverse($items);
839 foreach ($posts as $post) {
840 if ($post->id > $lastid)
846 if (is_object($post->retweeted_status))
849 if ($post->in_reply_to_status_id != "")
852 if (!strpos($post->source, $application_name)) {
853 $_SESSION["authenticated"] = true;
854 $_SESSION["uid"] = $uid;
856 $_REQUEST["type"] = "wall";
857 $_REQUEST["api_source"] = true;
858 $_REQUEST["profile_uid"] = $uid;
859 $_REQUEST["source"] = "StatusNet";
861 //$_REQUEST["date"] = $post->created_at;
863 $_REQUEST["body"] = $post->text;
864 if (is_string($post->place->name))
865 $_REQUEST["location"] = $post->place->name;
867 if (is_string($post->place->full_name))
868 $_REQUEST["location"] = $post->place->full_name;
870 if (is_array($post->geo->coordinates))
871 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
873 if (is_array($post->coordinates->coordinates))
874 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
876 //print_r($_REQUEST);
877 if ($_REQUEST["body"] != "") {
878 logger('statusnet: posting for user '.$uid);
880 require_once('mod/item.php');
886 set_pconfig($uid, 'statusnet', 'lastid', $lastid);