3 * Name: StatusNet Connector
5 * Author: Tobias Diekershoff <https://diekershoff.homeunix.net/friendika/profile/tobias>
8 /* StatusNet Plugin for Friendika
10 * Author: Tobias Diekershoff
11 * tobias.diekershoff@gmx.net
13 * License:3-clause BSD license
16 * To activate the plugin itself add it to the $a->config['system']['addon']
17 * setting. After this, your user can configure their Twitter account settings
18 * from "Settings -> Plugin Settings".
20 * Requirements: PHP5, curl [Slinky library]
22 * Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/StatusNet_Plugin
27 * - what about multimedia content?
28 * so far we just strip HTML tags from the message
33 * We have to alter the TwitterOAuth class a little bit to work with any StatusNet
34 * installation abroad. Basically it's only make the API path variable and be happy.
36 * Thank you guys for the Twitter compatible API!
39 require_once('library/twitteroauth.php');
41 class StatusNetOAuth extends TwitterOAuth {
42 function get_maxlength() {
43 $config = $this->get($this->host . 'statusnet/config.json');
44 return $config->site->textlimit;
46 function accessTokenURL() { return $this->host.'oauth/access_token'; }
47 function authenticateURL() { return $this->host.'oauth/authenticate'; }
48 function authorizeURL() { return $this->host.'oauth/authorize'; }
49 function requestTokenURL() { return $this->host.'oauth/request_token'; }
50 function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
51 parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
52 $this->host = $apipath;
55 * Make an HTTP request
59 * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendika
61 function http($url, $method, $postfields = NULL) {
62 $this->http_info = array();
65 $prx = get_config('system','proxy');
66 logger('Proxy SN: '.$prx);
68 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
69 curl_setopt($ci, CURLOPT_PROXY, $prx);
70 $prxusr = get_config('system','proxyuser');
72 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
74 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
75 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
76 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
77 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
78 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
79 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
80 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
81 curl_setopt($ci, CURLOPT_HEADER, FALSE);
85 curl_setopt($ci, CURLOPT_POST, TRUE);
86 if (!empty($postfields)) {
87 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
91 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
92 if (!empty($postfields)) {
93 $url = "{$url}?{$postfields}";
97 curl_setopt($ci, CURLOPT_URL, $url);
98 $response = curl_exec($ci);
99 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
100 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
107 function statusnet_install() {
108 // we need some hooks, for the configuration and for sending tweets
109 register_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
110 register_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
111 register_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
112 register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
113 logger("installed statusnet");
117 function statusnet_uninstall() {
118 unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
119 unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
120 unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
121 unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
124 function statusnet_jot_nets(&$a,&$b) {
128 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
129 if(intval($statusnet_post) == 1) {
130 $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default');
131 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
132 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . 'value="1" /> '
133 . t('Post to StatusNet') . '</div>';
140 function statusnet_settings_post ($a,$post) {
143 // don't check statusnet settings if statusnet submit button is not clicked
144 if (!x($_POST,'statusnet-submit')) return;
146 if (isset($_POST['statusnet-disconnect'])) {
148 * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
149 * TODO can we revoke the access tokens at Twitter and do we need to do so?
151 del_pconfig( local_user(), 'statusnet', 'consumerkey' );
152 del_pconfig( local_user(), 'statusnet', 'consumersecret' );
153 del_pconfig( local_user(), 'statusnet', 'post' );
154 del_pconfig( local_user(), 'statusnet', 'post_by_default' );
155 del_pconfig( local_user(), 'statusnet', 'oauthtoken' );
156 del_pconfig( local_user(), 'statusnet', 'oauthsecret' );
157 del_pconfig( local_user(), 'statusnet', 'baseapi' );
159 if (isset($_POST['statusnet-preconf-apiurl'])) {
161 * If the user used one of the preconfigured StatusNet server credentials
162 * use them. All the data are available in the global config.
163 * Check the API Url never the less and blame the admin if it's not working ^^
165 $globalsn = get_config('statusnet', 'sites');
166 foreach ( $globalsn as $asn) {
167 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
168 $apibase = $asn['apiurl'];
169 $c = fetch_url( $apibase . 'statusnet/version.xml' );
170 if (strlen($c) > 0) {
171 set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
172 set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
173 set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
175 notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
179 goaway($a->get_baseurl().'/settings/addon');
181 if (isset($_POST['statusnet-consumersecret'])) {
182 // check if we can reach the API of the StatusNet server
183 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
184 // resign quickly after this one try to fix the path ;-)
185 $apibase = $_POST['statusnet-baseapi'];
186 $c = fetch_url( $apibase . 'statusnet/version.xml' );
187 if (strlen($c) > 0) {
188 // ok the API path is correct, let's save the settings
189 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
190 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
191 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
193 // the API path is not correct, maybe missing trailing / ?
194 $apibase = $apibase . '/';
195 $c = fetch_url( $apibase . 'statusnet/version.xml' );
196 if (strlen($c) > 0) {
197 // ok the API path is now correct, let's save the settings
198 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
199 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
200 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
202 // still not the correct API base, let's do noting
203 notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
206 goaway($a->get_baseurl().'/settings/addon');
208 if (isset($_POST['statusnet-pin'])) {
209 // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
210 logger('got a StatusNet security code');
211 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
212 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
213 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
214 // the token and secret for which the PIN was generated were hidden in the settings
215 // form as token and token2, we need a new connection to Twitter using these token
216 // and secret to request a Access Token with the PIN
217 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
218 $token = $connection->getAccessToken( $_POST['statusnet-pin'] );
219 // ok, now that we have the Access Token, save them in the user config
220 set_pconfig(local_user(),'statusnet', 'oauthtoken', $token['oauth_token']);
221 set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
222 set_pconfig(local_user(),'statusnet', 'post', 1);
223 // reload the Addon Settings page, if we don't do it see Bug #42
224 goaway($a->get_baseurl().'/settings/addon');
226 // if no PIN is supplied in the POST variables, the user has changed the setting
227 // to post a tweet for every new __public__ posting to the wall
228 set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
229 set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
230 info( t('StatusNet settings updated.') . EOL);
233 function statusnet_settings(&$a,&$s) {
236 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
238 * 1) Check that we have a base api url and a consumer key & secret
239 * 2) If no OAuthtoken & stuff is present, generate button to get some
240 * allow the user to cancel the connection process at this step
241 * 3) Checkbox for "Send public notices (respect size limitation)
243 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
244 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
245 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
246 $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken' );
247 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
248 $enabled = get_pconfig(local_user(), 'statusnet', 'post');
249 $checked = (($enabled) ? ' checked="checked" ' : '');
250 $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
251 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
252 $s .= '<div class="settings-block">';
253 $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
255 if ( (!$ckey) && (!$csecret) ) {
259 $globalsn = get_config('statusnet', 'sites');
261 * lets check if we have one or more globally configured StatusNet
262 * server OAuth credentials in the configuration. If so offer them
263 * with a little explanation to the user as choice - otherwise
264 * ignore this option entirely.
266 if (! $globalsn == null) {
267 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
268 $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>';
269 $s .= '<div id="statusnet-preconf-wrapper">';
270 foreach ($globalsn as $asn) {
271 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
273 $s .= '<p></p><div class="clear"></div></div>';
274 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
276 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
277 $s .= '<p>'. t('No consumer key pair for StatusNet found. Register your Friendika 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 Friendika installation at your favorited StatusNet installation.') .'</p>';
278 $s .= '<div id="statusnet-consumer-wrapper">';
279 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
280 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
281 $s .= '<div class="clear"></div>';
282 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
283 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
284 $s .= '<div class="clear"></div>';
285 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
286 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
287 $s .= '<p></p><div class="clear"></div></div>';
288 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
291 * ok we have a consumer key pair now look into the OAuth stuff
293 if ( (!$otoken) && (!$osecret) ) {
295 * the user has not yet connected the account to statusnet
296 * get a temporary OAuth key/secret pair and display a button with
297 * which the user can request a PIN to connect the account to a
298 * account at statusnet
300 $connection = new StatusNetOAuth($api, $ckey, $csecret);
301 $request_token = $connection->getRequestToken('oob');
302 $token = $request_token['oauth_token'];
304 * make some nice form
306 $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>';
307 $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
308 $s .= '<div id="statusnet-pin-wrapper">';
309 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
310 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
311 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
312 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
313 $s .= '</div><div class="clear"></div>';
314 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
315 $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
316 $s .= '<div id="statusnet-cancel-wrapper">';
317 $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
318 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
319 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
320 $s .= '</div><div class="clear"></div>';
321 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
324 * we have an OAuth key / secret pair for the user
325 * so let's give a chance to disable the postings to statusnet
327 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
328 $details = $connection->get('account/verify_credentials');
329 $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>';
330 $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>';
331 $s .= '<div id="statusnet-enable-wrapper">';
332 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
333 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
334 $s .= '<div class="clear"></div>';
335 $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
336 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
337 $s .= '</div><div class="clear"></div>';
339 $s .= '<div id="statusnet-disconnect-wrapper">';
340 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
341 $s .= '<input id="statusnet-disconnect" 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 $s .= '</div><div class="clear"></div></div>';
350 function statusnet_post_hook(&$a,&$b) {
356 logger('StatusNet post invoked');
358 if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (!$b['parent']) ) {
360 // Status.Net is not considered a private network
364 load_pconfig(local_user(), 'statusnet');
366 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
367 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
368 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
369 $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken' );
370 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
372 if($ckey && $csecret && $otoken && $osecret) {
374 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
375 $statusnet_enable = (($statusnet_post && x($_POST,'statusnet_enable')) ? intval($_POST['statusnet_enable']) : 0);
376 // if API is used, default to the chosen settings
377 if($_POST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
378 $statusnet_enable = 1;
380 if($statusnet_enable && $statusnet_post) {
381 require_once('include/bbcode.php');
382 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
383 $max_char = $dent->get_maxlength(); // max. length for a dent
384 $msg = strip_tags(bbcode($b['body']));
385 if ( strlen($msg) > $max_char) {
387 require_once('library/slinky.php');
388 // post url = base url + /display/ + owner + post id
389 // we construct this from the Owner link and replace
390 // profile by display - this will cause an error when
391 // /profile/ is in the owner url twice but I don't
392 // think this will be very common...
393 $posturl = str_replace('/profile/','/display/',$b['owner-link']).'/'.$b['id'];
394 $slinky = new Slinky( $posturl );
395 // setup a cascade of shortening services
396 // try to get a short link from these services
397 // in the order ur1.ca, trim, id.gd, tinyurl
398 $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
399 $shortlink = $slinky->short();
400 // the new message will be shortened such that "... $shortlink"
401 // will fit into the character limit
402 $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
403 $msg .= '... ' . $shortlink;
405 // and now tweet it :-)
407 $dent->post('statuses/update', array('status' => $msg));
413 function statusnet_plugin_admin_post(&$a){
417 foreach($_POST['sitename'] as $id=>$sitename){
418 $sitename=trim($sitename);
419 $apiurl=trim($_POST['apiurl'][$id]);
420 $secret=trim($_POST['secret'][$id]);
421 $key=trim($_POST['key'][$id]);
426 !x($_POST['delete'][$id])){
429 'sitename' => $sitename,
431 'consumersecret' => $secret,
432 'consumerkey' => $key
437 $sites = set_config('statusnet','sites', $sites);
441 function statusnet_plugin_admin(&$a, &$o){
443 $sites = get_config('statusnet','sites');
445 if (is_array($sites)){
446 foreach($sites as $id=>$s){
447 $sitesform[] = Array(
448 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
449 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
450 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
451 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
452 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
456 /* empty form to add new site */
458 $sitesform[] = Array(
459 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
460 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
461 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
462 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
466 $t = file_get_contents( dirname(__file__). "/admin.tpl" );
467 $o = replace_macros($t, array(
468 '$submit' => t('Submit'),
470 '$sites' => $sitesform,