]> git.mxchange.org Git - friendica-addons.git/blob - statusnet/statusnet.php
fbpost: Now you can mirror public facebook posts from your wall to friendica
[friendica-addons.git] / statusnet / statusnet.php
1 <?php
2 /**
3  * Name: StatusNet Connector
4  * Description: Relay public postings to a connected StatusNet account
5  * Version: 1.0.5
6  * Author: Tobias Diekershoff <http://diekershoff.homeunix.net/friendika/profile/tobias>
7  */
8  
9 /*   StatusNet Plugin for Friendica
10  *
11  *   Author: Tobias Diekershoff
12  *           tobias.diekershoff@gmx.net
13  *
14  *   License:3-clause BSD license
15  *
16  *   Configuration:
17  *     To activate the plugin itself add it to the $a->config['system']['addon']
18  *     setting. After this, your user can configure their Twitter account settings
19  *     from "Settings -> Plugin Settings".
20  *
21  *     Requirements: PHP5, curl [Slinky library]
22  *
23  *     Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/StatusNet_Plugin
24  */
25
26 /***
27  * We have to alter the TwitterOAuth class a little bit to work with any StatusNet
28  * installation abroad. Basically it's only make the API path variable and be happy.
29  *
30  * Thank you guys for the Twitter compatible API!
31  */
32
33 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
34
35 require_once('library/twitteroauth.php');
36
37 class StatusNetOAuth extends TwitterOAuth {
38     function get_maxlength() {
39         $config = $this->get($this->host . 'statusnet/config.json');
40         return $config->site->textlimit;
41     }
42     function accessTokenURL()  { return $this->host.'oauth/access_token'; }
43     function authenticateURL() { return $this->host.'oauth/authenticate'; } 
44     function authorizeURL() { return $this->host.'oauth/authorize'; }
45     function requestTokenURL() { return $this->host.'oauth/request_token'; }
46     function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
47         parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
48         $this->host = $apipath;
49     }
50   /**
51    * Make an HTTP request
52    *
53    * @return API results
54    *
55    * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
56    */
57   function http($url, $method, $postfields = NULL) {
58     $this->http_info = array();
59     $ci = curl_init();
60     /* Curl settings */
61     $prx = get_config('system','proxy');
62     if(strlen($prx)) {
63         curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
64         curl_setopt($ci, CURLOPT_PROXY, $prx);
65         $prxusr = get_config('system','proxyuser');
66         if(strlen($prxusr))
67             curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
68     }
69     curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
70     curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
71     curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
72     curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
73     curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
74     curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
75     curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
76     curl_setopt($ci, CURLOPT_HEADER, FALSE);
77
78     switch ($method) {
79       case 'POST':
80         curl_setopt($ci, CURLOPT_POST, TRUE);
81         if (!empty($postfields)) {
82           curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
83         }
84         break;
85       case 'DELETE':
86         curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
87         if (!empty($postfields)) {
88           $url = "{$url}?{$postfields}";
89         }
90     }
91
92     curl_setopt($ci, CURLOPT_URL, $url);
93     $response = curl_exec($ci);
94     $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
95     $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
96     $this->url = $url;
97     curl_close ($ci);
98     return $response;
99   }
100 }
101
102 function statusnet_install() {
103         //  we need some hooks, for the configuration and for sending tweets
104         register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
105         register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
106         register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
107         register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
108         register_hook('jot_networks',    'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
109         register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
110         logger("installed statusnet");
111 }
112
113
114 function statusnet_uninstall() {
115         unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
116         unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
117         unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
118         unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
119         unregister_hook('jot_networks',    'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
120         unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
121
122         // old setting - remove only
123         unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
124         unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
125         unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
126
127 }
128
129 function statusnet_jot_nets(&$a,&$b) {
130         if(! local_user())
131                 return;
132
133         $statusnet_post = get_pconfig(local_user(),'statusnet','post');
134         if(intval($statusnet_post) == 1) {
135                 $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default');
136                 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
137                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> ' 
138                         . t('Post to StatusNet') . '</div>';
139         }
140 }
141
142 function statusnet_settings_post ($a,$post) {
143         if(! local_user())
144             return;
145         // don't check statusnet settings if statusnet submit button is not clicked
146         if (!x($_POST,'statusnet-submit')) return;
147         
148         if (isset($_POST['statusnet-disconnect'])) {
149             /***
150              * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
151              */
152             del_pconfig(local_user(), 'statusnet', 'consumerkey');
153             del_pconfig(local_user(), 'statusnet', 'consumersecret');
154             del_pconfig(local_user(), 'statusnet', 'post');
155             del_pconfig(local_user(), 'statusnet', 'post_by_default');
156             del_pconfig(local_user(), 'statusnet', 'oauthtoken');
157             del_pconfig(local_user(), 'statusnet', 'oauthsecret');
158             del_pconfig(local_user(), 'statusnet', 'baseapi');
159             del_pconfig(local_user(), 'statusnet', 'post_taglinks');
160             del_pconfig(local_user(), 'statusnet', 'lastid');
161             del_pconfig(local_user(), 'statusnet', 'mirror_posts');
162             del_pconfig(local_user(), 'statusnet', 'intelligent_shortening');
163         } else {
164             if (isset($_POST['statusnet-preconf-apiurl'])) {
165                 /***
166                  * If the user used one of the preconfigured StatusNet server credentials
167                  * use them. All the data are available in the global config.
168                  * Check the API Url never the less and blame the admin if it's not working ^^
169                  */
170                 $globalsn = get_config('statusnet', 'sites');
171                 foreach ( $globalsn as $asn) {
172                     if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
173                         $apibase = $asn['apiurl'];
174                         $c = fetch_url( $apibase . 'statusnet/version.xml' );
175                         if (strlen($c) > 0) {
176                             set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
177                             set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
178                             set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
179                         } else {
180                             notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
181                         }
182                     }
183                 }
184                 goaway($a->get_baseurl().'/settings/connectors');
185             } else {
186             if (isset($_POST['statusnet-consumersecret'])) {
187                 //  check if we can reach the API of the StatusNet server
188                 //  we'll check the API Version for that, if we don't get one we'll try to fix the path but will
189                 //  resign quickly after this one try to fix the path ;-)
190                 $apibase = $_POST['statusnet-baseapi'];
191                 $c = fetch_url( $apibase . 'statusnet/version.xml' );
192                 if (strlen($c) > 0) {
193                     //  ok the API path is correct, let's save the settings
194                     set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
195                     set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
196                     set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
197                 } else {
198                     //  the API path is not correct, maybe missing trailing / ?
199                     $apibase = $apibase . '/';
200                     $c = fetch_url( $apibase . 'statusnet/version.xml' );
201                     if (strlen($c) > 0) {
202                         //  ok the API path is now correct, let's save the settings
203                         set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
204                         set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
205                         set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
206                     } else {
207                         //  still not the correct API base, let's do noting
208                         notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
209                     }
210                 }
211                 goaway($a->get_baseurl().'/settings/connectors');
212             } else {
213                 if (isset($_POST['statusnet-pin'])) {
214                         //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
215                     $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
216                                         $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey'  );
217                                         $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
218                                         //  the token and secret for which the PIN was generated were hidden in the settings
219                                         //  form as token and token2, we need a new connection to Twitter using these token
220                                         //  and secret to request a Access Token with the PIN
221                                         $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
222                                         $token   = $connection->getAccessToken( $_POST['statusnet-pin'] );
223                                         //  ok, now that we have the Access Token, save them in the user config
224                                         set_pconfig(local_user(),'statusnet', 'oauthtoken',  $token['oauth_token']);
225                                         set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
226                                         set_pconfig(local_user(),'statusnet', 'post', 1);
227                                         set_pconfig(local_user(),'statusnet', 'post_taglinks', 1);
228                     //  reload the Addon Settings page, if we don't do it see Bug #42
229                     goaway($a->get_baseurl().'/settings/connectors');
230                                 } else {
231                                         //  if no PIN is supplied in the POST variables, the user has changed the setting
232                                         //  to post a dent for every new __public__ posting to the wall
233                                         set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
234                                         set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
235                                         set_pconfig(local_user(),'statusnet','post_taglinks',intval($_POST['statusnet-sendtaglinks']));
236                                         set_pconfig(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
237                                         set_pconfig(local_user(), 'statusnet', 'intelligent_shortening', intval($_POST['statusnet-shortening']));
238                                         info( t('StatusNet settings updated.') . EOL);
239                 }}}}
240 }
241 function statusnet_settings(&$a,&$s) {
242         if(! local_user())
243                 return;
244         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
245         /***
246          * 1) Check that we have a base api url and a consumer key & secret
247          * 2) If no OAuthtoken & stuff is present, generate button to get some
248          *    allow the user to cancel the connection process at this step
249          * 3) Checkbox for "Send public notices (respect size limitation)
250          */
251         $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
252         $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
253         $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
254         $otoken  = get_pconfig(local_user(), 'statusnet', 'oauthtoken'  );
255         $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
256         $enabled = get_pconfig(local_user(), 'statusnet', 'post');
257         $checked = (($enabled) ? ' checked="checked" ' : '');
258         $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
259         $defchecked = (($defenabled) ? ' checked="checked" ' : '');
260         $linksenabled = get_pconfig(local_user(),'statusnet','post_taglinks');
261         $linkschecked = (($linksenabled) ? ' checked="checked" ' : '');
262
263         $mirrorenabled = get_pconfig(local_user(),'statusnet','mirror_posts');
264         $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
265         $shorteningenabled = get_pconfig(local_user(),'statusnet','intelligent_shortening');
266         $shorteningchecked = (($shorteningenabled) ? ' checked="checked" ' : '');
267
268         $s .= '<div class="settings-block">';
269         $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
270
271         if ( (!$ckey) && (!$csecret) ) {
272                 /***
273                  * no consumer keys
274                  */
275             $globalsn = get_config('statusnet', 'sites');
276             /***
277              * lets check if we have one or more globally configured StatusNet
278              * server OAuth credentials in the configuration. If so offer them
279              * with a little explanation to the user as choice - otherwise
280              * ignore this option entirely.
281              */
282             if (! $globalsn == null) {
283                 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
284                 $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>';
285                 $s .= '<div id="statusnet-preconf-wrapper">';
286                 foreach ($globalsn as $asn) {
287                     $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
288                 }
289                 $s .= '<p></p><div class="clear"></div></div>';
290                 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
291             }
292             $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
293             $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>';
294             $s .= '<div id="statusnet-consumer-wrapper">';
295             $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
296             $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
297             $s .= '<div class="clear"></div>';
298             $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
299             $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
300             $s .= '<div class="clear"></div>';
301             $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
302             $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
303             $s .= '<p></p><div class="clear"></div></div>';
304             $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
305         } else {
306                 /***
307                  * ok we have a consumer key pair now look into the OAuth stuff
308                  */
309                 if ( (!$otoken) && (!$osecret) ) {
310                         /***
311                          * the user has not yet connected the account to statusnet
312                          * get a temporary OAuth key/secret pair and display a button with
313                          * which the user can request a PIN to connect the account to a
314                          * account at statusnet
315                          */
316                         $connection = new StatusNetOAuth($api, $ckey, $csecret);
317                         $request_token = $connection->getRequestToken('oob');
318                         $token = $request_token['oauth_token'];
319                         /***
320                          *  make some nice form
321                          */
322                         $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>';
323                         $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
324                         $s .= '<div id="statusnet-pin-wrapper">';
325                         $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
326                         $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
327                         $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
328                         $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
329                         $s .= '</div><div class="clear"></div>';
330                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
331                         $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
332                         $s .= '<div id="statusnet-cancel-wrapper">';
333                         $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
334                         $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
335                         $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
336                         $s .= '</div><div class="clear"></div>';
337                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
338                 } else {
339                         /***
340                          *  we have an OAuth key / secret pair for the user
341                          *  so let's give a chance to disable the postings to statusnet
342                          */
343                         $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
344                         $details = $connection->get('account/verify_credentials');
345                         $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>';
346                         $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>';
347                         if ($a->user['hidewall']) {
348                             $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>';
349                         }
350                         $s .= '<div id="statusnet-enable-wrapper">';
351                         $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
352                         $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
353                         $s .= '<div class="clear"></div>';
354                         $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
355                         $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
356                         $s .= '<div class="clear"></div>';
357
358                         $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from statusnet that are no replies or repeated messages').'</label>';
359                         $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
360                         $s .= '<div class="clear"></div>';
361
362                         $s .= '<label id="statusnet-shortening-label" for="statusnet-shortening">'.t('Shortening method that optimizes the post').'</label>';
363                         $s .= '<input id="statusnet-shortening" type="checkbox" name="statusnet-shortening" value="1" '. $shorteningchecked . '/>';
364                         $s .= '<div class="clear"></div>';
365
366                         $s .= '<label id="statusnet-sendtaglinks-label" for="statusnet-sendtaglinks">'.t('Send linked #-tags and @-names to StatusNet').'</label>';
367                         $s .= '<input id="statusnet-sendtaglinks" type="checkbox" name="statusnet-sendtaglinks" value="1" '. $linkschecked . '/>';
368                         $s .= '</div><div class="clear"></div>';
369
370                         $s .= '<div id="statusnet-disconnect-wrapper">';
371                         $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
372                         $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
373                         $s .= '</div><div class="clear"></div>';
374                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
375                 }
376         }
377         $s .= '</div><div class="clear"></div></div>';
378 }
379
380
381 function statusnet_post_local(&$a,&$b) {
382         if($b['edit'])
383                 return;
384
385         if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
386
387                 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
388                 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
389
390                 // if API is used, default to the chosen settings
391                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
392                         $statusnet_enable = 1;
393
394        if(! $statusnet_enable)
395             return;
396
397        if(strlen($b['postopts']))
398            $b['postopts'] .= ',';
399        $b['postopts'] .= 'statusnet';
400     }
401 }
402
403 if (! function_exists( 'short_link' )) {
404 function short_link($url) {
405     require_once('library/slinky.php');
406     $slinky = new Slinky( $url );
407     $yourls_url = get_config('yourls','url1');
408     if ($yourls_url) {
409             $yourls_username = get_config('yourls','username1');
410             $yourls_password = get_config('yourls', 'password1');
411             $yourls_ssl = get_config('yourls', 'ssl1');
412             $yourls = new Slinky_YourLS();
413             $yourls->set( 'username', $yourls_username );
414             $yourls->set( 'password', $yourls_password );
415             $yourls->set( 'ssl', $yourls_ssl );
416             $yourls->set( 'yourls-url', $yourls_url );
417             $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
418     }
419     else {
420             // setup a cascade of shortening services
421             // try to get a short link from these services
422             // in the order ur1.ca, trim, id.gd, tinyurl
423             $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
424     }
425     return $slinky->short();
426 } };
427
428 function statusnet_shortenmsg($b, $max_char) {
429         require_once("include/bbcode.php");
430         require_once("include/html2plain.php");
431
432         // Looking for the first image
433         $image = '';
434         if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
435                 $image = $matches[3];
436
437         if ($image == '')
438                 if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
439                         $image = $matches[1];
440
441         $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
442
443         // When saved into the database the content is sent through htmlspecialchars
444         // That means that we have to decode all image-urls
445         $image = htmlspecialchars_decode($image);
446
447         $body = $b["body"];
448         if ($b["title"] != "")
449                 $body = $b["title"]."\n\n".$body;
450
451         // remove the recycle signs and the names since they aren't helpful on twitter
452         // recycle 1
453         $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
454         $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
455         // recycle 2 (Test)
456         $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
457         $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
458
459         // remove the share element
460         $body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
461
462         // At first convert the text to html
463         $html = bbcode($body, false, false);
464
465         // Then convert it to plain text
466         //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
467         $msg = trim(html2plain($html, 0, true));
468         $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
469
470         // Removing multiple newlines
471         while (strpos($msg, "\n\n\n") !== false)
472                 $msg = str_replace("\n\n\n", "\n\n", $msg);
473
474         // Removing multiple spaces
475         while (strpos($msg, "  ") !== false)
476                 $msg = str_replace("  ", " ", $msg);
477
478         // Removing URLs
479         $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
480
481         $msg = trim($msg);
482
483         $link = '';
484         // look for bookmark-bbcode and handle it with priority
485         if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
486                 $link = $matches[1];
487
488         $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
489
490         // If there is no bookmark element then take the first link
491         if ($link == '') {
492                 $links = collecturls($html);
493                 if (sizeof($links) > 0) {
494                         reset($links);
495                         $link = current($links);
496                 }
497                 $multiplelinks = (sizeof($links) > 1);
498         }
499
500         $msglink = "";
501         if ($multiplelinks)
502                 $msglink = $b["plink"];
503         else if ($link != "")
504                 $msglink = $link;
505         else if ($multipleimages)
506                 $msglink = $b["plink"];
507         else if ($image != "")
508                 $msglink = $image;
509
510         if (($msglink == "") and strlen($msg) > $max_char)
511                 $msglink = $b["plink"];
512
513         if (strlen($msglink) > 20)
514                 $msglink = short_link($msglink);
515
516         if (strlen(trim($msg." ".$msglink)) > $max_char) {
517                 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
518                 $lastchar = substr($msg, -1);
519                 $msg = substr($msg, 0, -1);
520                 $pos = strrpos($msg, "\n");
521                 if ($pos > 0)
522                         $msg = substr($msg, 0, $pos);
523                 else if ($lastchar != "\n")
524                         $msg = substr($msg, 0, -3)."...";
525         }
526         $msg = str_replace("\n", " ", $msg);
527
528         // Removing multiple spaces - again
529         while (strpos($msg, "  ") !== false)
530                 $msg = str_replace("  ", " ", $msg);
531
532         return(array("msg"=>trim($msg." ".$msglink), "image"=>$image));
533 }
534
535 function statusnet_post_hook(&$a,&$b) {
536
537         /**
538          * Post to statusnet
539          */
540
541         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
542                 return;
543
544         if(! strstr($b['postopts'],'statusnet'))
545                 return;
546
547         // if posts comes from statusnet don't send it back
548         if($b['app'] == "StatusNet")
549                 return;
550
551         logger('statusnet post invoked');
552
553         load_pconfig($b['uid'], 'statusnet');
554
555         $api     = get_pconfig($b['uid'], 'statusnet', 'baseapi');
556         $ckey    = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
557         $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
558         $otoken  = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
559         $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
560         $intelligent_shortening = get_pconfig($b['uid'], 'statusnet', 'intelligent_shortening');
561
562         // Global setting overrides this
563         if (get_config('statusnet','intelligent_shortening'))
564                 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
565
566         if($ckey && $csecret && $otoken && $osecret) {
567
568                 require_once('include/bbcode.php');
569                 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
570                 $max_char = $dent->get_maxlength(); // max. length for a dent
571                 // we will only work with up to two times the length of the dent
572                 // we can later send to StatusNet. This way we can "gain" some
573                 // information during shortening of potential links but do not
574                 // shorten all the links in a 200000 character long essay.
575
576                 $tempfile = "";
577                 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
578                 if (!$intelligent_shortening) {
579                         if (! $b['title']=='') {
580                                 $tmp = $b['title'].": \n".$b['body'];
581         //                    $tmp = substr($tmp, 0, 4*$max_char);
582                         } else {
583                             $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
584                         }
585                         // if [url=bla][img]blub.png[/img][/url] get blub.png
586                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
587                         // preserve links to images, videos and audios
588                         $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
589                         $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
590                         $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
591                         $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
592                         $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
593                         $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
594                         $linksenabled = get_pconfig($b['uid'],'statusnet','post_taglinks');
595                         // if a #tag is linked, don't send the [url] over to SN
596                         // that is, don't send if the option is not set in the 
597                         // connector settings
598                         if ($linksenabled=='0') {
599                                 // #-tags
600                                 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
601                                 // @-mentions
602                                 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
603                                 // recycle 1
604                                 $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
605                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
606                                 // recycle 2 (test)
607                                 $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
608                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
609                         }
610                         // preserve links to webpages
611                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
612                         $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
613                         // find all http or https links in the body of the entry and 
614                         // apply the shortener if the link is longer then 20 characters 
615                         if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
616                             preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls  );
617                             foreach ($allurls as $url) {
618                                 foreach ($url as $u) {
619                                     if (strlen($u)>20) {
620                                         $sl = short_link($u);
621                                         $tmp = str_replace( $u, $sl, $tmp );
622                                     }
623                                 }
624                             }
625                         }
626                         // ok, all the links we want to send out are save, now strip 
627                         // away the remaining bbcode
628                         //$msg = strip_tags(bbcode($tmp, false, false));
629                         $msg = bbcode($tmp, false, false);
630                         $msg = str_replace(array('<br>','<br />'),"\n",$msg);
631                         $msg = strip_tags($msg);
632
633                         // quotes not working - let's try this
634                         $msg = html_entity_decode($msg);
635
636                         if (( strlen($msg) > $max_char) && $max_char > 0) {
637                                 $shortlink = short_link( $b['plink'] );
638                                 // the new message will be shortened such that "... $shortlink"
639                                 // will fit into the character limit
640                                 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
641                                 $msg = str_replace(array('<br>','<br />'),' ',$msg);
642                                 $e = explode(' ', $msg);
643                                 //  remove the last word from the cut down message to 
644                                 //  avoid sending cut words to the MicroBlog
645                                 array_pop($e);
646                                 $msg = implode(' ', $e);
647                                 $msg .= '... ' . $shortlink;
648                         }
649
650                         $msg = trim($msg);
651                         $postdata = array('status' => $msg);
652                 } else {
653                         $msgarr = statusnet_shortenmsg($b, $max_char);
654                         $msg = $msgarr["msg"];
655                         $image = $msgarr["image"];
656                         if ($image != "") {
657                                 $imagedata = file_get_contents($image);
658                                 $tempfile = tempnam(get_config("system","temppath"), "upload");
659                                 file_put_contents($tempfile, $imagedata);
660                                 $postdata = array("status"=>$msg, "media"=>"@".$tempfile);
661                         } else
662                                 $postdata = array("status"=>$msg);
663                 }
664
665                 // and now dent it :-)
666                 if(strlen($msg)) {
667                     //$result = $dent->post('statuses/update', array('status' => $msg));
668                     $result = $dent->post('statuses/update', $postdata);
669                     logger('statusnet_post send, result: ' . print_r($result, true).
670                            "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
671                     if ($result->error) {
672                         logger('Send to StatusNet failed: "' . $result->error . '"');
673                     }
674                 }
675                 if ($tempfile != "")
676                         unlink($tempfile);
677         }
678 }
679
680 function statusnet_plugin_admin_post(&$a){
681         
682         $sites = array();
683         
684         foreach($_POST['sitename'] as $id=>$sitename){
685                 $sitename=trim($sitename);
686                 $apiurl=trim($_POST['apiurl'][$id]);
687                 $secret=trim($_POST['secret'][$id]);
688                 $key=trim($_POST['key'][$id]);
689                 if ($sitename!="" &&
690                         $apiurl!="" &&
691                         $secret!="" &&
692                         $key!="" &&
693                         !x($_POST['delete'][$id])){
694                                 
695                                 $sites[] = Array(
696                                         'sitename' => $sitename,
697                                         'apiurl' => $apiurl,
698                                         'consumersecret' => $secret,
699                                         'consumerkey' => $key
700                                 );
701                 }
702         }
703         
704         $sites = set_config('statusnet','sites', $sites);
705         
706 }
707
708 function statusnet_plugin_admin(&$a, &$o){
709
710         $sites = get_config('statusnet','sites');
711         $sitesform=array();
712         if (is_array($sites)){
713                 foreach($sites as $id=>$s){
714                         $sitesform[] = Array(
715                                 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
716                                 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
717                                 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
718                                 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
719                                 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
720                         );
721                 }
722         }
723         /* empty form to add new site */
724         $id++;
725         $sitesform[] = Array(
726                 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
727                 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
728                 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
729                 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
730         );
731
732         $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
733         $o = replace_macros($t, array(
734                 '$submit' => t('Submit'),
735                 '$sites' => $sitesform,
736         ));
737 }
738
739 function statusnet_cron($a,$b) {
740         $last = get_config('statusnet','last_poll');
741
742         $poll_interval = intval(get_config('statusnet','poll_interval'));
743         if(! $poll_interval)
744                 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
745
746         if($last) {
747                 $next = $last + ($poll_interval * 60);
748                 if($next > time()) {
749                         logger('statusnet: poll intervall not reached');
750                         return;
751                 }
752         }
753         logger('statusnet: cron_start');
754
755         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
756         if(count($r)) {
757                 foreach($r as $rr) {
758                         logger('statusnet: fetching for user '.$rr['uid']);
759                         statusnet_fetchtimeline($a, $rr['uid']);
760                 }
761         }
762
763         logger('statusnet: cron_end');
764
765         set_config('statusnet','last_poll', time());
766 }
767
768 function statusnet_fetchtimeline($a, $uid) {
769         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
770         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
771         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
772         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
773         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
774         $lastid  = get_pconfig($uid, 'statusnet', 'lastid');
775
776         $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
777
778         $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
779
780         if ($lastid <> "")
781                 $parameters["since_id"] = $lastid;
782
783         $items = $connection->get('statuses/user_timeline', $parameters);
784         $posts = array_reverse($items);
785
786         foreach ($posts as $post) {
787                 if ($post->id > $lastid)
788                         $lastid = $post->id;
789
790                 if (is_object($post->retweeted_status))
791                         continue;
792
793                 if (!strpos($post->source, $a->get_hostname())) {
794                         $_SESSION["authenticated"] = true;
795                         $_SESSION["uid"] = $uid;
796
797                         $_REQUEST["type"] = "wall";
798                         $_REQUEST["api_source"] = true;
799                         $_REQUEST["profile_uid"] = $uid;
800                         $_REQUEST["source"] = "StatusNet";
801
802                         //$_REQUEST["date"] = $post->created_at;
803
804                         $_REQUEST["body"] = $post->text;
805                         if (is_string($post->place->name))
806                                 $_REQUEST["location"] = $post->place->name;
807
808                         if (is_string($post->place->full_name))
809                                 $_REQUEST["location"] = $post->place->full_name;
810
811                         if (is_array($post->geo->coordinates))
812                                 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
813
814                         if (is_array($post->coordinates->coordinates))
815                                 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
816
817                         //print_r($_REQUEST);
818                         if ($_REQUEST["body"] != "") {
819                                 logger('statusnet: posting for user '.$uid);
820
821                                 require_once('mod/item.php');
822                                 item_post($a);
823                         }
824                 }
825         }
826         set_pconfig($uid, 'statusnet', 'lastid', $lastid);
827 }
828