]> git.mxchange.org Git - friendica-addons.git/blob - statusnet/statusnet.php
Merge pull request #185 from annando/master
[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 <https://f.diekershoff.de/profile/tobias>
7  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
8  *
9  * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel
10  * All rights reserved.
11  *
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.
22  *
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.
33  *
34  */
35  
36
37 /***
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.
40  *
41  * Thank you guys for the Twitter compatible API!
42  */
43
44 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
45
46 require_once('library/twitteroauth.php');
47
48 class StatusNetOAuth extends TwitterOAuth {
49     function get_maxlength() {
50         $config = $this->get($this->host . 'statusnet/config.json');
51         return $config->site->textlimit;
52     }
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;
60     }
61   /**
62    * Make an HTTP request
63    *
64    * @return API results
65    *
66    * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
67    */
68   function http($url, $method, $postfields = NULL) {
69     $this->http_info = array();
70     $ci = curl_init();
71     /* Curl settings */
72     $prx = get_config('system','proxy');
73     if(strlen($prx)) {
74         curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
75         curl_setopt($ci, CURLOPT_PROXY, $prx);
76         $prxusr = get_config('system','proxyuser');
77         if(strlen($prxusr))
78             curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
79     }
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);
88
89     switch ($method) {
90       case 'POST':
91         curl_setopt($ci, CURLOPT_POST, TRUE);
92         if (!empty($postfields)) {
93           curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
94         }
95         break;
96       case 'DELETE':
97         curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
98         if (!empty($postfields)) {
99           $url = "{$url}?{$postfields}";
100         }
101     }
102
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));
107     $this->url = $url;
108     curl_close ($ci);
109     return $response;
110   }
111 }
112
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");
122 }
123
124
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');
132
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');
137
138 }
139
140 function statusnet_jot_nets(&$a,&$b) {
141         if(! local_user())
142                 return;
143
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>';
150         }
151 }
152
153 function statusnet_settings_post ($a,$post) {
154         if(! local_user())
155             return;
156         // don't check statusnet settings if statusnet submit button is not clicked
157         if (!x($_POST,'statusnet-submit')) return;
158
159         if (isset($_POST['statusnet-disconnect'])) {
160             /***
161              * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
162              */
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');
174         } else {
175             if (isset($_POST['statusnet-preconf-apiurl'])) {
176                 /***
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 ^^
180                  */
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'] );
191                         } else {
192                             notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
193                         }
194                     }
195                 }
196                 goaway($a->get_baseurl().'/settings/connectors');
197             } else {
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'] );
210                 } else {
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 );
219                     } else {
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 );
222                     }
223                 }
224                 goaway($a->get_baseurl().'/settings/connectors');
225             } else {
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');
243                                 } else {
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);
252                 }}}}
253 }
254 function statusnet_settings(&$a,&$s) {
255         if(! local_user())
256                 return;
257         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
258         /***
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)
263          */
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" ' : '');
275
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" ' : '');
280
281         $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
282         $s .= '<h3>'. t('StatusNet').'</h3>';
283         $s .= '</span>';
284         $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
285         $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
286         $s .= '<h3>'. t('StatusNet').'</h3>';
287         $s .= '</span>';
288
289         if ( (!$ckey) && (!$csecret) ) {
290                 /***
291                  * no consumer keys
292                  */
293             $globalsn = get_config('statusnet', 'sites');
294             /***
295              * lets check if we have one or more globally configured StatusNet
296              * server OAuth credentials in the configuration. If so offer them
297              * with a little explanation to the user as choice - otherwise
298              * ignore this option entirely.
299              */
300             if (! $globalsn == null) {
301                 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
302                 $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>';
303                 $s .= '<div id="statusnet-preconf-wrapper">';
304                 foreach ($globalsn as $asn) {
305                     $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
306                 }
307                 $s .= '<p></p><div class="clear"></div></div>';
308                 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
309             }
310             $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
311             $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>';
312             $s .= '<div id="statusnet-consumer-wrapper">';
313             $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
314             $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
315             $s .= '<div class="clear"></div>';
316             $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
317             $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
318             $s .= '<div class="clear"></div>';
319             $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
320             $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
321             $s .= '<div class="clear"></div>';
322             $s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('StatusNet application name').'</label>';
323             $s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
324             $s .= '<p></p><div class="clear"></div>';
325             $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
326             $s .= '</div>';
327         } else {
328                 /***
329                  * ok we have a consumer key pair now look into the OAuth stuff
330                  */
331                 if ( (!$otoken) && (!$osecret) ) {
332                         /***
333                          * the user has not yet connected the account to statusnet
334                          * get a temporary OAuth key/secret pair and display a button with
335                          * which the user can request a PIN to connect the account to a
336                          * account at statusnet
337                          */
338                         $connection = new StatusNetOAuth($api, $ckey, $csecret);
339                         $request_token = $connection->getRequestToken('oob');
340                         $token = $request_token['oauth_token'];
341                         /***
342                          *  make some nice form
343                          */
344                         $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>';
345                         $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
346                         $s .= '<div id="statusnet-pin-wrapper">';
347                         $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
348                         $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
349                         $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
350                         $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
351                         $s .= '</div><div class="clear"></div>';
352                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
353                         $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
354                         $s .= '<div id="statusnet-cancel-wrapper">';
355                         $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
356                         $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
357                         $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
358                         $s .= '</div><div class="clear"></div>';
359                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
360                 } else {
361                         /***
362                          *  we have an OAuth key / secret pair for the user
363                          *  so let's give a chance to disable the postings to statusnet
364                          */
365                         $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
366                         $details = $connection->get('account/verify_credentials');
367                         $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>';
368                         $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>';
369                         if ($a->user['hidewall']) {
370                             $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>';
371                         }
372                         $s .= '<div id="statusnet-enable-wrapper">';
373                         $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
374                         $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
375                         $s .= '<div class="clear"></div>';
376                         $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
377                         $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
378                         $s .= '<div class="clear"></div>';
379
380                         $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from statusnet that are no replies or repeated messages').'</label>';
381                         $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
382                         $s .= '<div class="clear"></div>';
383
384                         $s .= '<label id="statusnet-shortening-label" for="statusnet-shortening">'.t('Shortening method that optimizes the post').'</label>';
385                         $s .= '<input id="statusnet-shortening" type="checkbox" name="statusnet-shortening" value="1" '. $shorteningchecked . '/>';
386                         $s .= '<div class="clear"></div>';
387
388                         $s .= '<label id="statusnet-sendtaglinks-label" for="statusnet-sendtaglinks">'.t('Send linked #-tags and @-names to StatusNet').'</label>';
389                         $s .= '<input id="statusnet-sendtaglinks" type="checkbox" name="statusnet-sendtaglinks" value="1" '. $linkschecked . '/>';
390                         $s .= '</div><div class="clear"></div>';
391
392                         $s .= '<div id="statusnet-disconnect-wrapper">';
393                         $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
394                         $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
395                         $s .= '</div><div class="clear"></div>';
396                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>'; 
397                 }
398         }
399         $s .= '</div><div class="clear"></div>';
400 }
401
402
403 function statusnet_post_local(&$a,&$b) {
404         if($b['edit'])
405                 return;
406
407         if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
408
409                 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
410                 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
411
412                 // if API is used, default to the chosen settings
413                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
414                         $statusnet_enable = 1;
415
416        if(! $statusnet_enable)
417             return;
418
419        if(strlen($b['postopts']))
420            $b['postopts'] .= ',';
421        $b['postopts'] .= 'statusnet';
422     }
423 }
424
425 if (! function_exists( 'short_link' )) {
426 function short_link($url) {
427     require_once('library/slinky.php');
428     $slinky = new Slinky( $url );
429     $yourls_url = get_config('yourls','url1');
430     if ($yourls_url) {
431             $yourls_username = get_config('yourls','username1');
432             $yourls_password = get_config('yourls', 'password1');
433             $yourls_ssl = get_config('yourls', 'ssl1');
434             $yourls = new Slinky_YourLS();
435             $yourls->set( 'username', $yourls_username );
436             $yourls->set( 'password', $yourls_password );
437             $yourls->set( 'ssl', $yourls_ssl );
438             $yourls->set( 'yourls-url', $yourls_url );
439             $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
440     }
441     else {
442             // setup a cascade of shortening services
443             // try to get a short link from these services
444             // in the order ur1.ca, trim, id.gd, tinyurl
445             $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
446     }
447     return $slinky->short();
448 } };
449
450 function statusnet_shortenmsg($b, $max_char) {
451         require_once("include/api.php");
452         require_once("include/bbcode.php");
453         require_once("include/html2plain.php");
454
455         $b['body'] = bb_CleanPictureLinks($b['body']);
456
457         // Looking for the first image
458         $cleaned_body = api_clean_plain_items($b['body']);
459         $image = '';
460         if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$cleaned_body,$matches))
461                 $image = $matches[3];
462
463         if ($image == '')
464                 if(preg_match("/\[img\](.*?)\[\/img\]/is",$cleaned_body,$matches))
465                         $image = $matches[1];
466
467         $multipleimages = (strpos($cleaned_body, "[img") != strrpos($cleaned_body, "[img"));
468
469         // When saved into the database the content is sent through htmlspecialchars
470         // That means that we have to decode all image-urls
471         $image = htmlspecialchars_decode($image);
472
473         $body = $b["body"];
474         if ($b["title"] != "")
475                 $body = $b["title"]."\n\n".$body;
476
477         if (strpos($body, "[bookmark") !== false) {
478                 // splitting the text in two parts:
479                 // before and after the bookmark
480                 $pos = strpos($body, "[bookmark");
481                 $body1 = substr($body, 0, $pos);
482                 $body2 = substr($body, $pos);
483
484                 // Removing all quotes after the bookmark
485                 // they are mostly only the content after the bookmark.
486                 $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
487                 $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
488                 $body = $body1.$body2;
489         }
490
491         // Add some newlines so that the message could be cut better
492         $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
493                                 array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
494
495         // remove the recycle signs and the names since they aren't helpful on twitter
496         // recycle 1
497         $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
498         $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
499         // recycle 2 (Test)
500         $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
501         $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
502
503         // remove the share element
504         //$body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
505
506         // At first convert the text to html
507         $html = bbcode(api_clean_plain_items($body), false, false, 2);
508
509         // Then convert it to plain text
510         //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
511         $msg = trim(html2plain($html, 0, true));
512         $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
513
514         // Removing multiple newlines
515         while (strpos($msg, "\n\n\n") !== false)
516                 $msg = str_replace("\n\n\n", "\n\n", $msg);
517
518         // Removing multiple spaces
519         while (strpos($msg, "  ") !== false)
520                 $msg = str_replace("  ", " ", $msg);
521
522         $origmsg = $msg;
523
524         // Removing URLs
525         $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
526
527         $msg = trim($msg);
528
529         $link = '';
530         // look for bookmark-bbcode and handle it with priority
531         if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
532                 $link = $matches[1];
533
534         $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
535
536         // If there is no bookmark element then take the first link
537         if ($link == '') {
538                 $links = collecturls($html);
539                 if (sizeof($links) > 0) {
540                         reset($links);
541                         $link = current($links);
542                 }
543                 $multiplelinks = (sizeof($links) > 1);
544         }
545
546         $msglink = "";
547         if ($multiplelinks)
548                 $msglink = $b["plink"];
549         else if ($link != "")
550                 $msglink = $link;
551         else if ($multipleimages)
552                 $msglink = $b["plink"];
553         else if ($image != "")
554                 $msglink = $image;
555
556         if (($msglink == "") and strlen($msg) > $max_char)
557                 $msglink = $b["plink"];
558
559         // If the message is short enough then don't modify it. (if the link exists in the original message)
560         if ((strlen(trim($origmsg)) <= $max_char) AND (($msglink == "") OR strpos($origmsg, $msglink)))
561                 return(array("msg"=>trim($origmsg), "image"=>""));
562
563         // If the message is short enough and contains a picture then post the picture as well
564         if ((strlen(trim($origmsg)) <= ($max_char - 20)) AND strpos($origmsg, $msglink))
565                 return(array("msg"=>trim($origmsg), "image"=>$image));
566
567         // If the message is short enough and the link exists in the original message don't modify it as well
568         if ((strlen(trim($origmsg)) <= $max_char) AND strpos($origmsg, $msglink))
569                 return(array("msg"=>trim($origmsg), "image"=>""));
570
571         // Preserve the unshortened link
572         $orig_link = $msglink;
573
574         if (strlen($msglink) > 20)
575                 $msglink = short_link($msglink);
576
577         if (strlen(trim($msg." ".$msglink)) > $max_char) {
578                 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
579                 $lastchar = substr($msg, -1);
580                 $msg = substr($msg, 0, -1);
581                 $pos = strrpos($msg, "\n");
582                 if ($pos > 0)
583                         $msg = substr($msg, 0, $pos);
584                 else if ($lastchar != "\n")
585                         $msg = substr($msg, 0, -3)."...";
586         }
587         //$msg = str_replace("\n", " ", $msg);
588
589         // Removing multiple spaces - again
590         while (strpos($msg, "  ") !== false)
591                 $msg = str_replace("  ", " ", $msg);
592
593         //return(array("msg"=>trim($msg."\n".$msglink), "image"=>$image));
594
595         // Looking if the link points to an image
596         $img_str = fetch_url($orig_link);
597
598         $tempfile = tempnam(get_config("system","temppath"), "cache");
599         file_put_contents($tempfile, $img_str);
600         $mime = image_type_to_mime_type(exif_imagetype($tempfile));
601         unlink($tempfile);
602
603         if (($image == $orig_link) OR (substr($mime, 0, 6) == "image/"))
604                 return(array("msg"=>trim($msg), "image"=>$orig_link));
605         else if (($image != $orig_link) AND ($image != "") AND (strlen($msg." ".$msglink) <= ($max_char - 20)))
606                 return(array("msg"=>trim($msg." ".$msglink)."\n", "image"=>$image));
607         else
608                 return(array("msg"=>trim($msg." ".$msglink), "image"=>""));
609 }
610
611 function statusnet_post_hook(&$a,&$b) {
612
613         /**
614          * Post to statusnet
615          */
616
617         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
618                 return;
619
620         if(! strstr($b['postopts'],'statusnet'))
621                 return;
622
623         if($b['parent'] != $b['id'])
624                 return;
625
626         // if posts comes from statusnet don't send it back
627         if($b['app'] == "StatusNet")
628                 return;
629
630         logger('statusnet post invoked');
631
632         load_pconfig($b['uid'], 'statusnet');
633
634         $api     = get_pconfig($b['uid'], 'statusnet', 'baseapi');
635         $ckey    = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
636         $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
637         $otoken  = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
638         $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
639         $intelligent_shortening = get_pconfig($b['uid'], 'statusnet', 'intelligent_shortening');
640
641         // Global setting overrides this
642         if (get_config('statusnet','intelligent_shortening'))
643                 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
644
645         if($ckey && $csecret && $otoken && $osecret) {
646
647                 require_once('include/bbcode.php');
648                 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
649                 $max_char = $dent->get_maxlength(); // max. length for a dent
650                 // we will only work with up to two times the length of the dent
651                 // we can later send to StatusNet. This way we can "gain" some
652                 // information during shortening of potential links but do not
653                 // shorten all the links in a 200000 character long essay.
654
655                 $tempfile = "";
656                 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
657                 if (!$intelligent_shortening) {
658                         if (! $b['title']=='') {
659                                 $tmp = $b['title'].": \n".$b['body'];
660         //                    $tmp = substr($tmp, 0, 4*$max_char);
661                         } else {
662                             $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
663                         }
664                         // if [url=bla][img]blub.png[/img][/url] get blub.png
665                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
666                         // preserve links to images, videos and audios
667                         $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
668                         $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
669                         $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
670                         $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
671                         $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
672                         $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
673                         $linksenabled = get_pconfig($b['uid'],'statusnet','post_taglinks');
674                         // if a #tag is linked, don't send the [url] over to SN
675                         // that is, don't send if the option is not set in the 
676                         // connector settings
677                         if ($linksenabled=='0') {
678                                 // #-tags
679                                 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
680                                 // @-mentions
681                                 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
682                                 // recycle 1
683                                 $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
684                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
685                                 // recycle 2 (test)
686                                 $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
687                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
688                         }
689                         // preserve links to webpages
690                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
691                         $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
692                         // find all http or https links in the body of the entry and 
693                         // apply the shortener if the link is longer then 20 characters 
694                         if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
695                             preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls  );
696                             foreach ($allurls as $url) {
697                                 foreach ($url as $u) {
698                                     if (strlen($u)>20) {
699                                         $sl = short_link($u);
700                                         $tmp = str_replace( $u, $sl, $tmp );
701                                     }
702                                 }
703                             }
704                         }
705                         // ok, all the links we want to send out are save, now strip 
706                         // away the remaining bbcode
707                         //$msg = strip_tags(bbcode($tmp, false, false));
708                         $msg = bbcode($tmp, false, false, true);
709                         $msg = str_replace(array('<br>','<br />'),"\n",$msg);
710                         $msg = strip_tags($msg);
711
712                         // quotes not working - let's try this
713                         $msg = html_entity_decode($msg);
714
715                         if (( strlen($msg) > $max_char) && $max_char > 0) {
716                                 $shortlink = short_link( $b['plink'] );
717                                 // the new message will be shortened such that "... $shortlink"
718                                 // will fit into the character limit
719                                 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
720                                 $msg = str_replace(array('<br>','<br />'),' ',$msg);
721                                 $e = explode(' ', $msg);
722                                 //  remove the last word from the cut down message to 
723                                 //  avoid sending cut words to the MicroBlog
724                                 array_pop($e);
725                                 $msg = implode(' ', $e);
726                                 $msg .= '... ' . $shortlink;
727                         }
728
729                         $msg = trim($msg);
730                         $postdata = array('status' => $msg);
731                 } else {
732                         $msgarr = statusnet_shortenmsg($b, $max_char);
733                         $msg = $msgarr["msg"];
734                         $image = $msgarr["image"];
735                         if ($image != "") {
736                                 $img_str = fetch_url($image);
737                                 $tempfile = tempnam(get_config("system","temppath"), "cache");
738                                 file_put_contents($tempfile, $img_str);
739                                 $postdata = array("status" => $msg, "media[]" => $tempfile);
740                         } else
741                                 $postdata = array("status"=>$msg);
742                 }
743
744                 // and now dent it :-)
745                 if(strlen($msg)) {
746
747                     // New code that is able to post pictures
748                     require_once("addon/statusnet/codebird.php");
749                     $cb = \CodebirdSN\CodebirdSN::getInstance();
750                     $cb->setAPIEndpoint($api);
751                     $cb->setConsumerKey($ckey, $csecret);
752                     $cb->setToken($otoken, $osecret);
753                     $result = $cb->statuses_update($postdata);
754                     //$result = $dent->post('statuses/update', $postdata);
755                     logger('statusnet_post send, result: ' . print_r($result, true).
756                            "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
757                     if ($result->error) {
758                         logger('Send to StatusNet failed: "' . $result->error . '"');
759                     }
760                 }
761                 if ($tempfile != "")
762                         unlink($tempfile);
763         }
764 }
765
766 function statusnet_plugin_admin_post(&$a){
767
768         $sites = array();
769
770         foreach($_POST['sitename'] as $id=>$sitename){
771                 $sitename=trim($sitename);
772                 $apiurl=trim($_POST['apiurl'][$id]);
773                 if (! (substr($apiurl, -1)=='/'))
774                     $apiurl=$apiurl.'/';
775                 $secret=trim($_POST['secret'][$id]);
776                 $key=trim($_POST['key'][$id]);
777                 $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
778                 if ($sitename!="" &&
779                         $apiurl!="" &&
780                         $secret!="" &&
781                         $key!="" &&
782                         !x($_POST['delete'][$id])){
783                                 
784                                 $sites[] = Array(
785                                         'sitename' => $sitename,
786                                         'apiurl' => $apiurl,
787                                         'consumersecret' => $secret,
788                                         'consumerkey' => $key,
789                                         'applicationname' => $applicationname
790                                 );
791                 }
792         }
793         
794         $sites = set_config('statusnet','sites', $sites);
795         
796 }
797
798 function statusnet_plugin_admin(&$a, &$o){
799
800         $sites = get_config('statusnet','sites');
801         $sitesform=array();
802         if (is_array($sites)){
803                 foreach($sites as $id=>$s){
804                         $sitesform[] = Array(
805                                 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
806                                 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29") ),
807                                 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
808                                 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
809                                 'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
810                                 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
811                         );
812                 }
813         }
814         /* empty form to add new site */
815         $id++;
816         $sitesform[] = Array(
817                 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
818                 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29") ),
819                 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
820                 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
821                 'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
822         );
823
824         $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
825         $o = replace_macros($t, array(
826                 '$submit' => t('Save Settings'),
827                 '$sites' => $sitesform,
828         ));
829 }
830
831 function statusnet_cron($a,$b) {
832         $last = get_config('statusnet','last_poll');
833
834         $poll_interval = intval(get_config('statusnet','poll_interval'));
835         if(! $poll_interval)
836                 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
837
838         if($last) {
839                 $next = $last + ($poll_interval * 60);
840                 if($next > time()) {
841                         logger('statusnet: poll intervall not reached');
842                         return;
843                 }
844         }
845         logger('statusnet: cron_start');
846
847         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
848         if(count($r)) {
849                 foreach($r as $rr) {
850                         logger('statusnet: fetching for user '.$rr['uid']);
851                         statusnet_fetchtimeline($a, $rr['uid']);
852                 }
853         }
854
855         logger('statusnet: cron_end');
856
857         set_config('statusnet','last_poll', time());
858 }
859
860 function statusnet_fetchtimeline($a, $uid) {
861         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
862         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
863         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
864         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
865         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
866         $lastid  = get_pconfig($uid, 'statusnet', 'lastid');
867
868         //  get the application name for the SN app
869         //  1st try personal config, then system config and fallback to the 
870         //  hostname of the node if neither one is set. 
871         $application_name  = get_pconfig( $uid, 'statusnet', 'application_name');
872         if ($application_name == "")
873                 $application_name  = get_config('statusnet', 'application_name');
874         if ($application_name == "")
875                 $application_name = $a->get_hostname();
876
877         $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
878
879         $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
880
881         $first_time = ($lastid == "");
882
883         if ($lastid <> "")
884                 $parameters["since_id"] = $lastid;
885
886         $items = $connection->get('statuses/user_timeline', $parameters);
887
888         if (!is_array($items))
889                 return;
890
891         $posts = array_reverse($items);
892
893         if (count($posts)) {
894             foreach ($posts as $post) {
895                 if ($post->id > $lastid)
896                         $lastid = $post->id;
897
898                 if ($first_time)
899                         continue;
900
901                 if ($post->source == "activity")
902                         continue;
903
904                 if (is_object($post->retweeted_status))
905                         continue;
906
907                 if ($post->in_reply_to_status_id != "")
908                         continue;
909
910                 if (!strpos($post->source, $application_name)) {
911                         $_SESSION["authenticated"] = true;
912                         $_SESSION["uid"] = $uid;
913
914                         unset($_REQUEST);
915                         $_REQUEST["type"] = "wall";
916                         $_REQUEST["api_source"] = true;
917                         $_REQUEST["profile_uid"] = $uid;
918                         $_REQUEST["source"] = "StatusNet";
919
920                         //$_REQUEST["date"] = $post->created_at;
921
922                         $_REQUEST["title"] = "";
923
924                         $_REQUEST["body"] = $post->text;
925                         if (is_string($post->place->name))
926                                 $_REQUEST["location"] = $post->place->name;
927
928                         if (is_string($post->place->full_name))
929                                 $_REQUEST["location"] = $post->place->full_name;
930
931                         if (is_array($post->geo->coordinates))
932                                 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
933
934                         if (is_array($post->coordinates->coordinates))
935                                 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
936
937                         //print_r($_REQUEST);
938                         if ($_REQUEST["body"] != "") {
939                                 logger('statusnet: posting for user '.$uid);
940
941                                 require_once('mod/item.php');
942                                 item_post($a);
943                         }
944                 }
945             }
946         }
947         set_pconfig($uid, 'statusnet', 'lastid', $lastid);
948 }
949