3 * Name: StatusNet Connector
4 * Description: Relay public postings to a connected StatusNet account
6 * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
7 * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
9 * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel
10 * All rights reserved.
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions are met:
14 * * Redistributions of source code must retain the above copyright notice,
15 * this list of conditions and the following disclaimer.
16 * * Redistributions in binary form must reproduce the above
17 * * copyright notice, this list of conditions and the following disclaimer in
18 * the documentation and/or other materials provided with the distribution.
19 * * Neither the name of the <organization> nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
25 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
26 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
27 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
28 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
30 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
31 * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
32 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 * We have to alter the TwitterOAuth class a little bit to work with any StatusNet
39 * installation abroad. Basically it's only make the API path variable and be happy.
41 * Thank you guys for the Twitter compatible API!
44 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
46 require_once('library/twitteroauth.php');
48 class StatusNetOAuth extends TwitterOAuth {
49 function get_maxlength() {
50 $config = $this->get($this->host . 'statusnet/config.json');
51 return $config->site->textlimit;
53 function accessTokenURL() { return $this->host.'oauth/access_token'; }
54 function authenticateURL() { return $this->host.'oauth/authenticate'; }
55 function authorizeURL() { return $this->host.'oauth/authorize'; }
56 function requestTokenURL() { return $this->host.'oauth/request_token'; }
57 function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
58 parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
59 $this->host = $apipath;
62 * Make an HTTP request
66 * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
68 function http($url, $method, $postfields = NULL) {
69 $this->http_info = array();
72 $prx = get_config('system','proxy');
74 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
75 curl_setopt($ci, CURLOPT_PROXY, $prx);
76 $prxusr = get_config('system','proxyuser');
78 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
80 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
81 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
82 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
83 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
84 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
85 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
86 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
87 curl_setopt($ci, CURLOPT_HEADER, FALSE);
91 curl_setopt($ci, CURLOPT_POST, TRUE);
92 if (!empty($postfields)) {
93 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
97 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
98 if (!empty($postfields)) {
99 $url = "{$url}?{$postfields}";
103 curl_setopt($ci, CURLOPT_URL, $url);
104 $response = curl_exec($ci);
105 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
106 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
113 function statusnet_install() {
114 // we need some hooks, for the configuration and for sending tweets
115 register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
116 register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
117 register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
118 register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
119 register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
120 register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
121 logger("installed statusnet");
125 function statusnet_uninstall() {
126 unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
127 unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
128 unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
129 unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
130 unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
131 unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
133 // old setting - remove only
134 unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
135 unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
136 unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
140 function statusnet_jot_nets(&$a,&$b) {
144 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
145 if(intval($statusnet_post) == 1) {
146 $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default');
147 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
148 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
149 . t('Post to StatusNet') . '</div>';
153 function statusnet_settings_post ($a,$post) {
156 // don't check statusnet settings if statusnet submit button is not clicked
157 if (!x($_POST,'statusnet-submit')) return;
159 if (isset($_POST['statusnet-disconnect'])) {
161 * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
163 del_pconfig(local_user(), 'statusnet', 'consumerkey');
164 del_pconfig(local_user(), 'statusnet', 'consumersecret');
165 del_pconfig(local_user(), 'statusnet', 'post');
166 del_pconfig(local_user(), 'statusnet', 'post_by_default');
167 del_pconfig(local_user(), 'statusnet', 'oauthtoken');
168 del_pconfig(local_user(), 'statusnet', 'oauthsecret');
169 del_pconfig(local_user(), 'statusnet', 'baseapi');
170 del_pconfig(local_user(), 'statusnet', 'post_taglinks');
171 del_pconfig(local_user(), 'statusnet', 'lastid');
172 del_pconfig(local_user(), 'statusnet', 'mirror_posts');
173 del_pconfig(local_user(), 'statusnet', 'intelligent_shortening');
175 if (isset($_POST['statusnet-preconf-apiurl'])) {
177 * If the user used one of the preconfigured StatusNet server credentials
178 * use them. All the data are available in the global config.
179 * Check the API Url never the less and blame the admin if it's not working ^^
181 $globalsn = get_config('statusnet', 'sites');
182 foreach ( $globalsn as $asn) {
183 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
184 $apibase = $asn['apiurl'];
185 $c = fetch_url( $apibase . 'statusnet/version.xml' );
186 if (strlen($c) > 0) {
187 set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
188 set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
189 set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
190 set_pconfig(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
192 notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
196 goaway($a->get_baseurl().'/settings/connectors');
198 if (isset($_POST['statusnet-consumersecret'])) {
199 // check if we can reach the API of the StatusNet server
200 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
201 // resign quickly after this one try to fix the path ;-)
202 $apibase = $_POST['statusnet-baseapi'];
203 $c = fetch_url( $apibase . 'statusnet/version.xml' );
204 if (strlen($c) > 0) {
205 // ok the API path is 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 );
209 set_pconfig(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
211 // the API path is not correct, maybe missing trailing / ?
212 $apibase = $apibase . '/';
213 $c = fetch_url( $apibase . 'statusnet/version.xml' );
214 if (strlen($c) > 0) {
215 // ok the API path is now correct, let's save the settings
216 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
217 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
218 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
220 // still not the correct API base, let's do noting
221 notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
224 goaway($a->get_baseurl().'/settings/connectors');
226 if (isset($_POST['statusnet-pin'])) {
227 // if the user supplied us with a PIN from StatusNet, let the magic of OAuth happen
228 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
229 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
230 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
231 // the token and secret for which the PIN was generated were hidden in the settings
232 // form as token and token2, we need a new connection to Twitter using these token
233 // and secret to request a Access Token with the PIN
234 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
235 $token = $connection->getAccessToken( $_POST['statusnet-pin'] );
236 // ok, now that we have the Access Token, save them in the user config
237 set_pconfig(local_user(),'statusnet', 'oauthtoken', $token['oauth_token']);
238 set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
239 set_pconfig(local_user(),'statusnet', 'post', 1);
240 set_pconfig(local_user(),'statusnet', 'post_taglinks', 1);
241 // reload the Addon Settings page, if we don't do it see Bug #42
242 goaway($a->get_baseurl().'/settings/connectors');
244 // if no PIN is supplied in the POST variables, the user has changed the setting
245 // to post a dent for every new __public__ posting to the wall
246 set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
247 set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
248 set_pconfig(local_user(),'statusnet','post_taglinks',intval($_POST['statusnet-sendtaglinks']));
249 set_pconfig(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
250 set_pconfig(local_user(), 'statusnet', 'intelligent_shortening', intval($_POST['statusnet-shortening']));
251 info( t('StatusNet settings updated.') . EOL);
254 function statusnet_settings(&$a,&$s) {
257 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
259 * 1) Check that we have a base api url and a consumer key & secret
260 * 2) If no OAuthtoken & stuff is present, generate button to get some
261 * allow the user to cancel the connection process at this step
262 * 3) Checkbox for "Send public notices (respect size limitation)
264 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
265 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
266 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
267 $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken' );
268 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
269 $enabled = get_pconfig(local_user(), 'statusnet', 'post');
270 $checked = (($enabled) ? ' checked="checked" ' : '');
271 $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
272 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
273 $linksenabled = get_pconfig(local_user(),'statusnet','post_taglinks');
274 $linkschecked = (($linksenabled) ? ' checked="checked" ' : '');
276 $mirrorenabled = get_pconfig(local_user(),'statusnet','mirror_posts');
277 $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
278 $shorteningenabled = get_pconfig(local_user(),'statusnet','intelligent_shortening');
279 $shorteningchecked = (($shorteningenabled) ? ' checked="checked" ' : '');
281 $s .= '<div class="settings-block">';
282 $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
284 if ( (!$ckey) && (!$csecret) ) {
288 $globalsn = get_config('statusnet', 'sites');
290 * lets check if we have one or more globally configured StatusNet
291 * server OAuth credentials in the configuration. If so offer them
292 * with a little explanation to the user as choice - otherwise
293 * ignore this option entirely.
295 if (! $globalsn == null) {
296 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
297 $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>';
298 $s .= '<div id="statusnet-preconf-wrapper">';
299 foreach ($globalsn as $asn) {
300 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
302 $s .= '<p></p><div class="clear"></div></div>';
303 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
305 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
306 $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>';
307 $s .= '<div id="statusnet-consumer-wrapper">';
308 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
309 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
310 $s .= '<div class="clear"></div>';
311 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
312 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
313 $s .= '<div class="clear"></div>';
314 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
315 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
316 $s .= '<p></p><div class="clear"></div></div>';
317 $s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('StatusNet application name').'</label>';
318 $s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
319 $s .= '<p></p><div class="clear"></div></div>';
320 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
323 * ok we have a consumer key pair now look into the OAuth stuff
325 if ( (!$otoken) && (!$osecret) ) {
327 * the user has not yet connected the account to statusnet
328 * get a temporary OAuth key/secret pair and display a button with
329 * which the user can request a PIN to connect the account to a
330 * account at statusnet
332 $connection = new StatusNetOAuth($api, $ckey, $csecret);
333 $request_token = $connection->getRequestToken('oob');
334 $token = $request_token['oauth_token'];
336 * make some nice form
338 $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>';
339 $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
340 $s .= '<div id="statusnet-pin-wrapper">';
341 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
342 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
343 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
344 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
345 $s .= '</div><div class="clear"></div>';
346 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
347 $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
348 $s .= '<div id="statusnet-cancel-wrapper">';
349 $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
350 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
351 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
352 $s .= '</div><div class="clear"></div>';
353 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
356 * we have an OAuth key / secret pair for the user
357 * so let's give a chance to disable the postings to statusnet
359 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
360 $details = $connection->get('account/verify_credentials');
361 $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>';
362 $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>';
363 if ($a->user['hidewall']) {
364 $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>';
366 $s .= '<div id="statusnet-enable-wrapper">';
367 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
368 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
369 $s .= '<div class="clear"></div>';
370 $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
371 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
372 $s .= '<div class="clear"></div>';
374 $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from statusnet that are no replies or repeated messages').'</label>';
375 $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
376 $s .= '<div class="clear"></div>';
378 $s .= '<label id="statusnet-shortening-label" for="statusnet-shortening">'.t('Shortening method that optimizes the post').'</label>';
379 $s .= '<input id="statusnet-shortening" type="checkbox" name="statusnet-shortening" value="1" '. $shorteningchecked . '/>';
380 $s .= '<div class="clear"></div>';
382 $s .= '<label id="statusnet-sendtaglinks-label" for="statusnet-sendtaglinks">'.t('Send linked #-tags and @-names to StatusNet').'</label>';
383 $s .= '<input id="statusnet-sendtaglinks" type="checkbox" name="statusnet-sendtaglinks" value="1" '. $linkschecked . '/>';
384 $s .= '</div><div class="clear"></div>';
386 $s .= '<div id="statusnet-disconnect-wrapper">';
387 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
388 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
389 $s .= '</div><div class="clear"></div>';
390 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
393 $s .= '</div><div class="clear"></div></div>';
397 function statusnet_post_local(&$a,&$b) {
401 if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
403 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
404 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
406 // if API is used, default to the chosen settings
407 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
408 $statusnet_enable = 1;
410 if(! $statusnet_enable)
413 if(strlen($b['postopts']))
414 $b['postopts'] .= ',';
415 $b['postopts'] .= 'statusnet';
419 if (! function_exists( 'short_link' )) {
420 function short_link($url) {
421 require_once('library/slinky.php');
422 $slinky = new Slinky( $url );
423 $yourls_url = get_config('yourls','url1');
425 $yourls_username = get_config('yourls','username1');
426 $yourls_password = get_config('yourls', 'password1');
427 $yourls_ssl = get_config('yourls', 'ssl1');
428 $yourls = new Slinky_YourLS();
429 $yourls->set( 'username', $yourls_username );
430 $yourls->set( 'password', $yourls_password );
431 $yourls->set( 'ssl', $yourls_ssl );
432 $yourls->set( 'yourls-url', $yourls_url );
433 $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
436 // setup a cascade of shortening services
437 // try to get a short link from these services
438 // in the order ur1.ca, trim, id.gd, tinyurl
439 $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
441 return $slinky->short();
444 function statusnet_shortenmsg($b, $max_char) {
445 require_once("include/bbcode.php");
446 require_once("include/html2plain.php");
448 // Looking for the first image
450 if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
451 $image = $matches[3];
454 if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
455 $image = $matches[1];
457 $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
459 // When saved into the database the content is sent through htmlspecialchars
460 // That means that we have to decode all image-urls
461 $image = htmlspecialchars_decode($image);
464 if ($b["title"] != "")
465 $body = $b["title"]."\n\n".$body;
467 if (strpos($body, "[bookmark") !== false) {
468 // splitting the text in two parts:
469 // before and after the bookmark
470 $pos = strpos($body, "[bookmark");
471 $body1 = substr($body, 0, $pos);
472 $body2 = substr($body, $pos);
474 // Removing all quotes after the bookmark
475 // they are mostly only the content after the bookmark.
476 $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
477 $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
478 $body = $body1.$body2;
481 // Add some newlines so that the message could be cut better
482 $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
483 array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
485 // remove the recycle signs and the names since they aren't helpful on twitter
487 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
488 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
490 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
491 $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
493 // remove the share element
494 //$body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
496 // At first convert the text to html
497 $html = bbcode($body, false, false, 2);
499 // Then convert it to plain text
500 //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
501 $msg = trim(html2plain($html, 0, true));
502 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
504 // Removing multiple newlines
505 while (strpos($msg, "\n\n\n") !== false)
506 $msg = str_replace("\n\n\n", "\n\n", $msg);
508 // Removing multiple spaces
509 while (strpos($msg, " ") !== false)
510 $msg = str_replace(" ", " ", $msg);
515 $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
520 // look for bookmark-bbcode and handle it with priority
521 if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
524 $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
526 // If there is no bookmark element then take the first link
528 $links = collecturls($html);
529 if (sizeof($links) > 0) {
531 $link = current($links);
533 $multiplelinks = (sizeof($links) > 1);
538 $msglink = $b["plink"];
539 else if ($link != "")
541 else if ($multipleimages)
542 $msglink = $b["plink"];
543 else if ($image != "")
546 if (($msglink == "") and strlen($msg) > $max_char)
547 $msglink = $b["plink"];
549 // If the message is short enough then don't modify it. (if the link exists in the original message)
550 if ((strlen(trim($origmsg)) <= $max_char) AND (strpos($origmsg, $msglink) OR ($msglink == "")))
551 return(array("msg"=>trim($origmsg), "image"=>""));
553 // If the message is short enough and contains a picture then post the picture as well
554 if ((strlen(trim($origmsg)) <= ($max_char - 20)) AND strpos($origmsg, $msglink))
555 return(array("msg"=>trim($origmsg), "image"=>$image));
557 // If the message is short enough and the link exists in the original message don't modify it as well
558 if ((strlen(trim($origmsg)) <= $max_char) AND strpos($origmsg, $msglink))
559 return(array("msg"=>trim($origmsg), "image"=>""));
561 // Preserve the unshortened link
562 $orig_link = $msglink;
564 if (strlen($msglink) > 20)
565 $msglink = short_link($msglink);
567 if (strlen(trim($msg." ".$msglink)) > $max_char) {
568 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
569 $lastchar = substr($msg, -1);
570 $msg = substr($msg, 0, -1);
571 $pos = strrpos($msg, "\n");
573 $msg = substr($msg, 0, $pos);
574 else if ($lastchar != "\n")
575 $msg = substr($msg, 0, -3)."...";
577 //$msg = str_replace("\n", " ", $msg);
579 // Removing multiple spaces - again
580 while (strpos($msg, " ") !== false)
581 $msg = str_replace(" ", " ", $msg);
583 //return(array("msg"=>trim($msg."\n".$msglink), "image"=>$image));
585 // Looking if the link points to an image
586 $img_str = fetch_url($orig_link);
588 $tempfile = tempnam(get_config("system","temppath"), "cache");
589 file_put_contents($tempfile, $img_str);
590 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
593 if (($image == $orig_link) OR (substr($mime, 0, 6) == "image/"))
594 return(array("msg"=>trim($msg), "image"=>$orig_link));
595 else if (($image != $orig_link) AND ($image != "") AND (strlen($msg." ".$msglink) <= ($max_char - 20)))
596 return(array("msg"=>trim($msg." ".$msglink)."\n", "image"=>$image));
598 return(array("msg"=>trim($msg." ".$msglink), "image"=>""));
601 function statusnet_post_hook(&$a,&$b) {
607 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
610 if(! strstr($b['postopts'],'statusnet'))
613 if($b['parent'] != $b['id'])
616 // if posts comes from statusnet don't send it back
617 if($b['app'] == "StatusNet")
620 logger('statusnet post invoked');
622 load_pconfig($b['uid'], 'statusnet');
624 $api = get_pconfig($b['uid'], 'statusnet', 'baseapi');
625 $ckey = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
626 $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
627 $otoken = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
628 $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
629 $intelligent_shortening = get_pconfig($b['uid'], 'statusnet', 'intelligent_shortening');
631 // Global setting overrides this
632 if (get_config('statusnet','intelligent_shortening'))
633 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
635 if($ckey && $csecret && $otoken && $osecret) {
637 require_once('include/bbcode.php');
638 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
639 $max_char = $dent->get_maxlength(); // max. length for a dent
640 // we will only work with up to two times the length of the dent
641 // we can later send to StatusNet. This way we can "gain" some
642 // information during shortening of potential links but do not
643 // shorten all the links in a 200000 character long essay.
646 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
647 if (!$intelligent_shortening) {
648 if (! $b['title']=='') {
649 $tmp = $b['title'].": \n".$b['body'];
650 // $tmp = substr($tmp, 0, 4*$max_char);
652 $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
654 // if [url=bla][img]blub.png[/img][/url] get blub.png
655 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
656 // preserve links to images, videos and audios
657 $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
658 $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
659 $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
660 $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
661 $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
662 $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
663 $linksenabled = get_pconfig($b['uid'],'statusnet','post_taglinks');
664 // if a #tag is linked, don't send the [url] over to SN
665 // that is, don't send if the option is not set in the
666 // connector settings
667 if ($linksenabled=='0') {
669 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
671 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
673 $recycle = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8');
674 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
676 $recycle = html_entity_decode("◌ ", ENT_QUOTES, 'UTF-8');
677 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
679 // preserve links to webpages
680 $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
681 $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
682 // find all http or https links in the body of the entry and
683 // apply the shortener if the link is longer then 20 characters
684 if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
685 preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls );
686 foreach ($allurls as $url) {
687 foreach ($url as $u) {
689 $sl = short_link($u);
690 $tmp = str_replace( $u, $sl, $tmp );
695 // ok, all the links we want to send out are save, now strip
696 // away the remaining bbcode
697 //$msg = strip_tags(bbcode($tmp, false, false));
698 $msg = bbcode($tmp, false, false, true);
699 $msg = str_replace(array('<br>','<br />'),"\n",$msg);
700 $msg = strip_tags($msg);
702 // quotes not working - let's try this
703 $msg = html_entity_decode($msg);
705 if (( strlen($msg) > $max_char) && $max_char > 0) {
706 $shortlink = short_link( $b['plink'] );
707 // the new message will be shortened such that "... $shortlink"
708 // will fit into the character limit
709 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
710 $msg = str_replace(array('<br>','<br />'),' ',$msg);
711 $e = explode(' ', $msg);
712 // remove the last word from the cut down message to
713 // avoid sending cut words to the MicroBlog
715 $msg = implode(' ', $e);
716 $msg .= '... ' . $shortlink;
720 $postdata = array('status' => $msg);
722 $msgarr = statusnet_shortenmsg($b, $max_char);
723 $msg = $msgarr["msg"];
724 $image = $msgarr["image"];
726 $img_str = fetch_url($image);
727 $tempfile = tempnam(get_config("system","temppath"), "cache");
728 file_put_contents($tempfile, $img_str);
729 $postdata = array("status" => $msg, "media[]" => $tempfile);
731 $postdata = array("status"=>$msg);
734 // and now dent it :-)
737 // New code that is able to post pictures
738 require_once("addon/statusnet/codebird.php");
739 $cb = \CodebirdSN\CodebirdSN::getInstance();
740 $cb->setAPIEndpoint($api);
741 $cb->setConsumerKey($ckey, $csecret);
742 $cb->setToken($otoken, $osecret);
743 $result = $cb->statuses_update($postdata);
744 //$result = $dent->post('statuses/update', $postdata);
745 logger('statusnet_post send, result: ' . print_r($result, true).
746 "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
747 if ($result->error) {
748 logger('Send to StatusNet failed: "' . $result->error . '"');
756 function statusnet_plugin_admin_post(&$a){
760 foreach($_POST['sitename'] as $id=>$sitename){
761 $sitename=trim($sitename);
762 $apiurl=trim($_POST['apiurl'][$id]);
763 if (! (substr($apiurl, -1)=='/'))
765 $secret=trim($_POST['secret'][$id]);
766 $key=trim($_POST['key'][$id]);
767 $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
772 !x($_POST['delete'][$id])){
775 'sitename' => $sitename,
777 'consumersecret' => $secret,
778 'consumerkey' => $key,
779 'applicationname' => $applicationname
784 $sites = set_config('statusnet','sites', $sites);
788 function statusnet_plugin_admin(&$a, &$o){
790 $sites = get_config('statusnet','sites');
792 if (is_array($sites)){
793 foreach($sites as $id=>$s){
794 $sitesform[] = Array(
795 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
796 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29") ),
797 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
798 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
799 'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
800 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
804 /* empty form to add new site */
806 $sitesform[] = Array(
807 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
808 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29") ),
809 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
810 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
811 'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
814 $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
815 $o = replace_macros($t, array(
816 '$submit' => t('Submit'),
817 '$sites' => $sitesform,
821 function statusnet_cron($a,$b) {
822 $last = get_config('statusnet','last_poll');
824 $poll_interval = intval(get_config('statusnet','poll_interval'));
826 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
829 $next = $last + ($poll_interval * 60);
831 logger('statusnet: poll intervall not reached');
835 logger('statusnet: cron_start');
837 $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
840 logger('statusnet: fetching for user '.$rr['uid']);
841 statusnet_fetchtimeline($a, $rr['uid']);
845 logger('statusnet: cron_end');
847 set_config('statusnet','last_poll', time());
850 function statusnet_fetchtimeline($a, $uid) {
851 $ckey = get_pconfig($uid, 'statusnet', 'consumerkey');
852 $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
853 $api = get_pconfig($uid, 'statusnet', 'baseapi');
854 $otoken = get_pconfig($uid, 'statusnet', 'oauthtoken');
855 $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
856 $lastid = get_pconfig($uid, 'statusnet', 'lastid');
858 // get the application name for the SN app
859 // 1st try personal config, then system config and fallback to the
860 // hostname of the node if neither one is set.
861 $application_name = get_pconfig( $uid, 'statusnet', 'application_name');
862 if ($application_name == "")
863 $application_name = get_config('statusnet', 'application_name');
864 if ($application_name == "")
865 $application_name = $a->get_hostname();
867 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
869 $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
871 $first_time = ($lastid == "");
874 $parameters["since_id"] = $lastid;
876 $items = $connection->get('statuses/user_timeline', $parameters);
878 if (!is_array($items))
881 $posts = array_reverse($items);
884 foreach ($posts as $post) {
885 if ($post->id > $lastid)
891 if ($post->source == "activity")
894 if (is_object($post->retweeted_status))
897 if ($post->in_reply_to_status_id != "")
900 if (!strpos($post->source, $application_name)) {
901 $_SESSION["authenticated"] = true;
902 $_SESSION["uid"] = $uid;
905 $_REQUEST["type"] = "wall";
906 $_REQUEST["api_source"] = true;
907 $_REQUEST["profile_uid"] = $uid;
908 $_REQUEST["source"] = "StatusNet";
910 //$_REQUEST["date"] = $post->created_at;
912 $_REQUEST["title"] = "";
914 $_REQUEST["body"] = $post->text;
915 if (is_string($post->place->name))
916 $_REQUEST["location"] = $post->place->name;
918 if (is_string($post->place->full_name))
919 $_REQUEST["location"] = $post->place->full_name;
921 if (is_array($post->geo->coordinates))
922 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
924 if (is_array($post->coordinates->coordinates))
925 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
927 //print_r($_REQUEST);
928 if ($_REQUEST["body"] != "") {
929 logger('statusnet: posting for user '.$uid);
931 require_once('mod/item.php');
937 set_pconfig($uid, 'statusnet', 'lastid', $lastid);