]> git.mxchange.org Git - friendica-addons.git/blob - statusnet/statusnet.php
Merge pull request #196 from tobiasd/newmemberwidget1
[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'))
158                 return;
159
160         if (isset($_POST['statusnet-disconnect'])) {
161                 /***
162                  * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
163                  */
164                 del_pconfig(local_user(), 'statusnet', 'consumerkey');
165                 del_pconfig(local_user(), 'statusnet', 'consumersecret');
166                 del_pconfig(local_user(), 'statusnet', 'post');
167                 del_pconfig(local_user(), 'statusnet', 'post_by_default');
168                 del_pconfig(local_user(), 'statusnet', 'oauthtoken');
169                 del_pconfig(local_user(), 'statusnet', 'oauthsecret');
170                 del_pconfig(local_user(), 'statusnet', 'baseapi');
171                 del_pconfig(local_user(), 'statusnet', 'lastid');
172                 del_pconfig(local_user(), 'statusnet', 'mirror_posts');
173                 del_pconfig(local_user(), 'statusnet', 'import');
174                 del_pconfig(local_user(), 'statusnet', 'create_user');
175                 del_pconfig(local_user(), 'statusnet', 'own_id');
176         } else {
177         if (isset($_POST['statusnet-preconf-apiurl'])) {
178                 /***
179                  * If the user used one of the preconfigured StatusNet server credentials
180                  * use them. All the data are available in the global config.
181                  * Check the API Url never the less and blame the admin if it's not working ^^
182                  */
183                 $globalsn = get_config('statusnet', 'sites');
184                 foreach ( $globalsn as $asn) {
185                         if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
186                                 $apibase = $asn['apiurl'];
187                                 $c = fetch_url( $apibase . 'statusnet/version.xml' );
188                                 if (strlen($c) > 0) {
189                                         set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
190                                         set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
191                                         set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
192                                         set_pconfig(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
193                                 } else {
194                                         notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
195                                 }
196                         }
197                 }
198                 goaway($a->get_baseurl().'/settings/connectors');
199         } else {
200         if (isset($_POST['statusnet-consumersecret'])) {
201                 //  check if we can reach the API of the StatusNet server
202                 //  we'll check the API Version for that, if we don't get one we'll try to fix the path but will
203                 //  resign quickly after this one try to fix the path ;-)
204                 $apibase = $_POST['statusnet-baseapi'];
205                 $c = fetch_url( $apibase . 'statusnet/version.xml' );
206                 if (strlen($c) > 0) {
207                         //  ok the API path is correct, let's save the settings
208                         set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
209                         set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
210                         set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
211                         set_pconfig(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
212                 } else {
213                         //  the API path is not correct, maybe missing trailing / ?
214                         $apibase = $apibase . '/';
215                         $c = fetch_url( $apibase . 'statusnet/version.xml' );
216                         if (strlen($c) > 0) {
217                                 //  ok the API path is now correct, let's save the settings
218                                 set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
219                                 set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
220                                 set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
221                         } else {
222                                 //  still not the correct API base, let's do noting
223                                 notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
224                         }
225                 }
226                 goaway($a->get_baseurl().'/settings/connectors');
227         } else {
228         if (isset($_POST['statusnet-pin'])) {
229                 //  if the user supplied us with a PIN from StatusNet, let the magic of OAuth happen
230                 $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
231                 $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey'  );
232                 $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
233                 //  the token and secret for which the PIN was generated were hidden in the settings
234                 //  form as token and token2, we need a new connection to StatusNet using these token
235                 //  and secret to request a Access Token with the PIN
236                 $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
237                 $token   = $connection->getAccessToken( $_POST['statusnet-pin'] );
238                 //  ok, now that we have the Access Token, save them in the user config
239                 set_pconfig(local_user(),'statusnet', 'oauthtoken',  $token['oauth_token']);
240                 set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
241                 set_pconfig(local_user(),'statusnet', 'post', 1);
242                 set_pconfig(local_user(),'statusnet', 'post_taglinks', 1);
243                 //  reload the Addon Settings page, if we don't do it see Bug #42
244                 goaway($a->get_baseurl().'/settings/connectors');
245         } else {
246                 //  if no PIN is supplied in the POST variables, the user has changed the setting
247                 //  to post a dent for every new __public__ posting to the wall
248                 set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
249                 set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
250                 set_pconfig(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
251                 set_pconfig(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
252                 set_pconfig(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
253
254                 if (!intval($_POST['statusnet-mirror']))
255                         del_pconfig(local_user(),'statusnet','lastid');
256
257                 info( t('StatusNet settings updated.') . EOL);
258         }}}}
259 }
260 function statusnet_settings(&$a,&$s) {
261         if(! local_user())
262                 return;
263         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
264         /***
265          * 1) Check that we have a base api url and a consumer key & secret
266          * 2) If no OAuthtoken & stuff is present, generate button to get some
267          *    allow the user to cancel the connection process at this step
268          * 3) Checkbox for "Send public notices (respect size limitation)
269          */
270         $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
271         $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey');
272         $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret');
273         $otoken  = get_pconfig(local_user(), 'statusnet', 'oauthtoken');
274         $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret');
275         $enabled = get_pconfig(local_user(), 'statusnet', 'post');
276         $checked = (($enabled) ? ' checked="checked" ' : '');
277         $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
278         $defchecked = (($defenabled) ? ' checked="checked" ' : '');
279         $mirrorenabled = get_pconfig(local_user(),'statusnet','mirror_posts');
280         $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
281         $importenabled = get_pconfig(local_user(),'statusnet','import');
282         $importchecked = (($importenabled) ? ' checked="checked" ' : '');
283         $create_userenabled = get_pconfig(local_user(),'statusnet','create_user');
284         $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
285
286         $css = (($enabled) ? '' : '-disabled');
287
288         $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
289         $s .= '<img class="connector'.$css.'" src="images/gnusocial.png" /><h3 class="connector">'. t('StatusNet Import/Export/Mirror').'</h3>';
290         $s .= '</span>';
291         $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
292         $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
293         $s .= '<img class="connector'.$css.'" src="images/gnusocial.png" /><h3 class="connector">'. t('StatusNet Import/Export/Mirror').'</h3>';
294         $s .= '</span>';
295
296         if ( (!$ckey) && (!$csecret) ) {
297                 /***
298                  * no consumer keys
299                  */
300                 $globalsn = get_config('statusnet', 'sites');
301                 /***
302                  * lets check if we have one or more globally configured StatusNet
303                  * server OAuth credentials in the configuration. If so offer them
304                  * with a little explanation to the user as choice - otherwise
305                  * ignore this option entirely.
306                  */
307                 if (! $globalsn == null) {
308                         $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
309                         $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>';
310                         $s .= '<div id="statusnet-preconf-wrapper">';
311                         foreach ($globalsn as $asn) {
312                                 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
313                         }
314                         $s .= '<p></p><div class="clear"></div></div>';
315                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
316                 }
317                 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
318                 $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>';
319                 $s .= '<div id="statusnet-consumer-wrapper">';
320                 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
321                 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
322                 $s .= '<div class="clear"></div>';
323                 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
324                 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
325                 $s .= '<div class="clear"></div>';
326                 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
327                 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
328                 $s .= '<div class="clear"></div>';
329                 $s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('StatusNet application name').'</label>';
330                 $s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
331                 $s .= '<p></p><div class="clear"></div>';
332                 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
333                 $s .= '</div>';
334         } else {
335                 /***
336                  * ok we have a consumer key pair now look into the OAuth stuff
337                  */
338                 if ( (!$otoken) && (!$osecret) ) {
339                         /***
340                          * the user has not yet connected the account to statusnet
341                          * get a temporary OAuth key/secret pair and display a button with
342                          * which the user can request a PIN to connect the account to a
343                          * account at statusnet
344                          */
345                         $connection = new StatusNetOAuth($api, $ckey, $csecret);
346                         $request_token = $connection->getRequestToken('oob');
347                         $token = $request_token['oauth_token'];
348                         /***
349                          *  make some nice form
350                          */
351                         $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>';
352                         $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
353                         $s .= '<div id="statusnet-pin-wrapper">';
354                         $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
355                         $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
356                         $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
357                         $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
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                         $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
361                         $s .= '<div id="statusnet-cancel-wrapper">';
362                         $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
363                         $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
364                         $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
365                         $s .= '</div><div class="clear"></div>';
366                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
367                 } else {
368                         /***
369                          *  we have an OAuth key / secret pair for the user
370                          *  so let's give a chance to disable the postings to statusnet
371                          */
372                         $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
373                         $details = $connection->get('account/verify_credentials');
374                         $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>';
375                         $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>';
376                         if ($a->user['hidewall']) {
377                             $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>';
378                         }
379                         $s .= '<div id="statusnet-enable-wrapper">';
380                         $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
381                         $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
382                         $s .= '<div class="clear"></div>';
383                         $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
384                         $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
385                         $s .= '<div class="clear"></div>';
386
387                         $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from statusnet that are no replies or repeated messages').'</label>';
388                         $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
389                         $s .= '<div class="clear"></div>';
390                         $s .= '</div>';
391
392                         $s .= '<label id="statusnet-import-label" for="statusnet-import">'.t('Import the remote timeline').'</label>';
393                         $s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
394                         $s .= '<div class="clear"></div>';
395 /*
396                         $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.t('Automatically create contacts').'</label>';
397                         $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
398                         $s .= '<div class="clear"></div>';
399 */
400                         $s .= '<div id="statusnet-disconnect-wrapper">';
401                         $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
402                         $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
403                         $s .= '</div><div class="clear"></div>';
404                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>'; 
405                 }
406         }
407         $s .= '</div><div class="clear"></div>';
408 }
409
410
411 function statusnet_post_local(&$a,&$b) {
412         if($b['edit'])
413                 return;
414
415         if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
416
417                 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
418                 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
419
420                 // if API is used, default to the chosen settings
421                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
422                         $statusnet_enable = 1;
423
424                 if(! $statusnet_enable)
425                         return;
426
427                 if(strlen($b['postopts']))
428                         $b['postopts'] .= ',';
429                 $b['postopts'] .= 'statusnet';
430         }
431 }
432
433 function statusnet_action($a, $uid, $pid, $action) {
434         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
435         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
436         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
437         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
438         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
439
440         $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
441
442         logger("statusnet_action '".$action."' ID: ".$pid, LOGGER_DATA);
443
444         switch ($action) {
445                 case "delete":
446                         $result = $connection->post("statuses/destroy/".$pid);
447                         break;
448                 case "like":
449                         $result = $connection->post("favorites/create/".$pid);
450                         break;
451                 case "unlike":
452                         $result = $connection->post("favorites/destroy/".$pid);
453                         break;
454         }
455         logger("statusnet_action '".$action."' send, result: " . print_r($result, true), LOGGER_DEBUG);
456 }
457
458 function statusnet_post_hook(&$a,&$b) {
459
460         /**
461          * Post to statusnet
462          */
463
464         if (!get_pconfig($b["uid"],'statusnet','import')) {
465                 if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
466                         return;
467         }
468
469         $api = get_pconfig($b["uid"], 'statusnet', 'baseapi');
470         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
471
472         if($b['parent'] != $b['id']) {
473                 logger("statusnet_post_hook: parameter ".print_r($b, true), LOGGER_DATA);
474
475                 // Looking if its a reply to a statusnet post
476                 $hostlength = strlen($hostname) + 2;
477                 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname."::") AND (substr($b["extid"], 0, $hostlength) != $hostname."::")
478                         AND (substr($b["thr-parent"], 0, $hostlength) != $hostname."::")) {
479                         logger("statusnet_post_hook: no statusnet post ".$b["parent"]);
480                         return;
481                 }
482
483                 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
484                         FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
485                         WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
486                         dbesc($b["thr-parent"]),
487                         intval($b["uid"]));
488
489                 if(!count($r)) {
490                         logger("statusnet_post_hook: no parent found ".$b["thr-parent"]);
491                         return;
492                 } else {
493                         $iscomment = true;
494                         $orig_post = $r[0];
495                 }
496
497                 $nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
498                 $nicknameplain = "@".$orig_post["contact_nick"];
499
500                 logger("statusnet_post_hook: comparing ".$nickname." and ".$nicknameplain." with ".$b["body"], LOGGER_DEBUG);
501                 if ((strpos($b["body"], $nickname) === false) AND (strpos($b["body"], $nicknameplain) === false))
502                         $b["body"] = $nickname." ".$b["body"];
503
504                 logger("statusnet_post_hook: parent found ".print_r($orig_post, true), LOGGER_DEBUG);
505         } else {
506                 $iscomment = false;
507
508                 if($b['private'] OR !strstr($b['postopts'],'statusnet'))
509                         return;
510         }
511
512         if (($b['verb'] == ACTIVITY_POST) AND $b['deleted'])
513                 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
514
515         if($b['verb'] == ACTIVITY_LIKE) {
516                 logger("statusnet_post_hook: parameter 2 ".substr($b["thr-parent"], $hostlength), LOGGER_DEBUG);
517                 if ($b['deleted'])
518                         statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
519                 else
520                         statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
521                 return;
522         }
523
524         if($b['deleted'] || ($b['created'] !== $b['edited']))
525                 return;
526
527         // if posts comes from statusnet don't send it back
528         if($b['app'] == "StatusNet")
529                 return;
530
531         logger('statusnet post invoked');
532
533         load_pconfig($b['uid'], 'statusnet');
534
535         $api     = get_pconfig($b['uid'], 'statusnet', 'baseapi');
536         $ckey    = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
537         $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
538         $otoken  = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
539         $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
540
541         if($ckey && $csecret && $otoken && $osecret) {
542
543                 // If it's a repeated message from statusnet then do a native retweet and exit
544                 if (statusnet_is_retweet($a, $b['uid'], $b['body']))
545                         return;
546
547                 require_once('include/bbcode.php');
548                 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
549                 $max_char = $dent->get_maxlength(); // max. length for a dent
550
551                 $tempfile = "";
552                 require_once("include/plaintext.php");
553                 require_once("include/network.php");
554                 $msgarr = plaintext($a, $b, $max_char, true);
555                 $msg = $msgarr["text"];
556
557                 if (($msg == "") AND isset($msgarr["title"]))
558                         $msg = shortenmsg($msgarr["title"], $max_char - 50);
559
560                 $image = "";
561
562                 if (isset($msgarr["url"])) {
563                         if ((strlen($msgarr["url"]) > 20) AND
564                                 ((strlen($msg." \n".$msgarr["url"]) > $max_char)))
565                                 $msg .= " \n".short_link($msgarr["url"]);
566                         else
567                                 $msg .= " \n".$msgarr["url"];
568                 } elseif (isset($msgarr["image"]))
569                         $image = $msgarr["image"];
570
571                 if ($image != "") {
572                         $img_str = fetch_url($image);
573                         $tempfile = tempnam(get_config("system","temppath"), "cache");
574                         file_put_contents($tempfile, $img_str);
575                         $postdata = array("status" => $msg, "media[]" => $tempfile);
576                 } else
577                         $postdata = array("status"=>$msg);
578
579                 // and now dent it :-)
580                 if(strlen($msg)) {
581
582                         if ($iscomment) {
583                                 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
584                                 logger('statusnet_post send reply '.print_r($postdata, true), LOGGER_DEBUG);
585                         }
586
587                         // New code that is able to post pictures
588                         require_once("addon/statusnet/codebird.php");
589                         $cb = \CodebirdSN\CodebirdSN::getInstance();
590                         $cb->setAPIEndpoint($api);
591                         $cb->setConsumerKey($ckey, $csecret);
592                         $cb->setToken($otoken, $osecret);
593                         $result = $cb->statuses_update($postdata);
594                         //$result = $dent->post('statuses/update', $postdata);
595                         logger('statusnet_post send, result: ' . print_r($result, true).
596                                 "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
597                         if ($result->error) {
598                                 logger('Send to StatusNet failed: "'.$result->error.'"');
599                         } elseif ($iscomment) {
600                                 logger('statusnet_post: Update extid '.$result->id." for post id ".$b['id']);
601                                 q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d",
602                                         dbesc($hostname."::".$result->id),
603                                         dbesc($result->text),
604                                         intval($b['id'])
605                                 );
606                         }
607                 }
608                 if ($tempfile != "")
609                         unlink($tempfile);
610         }
611 }
612
613 function statusnet_plugin_admin_post(&$a){
614
615         $sites = array();
616
617         foreach($_POST['sitename'] as $id=>$sitename){
618                 $sitename=trim($sitename);
619                 $apiurl=trim($_POST['apiurl'][$id]);
620                 if (! (substr($apiurl, -1)=='/'))
621                     $apiurl=$apiurl.'/';
622                 $secret=trim($_POST['secret'][$id]);
623                 $key=trim($_POST['key'][$id]);
624                 $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
625                 if ($sitename!="" &&
626                         $apiurl!="" &&
627                         $secret!="" &&
628                         $key!="" &&
629                         !x($_POST['delete'][$id])){
630
631                                 $sites[] = Array(
632                                         'sitename' => $sitename,
633                                         'apiurl' => $apiurl,
634                                         'consumersecret' => $secret,
635                                         'consumerkey' => $key,
636                                         'applicationname' => $applicationname
637                                 );
638                 }
639         }
640
641         $sites = set_config('statusnet','sites', $sites);
642
643 }
644
645 function statusnet_plugin_admin(&$a, &$o){
646
647         $sites = get_config('statusnet','sites');
648         $sitesform=array();
649         if (is_array($sites)){
650                 foreach($sites as $id=>$s){
651                         $sitesform[] = Array(
652                                 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
653                                 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29") ),
654                                 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
655                                 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
656                                 'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
657                                 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
658                         );
659                 }
660         }
661         /* empty form to add new site */
662         $id++;
663         $sitesform[] = Array(
664                 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
665                 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29") ),
666                 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
667                 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
668                 'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
669         );
670
671         $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
672         $o = replace_macros($t, array(
673                 '$submit' => t('Save Settings'),
674                 '$sites' => $sitesform,
675         ));
676 }
677
678 function statusnet_cron($a,$b) {
679         $last = get_config('statusnet','last_poll');
680
681         $poll_interval = intval(get_config('statusnet','poll_interval'));
682         if(! $poll_interval)
683                 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
684
685         if($last) {
686                 $next = $last + ($poll_interval * 60);
687                 if($next > time()) {
688                         logger('statusnet: poll intervall not reached');
689                         return;
690                 }
691         }
692         logger('statusnet: cron_start');
693
694         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
695         if(count($r)) {
696                 foreach($r as $rr) {
697                         logger('statusnet: fetching for user '.$rr['uid']);
698                         statusnet_fetchtimeline($a, $rr['uid']);
699                 }
700         }
701
702         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` = '1' ORDER BY RAND()");
703         if(count($r)) {
704                 foreach($r as $rr) {
705                         logger('statusnet: importing timeline from user '.$rr['uid']);
706                         statusnet_fetchhometimeline($a, $rr["uid"]);
707                 }
708         }
709
710         logger('statusnet: cron_end');
711
712         set_config('statusnet','last_poll', time());
713 }
714
715 function statusnet_fetchtimeline($a, $uid) {
716         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
717         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
718         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
719         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
720         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
721         $lastid  = get_pconfig($uid, 'statusnet', 'lastid');
722
723         require_once('mod/item.php');
724         require_once('include/items.php');
725
726         //  get the application name for the SN app
727         //  1st try personal config, then system config and fallback to the
728         //  hostname of the node if neither one is set.
729         $application_name  = get_pconfig( $uid, 'statusnet', 'application_name');
730         if ($application_name == "")
731                 $application_name  = get_config('statusnet', 'application_name');
732         if ($application_name == "")
733                 $application_name = $a->get_hostname();
734
735         $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
736
737         $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
738
739         $first_time = ($lastid == "");
740
741         if ($lastid <> "")
742                 $parameters["since_id"] = $lastid;
743
744         $items = $connection->get('statuses/user_timeline', $parameters);
745
746         if (!is_array($items))
747                 return;
748
749         $posts = array_reverse($items);
750
751         if (count($posts)) {
752             foreach ($posts as $post) {
753                 if ($post->id > $lastid)
754                         $lastid = $post->id;
755
756                 if ($first_time)
757                         continue;
758
759                 if ($post->source == "activity")
760                         continue;
761
762                 if (is_object($post->retweeted_status))
763                         continue;
764
765                 if ($post->in_reply_to_status_id != "")
766                         continue;
767
768                 if (!strpos($post->source, $application_name)) {
769                         $_SESSION["authenticated"] = true;
770                         $_SESSION["uid"] = $uid;
771
772                         unset($_REQUEST);
773                         $_REQUEST["type"] = "wall";
774                         $_REQUEST["api_source"] = true;
775                         $_REQUEST["profile_uid"] = $uid;
776                         $_REQUEST["source"] = "StatusNet";
777
778                         //$_REQUEST["date"] = $post->created_at;
779
780                         $_REQUEST["title"] = "";
781
782                         $_REQUEST["body"] = add_page_info_to_body($post->text, true);
783                         if (is_string($post->place->name))
784                                 $_REQUEST["location"] = $post->place->name;
785
786                         if (is_string($post->place->full_name))
787                                 $_REQUEST["location"] = $post->place->full_name;
788
789                         if (is_array($post->geo->coordinates))
790                                 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
791
792                         if (is_array($post->coordinates->coordinates))
793                                 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
794
795                         //print_r($_REQUEST);
796                         if ($_REQUEST["body"] != "") {
797                                 logger('statusnet: posting for user '.$uid);
798
799                                 item_post($a);
800                         }
801                 }
802             }
803         }
804         set_pconfig($uid, 'statusnet', 'lastid', $lastid);
805 }
806
807 function statusnet_address($contact) {
808         $hostname = normalise_link($contact->statusnet_profile_url);
809         $nickname = $contact->screen_name;
810
811         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
812
813         $address = $contact->screen_name."@".$hostname;
814
815         return($address);
816 }
817
818 function statusnet_fetch_contact($uid, $contact, $create_user) {
819         // Check if the unique contact is existing
820         // To-Do: only update once a while
821          $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
822                         dbesc(normalise_link($contact->statusnet_profile_url)));
823
824         if (count($r) == 0)
825                 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
826                         dbesc(normalise_link($contact->statusnet_profile_url)),
827                         dbesc($contact->name),
828                         dbesc($contact->screen_name),
829                         dbesc($contact->profile_image_url));
830         else
831                 q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
832                         dbesc($contact->name),
833                         dbesc($contact->screen_name),
834                         dbesc($contact->profile_image_url),
835                         dbesc(normalise_link($contact->statusnet_profile_url)));
836
837         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
838                 intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)));
839
840         if(!count($r) AND !$create_user)
841                 return(0);
842
843         if (count($r) AND ($r[0]["readonly"] OR $r[0]["blocked"])) {
844                 logger("statusnet_fetch_contact: Contact '".$r[0]["nick"]."' is blocked or readonly.", LOGGER_DEBUG);
845                 return(-1);
846         }
847
848         if(!count($r)) {
849                 // create contact record
850                 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
851                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
852                                         `writable`, `blocked`, `readonly`, `pending` )
853                                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
854                         intval($uid),
855                         dbesc(datetime_convert()),
856                         dbesc($contact->statusnet_profile_url),
857                         dbesc(normalise_link($contact->statusnet_profile_url)),
858                         dbesc(statusnet_address($contact)),
859                         dbesc(normalise_link($contact->statusnet_profile_url)),
860                         dbesc(''),
861                         dbesc(''),
862                         dbesc($contact->name),
863                         dbesc($contact->screen_name),
864                         dbesc($contact->profile_image_url),
865                         dbesc(NETWORK_STATUSNET),
866                         intval(CONTACT_IS_FRIEND),
867                         intval(1),
868                         intval(1)
869                 );
870
871                 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d LIMIT 1",
872                         dbesc($contact->statusnet_profile_url),
873                         intval($uid)
874                         );
875
876                 if(! count($r))
877                         return(false);
878
879                 $contact_id  = $r[0]['id'];
880
881                 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
882                         intval($uid)
883                 );
884
885                 if($g && intval($g[0]['def_gid'])) {
886                         require_once('include/group.php');
887                         group_add_member($uid,'',$contact_id,$g[0]['def_gid']);
888                 }
889
890                 require_once("Photo.php");
891
892                 $photos = import_profile_photo($contact->profile_image_url,$uid,$contact_id);
893
894                 q("UPDATE `contact` SET `photo` = '%s',
895                                         `thumb` = '%s',
896                                         `micro` = '%s',
897                                         `name-date` = '%s',
898                                         `uri-date` = '%s',
899                                         `avatar-date` = '%s'
900                                 WHERE `id` = %d",
901                         dbesc($photos[0]),
902                         dbesc($photos[1]),
903                         dbesc($photos[2]),
904                         dbesc(datetime_convert()),
905                         dbesc(datetime_convert()),
906                         dbesc(datetime_convert()),
907                         intval($contact_id)
908                 );
909
910         } else {
911                 // update profile photos once every two weeks as we have no notification of when they change.
912
913                 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
914                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('','','now -12 hours'));
915
916                 // check that we have all the photos, this has been known to fail on occasion
917
918                 if((! $r[0]['photo']) || (! $r[0]['thumb']) || (! $r[0]['micro']) || ($update_photo)) {
919
920                         logger("statusnet_fetch_contact: Updating contact ".$contact->screen_name, LOGGER_DEBUG);
921
922                         require_once("Photo.php");
923
924                         $photos = import_profile_photo($contact->profile_image_url, $uid, $r[0]['id']);
925
926                         q("UPDATE `contact` SET `photo` = '%s',
927                                                 `thumb` = '%s',
928                                                 `micro` = '%s',
929                                                 `name-date` = '%s',
930                                                 `uri-date` = '%s',
931                                                 `avatar-date` = '%s',
932                                                 `url` = '%s',
933                                                 `nurl` = '%s',
934                                                 `addr` = '%s',
935                                                 `name` = '%s',
936                                                 `nick` = '%s'
937                                         WHERE `id` = %d",
938                                 dbesc($photos[0]),
939                                 dbesc($photos[1]),
940                                 dbesc($photos[2]),
941                                 dbesc(datetime_convert()),
942                                 dbesc(datetime_convert()),
943                                 dbesc(datetime_convert()),
944                                 dbesc($contact->statusnet_profile_url),
945                                 dbesc(normalise_link($contact->statusnet_profile_url)),
946                                 dbesc(statusnet_address($contact)),
947                                 dbesc($contact->name),
948                                 dbesc($contact->screen_name),
949                                 intval($r[0]['id'])
950                         );
951                 }
952         }
953
954         return($r[0]["id"]);
955 }
956
957 function statusnet_fetchuser($a, $uid, $screen_name = "", $user_id = "") {
958         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
959         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
960         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
961         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
962         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
963
964         require_once("addon/statusnet/codebird.php");
965
966         $cb = \Codebird\Codebird::getInstance();
967         $cb->setConsumerKey($ckey, $csecret);
968         $cb->setToken($otoken, $osecret);
969
970         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
971                 intval($uid));
972
973         if(count($r)) {
974                 $self = $r[0];
975         } else
976                 return;
977
978         $parameters = array();
979
980         if ($screen_name != "")
981                 $parameters["screen_name"] = $screen_name;
982
983         if ($user_id != "")
984                 $parameters["user_id"] = $user_id;
985
986         // Fetching user data
987         $user = $cb->users_show($parameters);
988
989         if (!is_object($user))
990                 return;
991
992         $contact_id = statusnet_fetch_contact($uid, $user, true);
993
994         return $contact_id;
995 }
996
997 function statusnet_createpost($a, $uid, $post, $self, $create_user, $only_existing_contact) {
998
999         require_once("include/html2bbcode.php");
1000
1001         $api = get_pconfig($uid, 'statusnet', 'baseapi');
1002         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1003
1004         $postarray = array();
1005         $postarray['network'] = NETWORK_STATUSNET;
1006         $postarray['gravity'] = 0;
1007         $postarray['uid'] = $uid;
1008         $postarray['wall'] = 0;
1009         $postarray['uri'] = $hostname."::".$post->id;
1010
1011         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1012                         dbesc($postarray['uri']),
1013                         intval($uid)
1014                 );
1015
1016         if (count($r))
1017                 return(array());
1018
1019         $contactid = 0;
1020
1021         if ($post->in_reply_to_status_id != "") {
1022
1023                 $parent = $hostname."::".$post->in_reply_to_status_id;
1024
1025                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1026                                 dbesc($parent),
1027                                 intval($uid)
1028                         );
1029                 if (count($r)) {
1030                         $postarray['thr-parent'] = $r[0]["uri"];
1031                         $postarray['parent-uri'] = $r[0]["parent-uri"];
1032                 } else {
1033                         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1034                                         dbesc($parent),
1035                                         intval($uid)
1036                                 );
1037                         if (count($r)) {
1038                                 $postarray['thr-parent'] = $r[0]['uri'];
1039                                 $postarray['parent-uri'] = $r[0]['parent-uri'];
1040                         } else {
1041                                 $postarray['thr-parent'] = $postarray['uri'];
1042                                 $postarray['parent-uri'] = $postarray['uri'];
1043                         }
1044                 }
1045
1046                 // Is it me?
1047                 $own_url = get_pconfig($uid, 'statusnet', 'own_url');
1048
1049                 if ($post->user->id == $own_url) {
1050                         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1051                                 intval($uid));
1052
1053                         if(count($r)) {
1054                                 $contactid = $r[0]["id"];
1055
1056                                 $postarray['owner-name'] =  $r[0]["name"];
1057                                 $postarray['owner-link'] = $r[0]["url"];
1058                                 $postarray['owner-avatar'] =  $r[0]["photo"];
1059                         } else
1060                                 return(array());
1061                 }
1062         } else
1063                 $postarray['parent-uri'] = $postarray['uri'];
1064
1065         if ($contactid == 0) {
1066                 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1067                 $postarray['owner-name'] = $post->user->name;
1068                 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1069                 $postarray['owner-avatar'] = $post->user->profile_image_url;
1070         }
1071         if(($contactid == 0) AND !$only_existing_contact)
1072                 $contactid = $self['id'];
1073         elseif ($contactid <= 0)
1074                 return(array());
1075
1076         $postarray['contact-id'] = $contactid;
1077
1078         $postarray['verb'] = ACTIVITY_POST;
1079         $postarray['author-name'] = $postarray['owner-name'];
1080         $postarray['author-link'] = $postarray['owner-link'];
1081         $postarray['author-avatar'] = $postarray['owner-avatar'];
1082
1083         // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1084         $hostname = str_replace("/api/", "/notice/", get_pconfig($uid, 'statusnet', 'baseapi'));
1085
1086         $postarray['plink'] = $hostname.$post->id;
1087         $postarray['app'] = strip_tags($post->source);
1088
1089         if ($post->user->protected) {
1090                 $postarray['private'] = 1;
1091                 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1092         }
1093
1094         $postarray['body'] = html2bbcode($post->statusnet_html);
1095
1096         $converted = statusnet_convertmsg($a, $postarray['body'], false);
1097         $postarray['body'] = $converted["body"];
1098         $postarray['tag'] = $converted["tags"];
1099
1100         $postarray['created'] = datetime_convert('UTC','UTC',$post->created_at);
1101         $postarray['edited'] = datetime_convert('UTC','UTC',$post->created_at);
1102
1103         if (is_string($post->place->name))
1104                 $postarray["location"] = $post->place->name;
1105
1106         if (is_string($post->place->full_name))
1107                 $postarray["location"] = $post->place->full_name;
1108
1109         if (is_array($post->geo->coordinates))
1110                 $postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
1111
1112         if (is_array($post->coordinates->coordinates))
1113                 $postarray["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
1114
1115         if (is_object($post->retweeted_status)) {
1116                 $postarray['body'] = html2bbcode($post->retweeted_status->statusnet_html);
1117
1118                 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1119                 $postarray['body'] = $converted["body"];
1120                 $postarray['tag'] = $converted["tags"];
1121
1122                 statusnet_fetch_contact($uid, $post->retweeted_status->user, false);
1123
1124                 // Let retweets look like wall-to-wall posts
1125                 $postarray['author-name'] = $post->retweeted_status->user->name;
1126                 $postarray['author-link'] = $post->retweeted_status->user->statusnet_profile_url;
1127                 $postarray['author-avatar'] = $post->retweeted_status->user->profile_image_url;
1128         }
1129         return($postarray);
1130 }
1131
1132 function statusnet_checknotification($a, $uid, $own_url, $top_item, $postarray) {
1133
1134         $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1135                         intval($uid)
1136                 );
1137
1138         if(!count($user))
1139                 return;
1140
1141         // Is it me?
1142         if (link_compare($user[0]["url"], $postarray['author-link']))
1143                 return;
1144
1145         $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1146                         intval($uid),
1147                         dbesc($own_url)
1148                 );
1149
1150         if(!count($own_user))
1151                 return;
1152
1153         // Is it me from statusnet?
1154         if (link_compare($own_user[0]["url"], $postarray['author-link']))
1155                 return;
1156
1157         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1158                         dbesc($postarray['parent-uri']),
1159                         intval($uid)
1160                         );
1161
1162         if(count($myconv)) {
1163
1164                 foreach($myconv as $conv) {
1165                         // now if we find a match, it means we're in this conversation
1166
1167                         if(!link_compare($conv['author-link'],$user[0]["url"]) AND !link_compare($conv['author-link'],$own_user[0]["url"]))
1168                                 continue;
1169
1170                         require_once('include/enotify.php');
1171
1172                         $conv_parent = $conv['parent'];
1173
1174                         notification(array(
1175                                 'type'         => NOTIFY_COMMENT,
1176                                 'notify_flags' => $user[0]['notify-flags'],
1177                                 'language'     => $user[0]['language'],
1178                                 'to_name'      => $user[0]['username'],
1179                                 'to_email'     => $user[0]['email'],
1180                                 'uid'          => $user[0]['uid'],
1181                                 'item'         => $postarray,
1182                                 'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1183                                 'source_name'  => $postarray['author-name'],
1184                                 'source_link'  => $postarray['author-link'],
1185                                 'source_photo' => $postarray['author-avatar'],
1186                                 'verb'         => ACTIVITY_POST,
1187                                 'otype'        => 'item',
1188                                 'parent'       => $conv_parent,
1189                         ));
1190
1191                         // only send one notification
1192                         break;
1193                 }
1194         }
1195 }
1196
1197 function statusnet_fetchhometimeline($a, $uid) {
1198         $conversations = array();
1199
1200         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
1201         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1202         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
1203         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
1204         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1205         $create_user = get_pconfig($uid, 'statusnet', 'create_user');
1206
1207         // "create_user" is deactivated, since currently you cannot add users manually by now
1208         $create_user = true;
1209
1210         logger("statusnet_fetchhometimeline: Fetching for user ".$uid, LOGGER_DEBUG);
1211
1212         require_once('library/twitteroauth.php');
1213         require_once('include/items.php');
1214
1215         $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1216
1217         $own_contact = statusnet_fetch_own_contact($a, $uid);
1218
1219         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1220                 intval($own_contact),
1221                 intval($uid));
1222
1223         if(count($r)) {
1224                 $nick = $r[0]["nick"];
1225         } else {
1226                 logger("statusnet_fetchhometimeline: Own statusnet contact not found for user ".$uid, LOGGER_DEBUG);
1227                 return;
1228         }
1229
1230         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1231                 intval($uid));
1232
1233         if(count($r)) {
1234                 $self = $r[0];
1235         } else {
1236                 logger("statusnet_fetchhometimeline: Own contact not found for user ".$uid, LOGGER_DEBUG);
1237                 return;
1238         }
1239
1240         $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1241                 intval($uid));
1242         if(!count($u)) {
1243                 logger("statusnet_fetchhometimeline: Own user not found for user ".$uid, LOGGER_DEBUG);
1244                 return;
1245         }
1246
1247         $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
1248         //$parameters["count"] = 200;
1249
1250
1251         // Fetching timeline
1252         $lastid  = get_pconfig($uid, 'statusnet', 'lasthometimelineid');
1253         //$lastid = 1;
1254
1255         $first_time = ($lastid == "");
1256
1257         if ($lastid <> "")
1258                 $parameters["since_id"] = $lastid;
1259
1260         $items = $connection->get('statuses/home_timeline', $parameters);
1261
1262         if (!is_array($items)) {
1263                 logger("statusnet_fetchhometimeline: Error fetching home timeline: ".print_r($items, true), LOGGER_DEBUG);
1264                 return;
1265         }
1266
1267         $posts = array_reverse($items);
1268
1269         logger("statusnet_fetchhometimeline: Fetching timeline for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1270
1271         if (count($posts)) {
1272                 foreach ($posts as $post) {
1273
1274                         if ($post->id > $lastid)
1275                                 $lastid = $post->id;
1276
1277                         if ($first_time)
1278                                 continue;
1279
1280                         if (isset($post->statusnet_conversation_id)) {
1281                                 if (!isset($conversations[$post->statusnet_conversation_id])) {
1282                                         statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1283                                         $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1284                                 }
1285                         } else {
1286                                 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1287
1288                                 if (trim($postarray['body']) == "")
1289                                         continue;
1290
1291                                 $item = item_store($postarray);
1292
1293                                 logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted home timeline item '.$item);
1294
1295                                 if ($item != 0)
1296                                         statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1297                         }
1298
1299                 }
1300         }
1301         set_pconfig($uid, 'statusnet', 'lasthometimelineid', $lastid);
1302
1303         // Fetching mentions
1304         $lastid  = get_pconfig($uid, 'statusnet', 'lastmentionid');
1305         $first_time = ($lastid == "");
1306
1307         if ($lastid <> "")
1308                 $parameters["since_id"] = $lastid;
1309
1310         $items = $connection->get('statuses/mentions_timeline', $parameters);
1311
1312         if (!is_array($items)) {
1313                 logger("statusnet_fetchhometimeline: Error fetching mentions: ".print_r($items, true), LOGGER_DEBUG);
1314                 return;
1315         }
1316
1317         $posts = array_reverse($items);
1318
1319         logger("statusnet_fetchhometimeline: Fetching mentions for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1320
1321         if (count($posts)) {
1322                 foreach ($posts as $post) {
1323                         if ($post->id > $lastid)
1324                                 $lastid = $post->id;
1325
1326                         if ($first_time)
1327                                 continue;
1328
1329                         $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1330
1331                         if (isset($post->statusnet_conversation_id)) {
1332                                 if (!isset($conversations[$post->statusnet_conversation_id])) {
1333                                         statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1334                                         $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1335                                 }
1336                         } else {
1337                                 if (trim($postarray['body']) != "") {
1338                                         continue;
1339
1340                                         $item = item_store($postarray);
1341
1342                                         logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted mention timeline item '.$item);
1343                                 }
1344                         }
1345
1346                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1347                                 dbesc($postarray['uri']),
1348                                 intval($uid)
1349                         );
1350                         if (count($r))
1351                                 $item = $r[0]['id'];
1352
1353                         if ($item != 0) {
1354                                 require_once('include/enotify.php');
1355                                 notification(array(
1356                                         'type'         => NOTIFY_TAGSELF,
1357                                         'notify_flags' => $u[0]['notify-flags'],
1358                                         'language'     => $u[0]['language'],
1359                                         'to_name'      => $u[0]['username'],
1360                                         'to_email'     => $u[0]['email'],
1361                                         'uid'          => $u[0]['uid'],
1362                                         'item'         => $postarray,
1363                                         'link'         => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item,
1364                                         'source_name'  => $postarray['author-name'],
1365                                         'source_link'  => $postarray['author-link'],
1366                                         'source_photo' => $postarray['author-avatar'],
1367                                         'verb'         => ACTIVITY_TAG,
1368                                         'otype'        => 'item'
1369                                 ));
1370                         }
1371                 }
1372         }
1373
1374         set_pconfig($uid, 'statusnet', 'lastmentionid', $lastid);
1375 }
1376
1377 function statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $conversation) {
1378         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
1379         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1380         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
1381         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
1382         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1383
1384         require_once('library/twitteroauth.php');
1385
1386         $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1387
1388         $parameters["count"] = 200;
1389
1390         $items = $connection->get('statusnet/conversation/'.$conversation, $parameters);
1391         if (is_array($items)) {
1392                 $posts = array_reverse($items);
1393
1394                 foreach($posts AS $post) {
1395                         $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1396
1397                         if (trim($postarray['body']) == "")
1398                                 continue;
1399
1400                         //print_r($postarray);
1401                         $item = item_store($postarray);
1402
1403                         logger('statusnet_complete_conversation: User '.$self["nick"].' posted home timeline item '.$item);
1404
1405                         if ($item != 0)
1406                                 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1407                 }
1408         }
1409 }
1410
1411 function statusnet_convertmsg($a, $body, $no_tags = false) {
1412
1413         require_once("include/oembed.php");
1414         require_once("include/items.php");
1415         require_once("include/network.php");
1416
1417         $URLSearchString = "^\[\]";
1418         $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body,$matches,PREG_SET_ORDER);
1419
1420         $footer = "";
1421         $footerurl = "";
1422         $footerlink = "";
1423         $type = "";
1424
1425         if ($links) {
1426                 foreach ($matches AS $match) {
1427                         $search = "[url=".$match[1]."]".$match[2]."[/url]";
1428
1429                         $expanded_url = original_url($match[1]);
1430
1431                         $oembed_data = oembed_fetch_url($expanded_url, true);
1432 print_r($oembed_data);
1433                         if ($type == "")
1434                                 $type = $oembed_data->type;
1435                         if ($oembed_data->type == "video") {
1436                                 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1437                                 $type = $oembed_data->type;
1438                                 $footerurl = $expanded_url;
1439                                 $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
1440
1441                                 $body = str_replace($search, $footerlink, $body);
1442                         } elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia)
1443                                 $body = str_replace($search, "[url=".$expanded_url."][img]".$oembed_data->url."[/img][/url]", $body);
1444                         elseif ($oembed_data->type != "link")
1445                                 $body = str_replace($search,  "[url=".$expanded_url."]".$expanded_url."[/url]", $body);
1446                         else {
1447                                 $img_str = fetch_url($expanded_url, true, $redirects, 4);
1448
1449                                 $tempfile = tempnam(get_config("system","temppath"), "cache");
1450                                 file_put_contents($tempfile, $img_str);
1451                                 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1452                                 unlink($tempfile);
1453
1454                                 if (substr($mime, 0, 6) == "image/") {
1455                                         $type = "photo";
1456                                         $body = str_replace($search, "[img]".$expanded_url."[/img]", $body);
1457                                 } else {
1458                                         $type = $oembed_data->type;
1459                                         $footerurl = $expanded_url;
1460                                         $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
1461
1462                                         $body = str_replace($search, $footerlink, $body);
1463                                 }
1464                         }
1465                 }
1466
1467                 if ($footerurl != "")
1468                         $footer = add_page_info($footerurl);
1469
1470                 if (($footerlink != "") AND (trim($footer) != "")) {
1471                         $removedlink = trim(str_replace($footerlink, "", $body));
1472
1473                         if (strstr($body, $removedlink))
1474                                 $body = $removedlink;
1475
1476                         $body .= $footer;
1477                 }
1478         }
1479
1480         if ($no_tags)
1481                 return(array("body" => $body, "tags" => ""));
1482
1483         $str_tags = '';
1484
1485         $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$body,$matches,PREG_SET_ORDER);
1486         if($cnt) {
1487                 foreach($matches as $mtch) {
1488                         if(strlen($str_tags))
1489                                 $str_tags .= ',';
1490
1491                         if ($mtch[1] == "#") {
1492                                 // Replacing the hash tags that are directed to the statusnet server with internal links
1493                                 $snhash = "#[url=".$mtch[2]."]".$mtch[3]."[/url]";
1494                                 $frdchash = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($mtch[3]).']'.$mtch[3].'[/url]';
1495                                 $body = str_replace($snhash, $frdchash, $body);
1496
1497                                 $str_tags .= $frdchash;
1498                         } else
1499                                 $str_tags .= "@[url=".$mtch[2]."]".$mtch[3]."[/url]";
1500                                 // To-Do:
1501                                 // There is a problem with links with to statusnet groups, so these links are stored with "@" like friendica groups
1502                                 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1503                 }
1504         }
1505
1506         return(array("body"=>$body, "tags"=>$str_tags));
1507
1508 }
1509
1510 function statusnet_fetch_own_contact($a, $uid) {
1511         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
1512         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1513         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
1514         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
1515         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1516         $own_url = get_pconfig($uid, 'statusnet', 'own_url');
1517
1518         $contact_id = 0;
1519
1520         if ($own_url == "") {
1521                 require_once('library/twitteroauth.php');
1522
1523                 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1524
1525                 // Fetching user data
1526                 $user = $connection->get('account/verify_credentials');
1527
1528                 set_pconfig($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
1529
1530                 $contact_id = statusnet_fetch_contact($uid, $user, true);
1531
1532         } else {
1533                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1534                         intval($uid), dbesc($own_url));
1535                 if(count($r))
1536                         $contact_id = $r[0]["id"];
1537                 else
1538                         del_pconfig($uid, 'statusnet', 'own_url');
1539
1540         }
1541         return($contact_id);
1542 }
1543
1544 function statusnet_is_retweet($a, $uid, $body) {
1545         $body = trim($body);
1546
1547         // Skip if it isn't a pure repeated messages
1548         // Does it start with a share?
1549         if (strpos($body, "[share") > 0)
1550                 return(false);
1551
1552         // Does it end with a share?
1553         if (strlen($body) > (strrpos($body, "[/share]") + 8))
1554                 return(false);
1555
1556         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1557         // Skip if there is no shared message in there
1558         if ($body == $attributes)
1559                 return(false);
1560
1561         $link = "";
1562         preg_match("/link='(.*?)'/ism", $attributes, $matches);
1563         if ($matches[1] != "")
1564                 $link = $matches[1];
1565
1566         preg_match('/link="(.*?)"/ism', $attributes, $matches);
1567         if ($matches[1] != "")
1568                 $link = $matches[1];
1569
1570         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
1571         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1572         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
1573         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
1574         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1575         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1576
1577         $id = preg_replace("=https?://".$hostname."/notice/(.*)=ism", "$1", $link);
1578
1579         if ($id == $link)
1580                 return(false);
1581
1582         logger('statusnet_is_retweet: Retweeting id '.$id.' for user '.$uid, LOGGER_DEBUG);
1583
1584         $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1585
1586         $result = $connection->post('statuses/retweet/'.$id);
1587
1588         logger('statusnet_is_retweet: result '.print_r($result, true), LOGGER_DEBUG);
1589         return(isset($result->id));
1590 }