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 = 'http://localhost:8118';
66 $prx = get_config('system','proxy');
67 logger('Proxy SN: '.$prx);
69 curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
70 curl_setopt($ci, CURLOPT_PROXY, $prx);
71 $prxusr = get_config('system','proxyuser');
73 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
75 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
76 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
77 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
78 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
79 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
80 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
81 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
82 curl_setopt($ci, CURLOPT_HEADER, FALSE);
86 curl_setopt($ci, CURLOPT_POST, TRUE);
87 if (!empty($postfields)) {
88 curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
92 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
93 if (!empty($postfields)) {
94 $url = "{$url}?{$postfields}";
98 curl_setopt($ci, CURLOPT_URL, $url);
99 $response = curl_exec($ci);
100 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
101 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
108 function statusnet_install() {
109 // we need some hooks, for the configuration and for sending tweets
110 register_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
111 register_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
112 register_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
113 register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
114 logger("installed statusnet");
118 function statusnet_uninstall() {
119 unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
120 unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
121 unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
122 unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
125 function statusnet_jot_nets(&$a,&$b) {
129 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
130 if(intval($statusnet_post) == 1) {
131 $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default');
132 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
133 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . 'value="1" /> '
134 . t('Post to StatusNet') . '</div>';
141 function statusnet_settings_post ($a,$post) {
144 // don't check statusnet settings if statusnet submit button is not clicked
145 if (!x($_POST,'statusnet-submit')) return;
147 if (isset($_POST['statusnet-disconnect'])) {
149 * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
150 * TODO can we revoke the access tokens at Twitter and do we need to do so?
152 del_pconfig( local_user(), 'statusnet', 'consumerkey' );
153 del_pconfig( local_user(), 'statusnet', 'consumersecret' );
154 del_pconfig( local_user(), 'statusnet', 'post' );
155 del_pconfig( local_user(), 'statusnet', 'post_by_default' );
156 del_pconfig( local_user(), 'statusnet', 'oauthtoken' );
157 del_pconfig( local_user(), 'statusnet', 'oauthsecret' );
158 del_pconfig( local_user(), 'statusnet', 'baseapi' );
160 if (isset($_POST['statusnet-preconf-apiurl'])) {
162 * If the user used one of the preconfigured StatusNet server credentials
163 * use them. All the data are available in the global config.
164 * Check the API Url never the less and blame the admin if it's not working ^^
166 $globalsn = get_config('statusnet', 'sites');
167 foreach ( $globalsn as $asn) {
168 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
169 $apibase = $asn['apiurl'];
170 $c = fetch_url( $apibase . 'statusnet/version.xml' );
171 if (strlen($c) > 0) {
172 set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
173 set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
174 set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
176 notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
180 goaway($a->get_baseurl().'/settings/addon');
182 if (isset($_POST['statusnet-consumersecret'])) {
183 // check if we can reach the API of the StatusNet server
184 // we'll check the API Version for that, if we don't get one we'll try to fix the path but will
185 // resign quickly after this one try to fix the path ;-)
186 $apibase = $_POST['statusnet-baseapi'];
187 $c = fetch_url( $apibase . 'statusnet/version.xml' );
188 if (strlen($c) > 0) {
189 // ok the API path is correct, let's save the settings
190 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
191 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
192 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
194 // the API path is not correct, maybe missing trailing / ?
195 $apibase = $apibase . '/';
196 $c = fetch_url( $apibase . 'statusnet/version.xml' );
197 if (strlen($c) > 0) {
198 // ok the API path is now correct, let's save the settings
199 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
200 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
201 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
203 // still not the correct API base, let's do noting
204 notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
207 goaway($a->get_baseurl().'/settings/addon');
209 if (isset($_POST['statusnet-pin'])) {
210 // if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
211 logger('got a StatusNet security code');
212 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
213 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
214 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
215 // the token and secret for which the PIN was generated were hidden in the settings
216 // form as token and token2, we need a new connection to Twitter using these token
217 // and secret to request a Access Token with the PIN
218 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
219 $token = $connection->getAccessToken( $_POST['statusnet-pin'] );
220 // ok, now that we have the Access Token, save them in the user config
221 set_pconfig(local_user(),'statusnet', 'oauthtoken', $token['oauth_token']);
222 set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
223 set_pconfig(local_user(),'statusnet', 'post', 1);
224 // reload the Addon Settings page, if we don't do it see Bug #42
225 goaway($a->get_baseurl().'/settings/addon');
227 // if no PIN is supplied in the POST variables, the user has changed the setting
228 // to post a tweet for every new __public__ posting to the wall
229 set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
230 set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
231 info( t('StatusNet settings updated.') . EOL);
234 function statusnet_settings(&$a,&$s) {
237 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
239 * 1) Check that we have a base api url and a consumer key & secret
240 * 2) If no OAuthtoken & stuff is present, generate button to get some
241 * allow the user to cancel the connection process at this step
242 * 3) Checkbox for "Send public notices (respect size limitation)
244 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
245 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
246 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
247 $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken' );
248 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
249 $enabled = get_pconfig(local_user(), 'statusnet', 'post');
250 $checked = (($enabled) ? ' checked="checked" ' : '');
251 $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
252 $defchecked = (($defenabled) ? ' checked="checked" ' : '');
253 $s .= '<div class="settings-block">';
254 $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
256 if ( (!$ckey) && (!$csecret) ) {
260 $globalsn = get_config('statusnet', 'sites');
262 * lets check if we have one or more globally configured StatusNet
263 * server OAuth credentials in the configuration. If so offer them
264 * with a little explanation to the user as choice - otherwise
265 * ignore this option entirely.
267 if (! $globalsn == null) {
268 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
269 $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>';
270 $s .= '<div id="statusnet-preconf-wrapper">';
271 foreach ($globalsn as $asn) {
272 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
274 $s .= '<p></p><div class="clear"></div></div>';
275 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
277 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
278 $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>';
279 $s .= '<div id="statusnet-consumer-wrapper">';
280 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
281 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
282 $s .= '<div class="clear"></div>';
283 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
284 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
285 $s .= '<div class="clear"></div>';
286 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
287 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
288 $s .= '<p></p><div class="clear"></div></div>';
289 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
292 * ok we have a consumer key pair now look into the OAuth stuff
294 if ( (!$otoken) && (!$osecret) ) {
296 * the user has not yet connected the account to statusnet
297 * get a temporary OAuth key/secret pair and display a button with
298 * which the user can request a PIN to connect the account to a
299 * account at statusnet
301 $connection = new StatusNetOAuth($api, $ckey, $csecret);
302 $request_token = $connection->getRequestToken('oob');
303 $token = $request_token['oauth_token'];
305 * make some nice form
307 $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>';
308 $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
309 $s .= '<div id="statusnet-pin-wrapper">';
310 $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
311 $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
312 $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
313 $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
314 $s .= '</div><div class="clear"></div>';
315 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
316 $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
317 $s .= '<div id="statusnet-cancel-wrapper">';
318 $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
319 $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
320 $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
321 $s .= '</div><div class="clear"></div>';
322 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
325 * we have an OAuth key / secret pair for the user
326 * so let's give a chance to disable the postings to statusnet
328 $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
329 $details = $connection->get('account/verify_credentials');
330 $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>';
331 $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>';
332 $s .= '<div id="statusnet-enable-wrapper">';
333 $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
334 $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
335 $s .= '<div class="clear"></div>';
336 $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
337 $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
338 $s .= '</div><div class="clear"></div>';
340 $s .= '<div id="statusnet-disconnect-wrapper">';
341 $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
342 $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
343 $s .= '</div><div class="clear"></div>';
344 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
347 $s .= '</div><div class="clear"></div></div>';
351 function statusnet_post_hook(&$a,&$b) {
357 logger('StatusNet post invoked');
359 if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (!$b['parent']) ) {
361 // Status.Net is not considered a private network
365 load_pconfig(local_user(), 'statusnet');
367 $api = get_pconfig(local_user(), 'statusnet', 'baseapi');
368 $ckey = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
369 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
370 $otoken = get_pconfig(local_user(), 'statusnet', 'oauthtoken' );
371 $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
373 if($ckey && $csecret && $otoken && $osecret) {
375 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
376 $statusnet_enable = (($statusnet_post && x($_POST,'statusnet_enable')) ? intval($_POST['statusnet_enable']) : 0);
378 if($statusnet_enable && $statusnet_post) {
379 require_once('include/bbcode.php');
380 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
381 $max_char = $dent->get_maxlength(); // max. length for a dent
382 $msg = strip_tags(bbcode($b['body']));
383 if ( strlen($msg) > $max_char) {
385 require_once('library/slinky.php');
386 // post url = base url + /display/ + owner + post id
387 // we construct this from the Owner link and replace
388 // profile by display - this will cause an error when
389 // /profile/ is in the owner url twice but I don't
390 // think this will be very common...
391 $posturl = str_replace('/profile/','/display/',$b['owner-link']).'/'.$b['id'];
392 $slinky = new Slinky( $posturl );
393 // setup a cascade of shortening services
394 // try to get a short link from these services
395 // in the order ur1.ca, trim, id.gd, tinyurl
396 $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
397 $shortlink = $slinky->short();
398 // the new message will be shortened such that "... $shortlink"
399 // will fit into the character limit
400 $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
401 $msg .= '... ' . $shortlink;
403 // and now tweet it :-)
405 $dent->post('statuses/update', array('status' => $msg));
411 function statusnet_plugin_admin_post(&$a){
415 foreach($_POST['sitename'] as $id=>$sitename){
416 $sitename=trim($sitename);
417 $apiurl=trim($_POST['apiurl'][$id]);
418 $secret=trim($_POST['secret'][$id]);
419 $key=trim($_POST['key'][$id]);
424 !x($_POST['delete'][$id])){
427 'sitename' => $sitename,
429 'consumersecret' => $secret,
430 'consumerkey' => $key
435 $sites = set_config('statusnet','sites', $sites);
439 function statusnet_plugin_admin(&$a, &$o){
441 $sites = get_config('statusnet','sites');
443 if (is_array($sites)){
444 foreach($sites as $id=>$s){
445 $sitesform[] = Array(
446 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
447 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
448 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
449 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
450 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
454 /* empty form to add new site */
456 $sitesform[] = Array(
457 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
458 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
459 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
460 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
464 $t = file_get_contents( dirname(__file__). "/admin.tpl" );
465 $o = replace_macros($t, array(
466 '$submit' => t('Submit'),
468 '$sites' => $sitesform,