]> git.mxchange.org Git - friendica-addons.git/blob - statusnet/statusnet.php
appnet, statusnet: Posts from unknown contacts weren't posted
[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_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                 // Don't create accounts of people who just comment something
1063                 $create_user = false;
1064         } else
1065                 $postarray['parent-uri'] = $postarray['uri'];
1066
1067         if ($contactid == 0) {
1068                 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1069                 $postarray['owner-name'] = $post->user->name;
1070                 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1071                 $postarray['owner-avatar'] = $post->user->profile_image_url;
1072         }
1073         if(($contactid == 0) AND !$only_existing_contact)
1074                 $contactid = $self['id'];
1075         elseif ($contactid <= 0)
1076                 return(array());
1077
1078         $postarray['contact-id'] = $contactid;
1079
1080         $postarray['verb'] = ACTIVITY_POST;
1081         $postarray['author-name'] = $postarray['owner-name'];
1082         $postarray['author-link'] = $postarray['owner-link'];
1083         $postarray['author-avatar'] = $postarray['owner-avatar'];
1084
1085         // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1086         $hostname = str_replace("/api/", "/notice/", get_pconfig($uid, 'statusnet', 'baseapi'));
1087
1088         $postarray['plink'] = $hostname.$post->id;
1089         $postarray['app'] = strip_tags($post->source);
1090
1091         if ($post->user->protected) {
1092                 $postarray['private'] = 1;
1093                 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1094         }
1095
1096         $postarray['body'] = html2bbcode($post->statusnet_html);
1097
1098         $converted = statusnet_convertmsg($a, $postarray['body'], false);
1099         $postarray['body'] = $converted["body"];
1100         $postarray['tag'] = $converted["tags"];
1101
1102         $postarray['created'] = datetime_convert('UTC','UTC',$post->created_at);
1103         $postarray['edited'] = datetime_convert('UTC','UTC',$post->created_at);
1104
1105         if (is_string($post->place->name))
1106                 $postarray["location"] = $post->place->name;
1107
1108         if (is_string($post->place->full_name))
1109                 $postarray["location"] = $post->place->full_name;
1110
1111         if (is_array($post->geo->coordinates))
1112                 $postarray["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
1113
1114         if (is_array($post->coordinates->coordinates))
1115                 $postarray["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
1116
1117         if (is_object($post->retweeted_status)) {
1118                 $postarray['body'] = html2bbcode($post->retweeted_status->statusnet_html);
1119
1120                 $converted = statusnet_convertmsg($a, $postarray['body'], false);
1121                 $postarray['body'] = $converted["body"];
1122                 $postarray['tag'] = $converted["tags"];
1123
1124                 statusnet_fetch_contact($uid, $post->retweeted_status->user, false);
1125
1126                 // Let retweets look like wall-to-wall posts
1127                 $postarray['author-name'] = $post->retweeted_status->user->name;
1128                 $postarray['author-link'] = $post->retweeted_status->user->statusnet_profile_url;
1129                 $postarray['author-avatar'] = $post->retweeted_status->user->profile_image_url;
1130         }
1131         return($postarray);
1132 }
1133
1134 function statusnet_checknotification($a, $uid, $own_url, $top_item, $postarray) {
1135
1136         $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1137                         intval($uid)
1138                 );
1139
1140         if(!count($user))
1141                 return;
1142
1143         // Is it me?
1144         if (link_compare($user[0]["url"], $postarray['author-link']))
1145                 return;
1146
1147         $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1148                         intval($uid),
1149                         dbesc($own_url)
1150                 );
1151
1152         if(!count($own_user))
1153                 return;
1154
1155         // Is it me from statusnet?
1156         if (link_compare($own_user[0]["url"], $postarray['author-link']))
1157                 return;
1158
1159         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1160                         dbesc($postarray['parent-uri']),
1161                         intval($uid)
1162                         );
1163
1164         if(count($myconv)) {
1165
1166                 foreach($myconv as $conv) {
1167                         // now if we find a match, it means we're in this conversation
1168
1169                         if(!link_compare($conv['author-link'],$user[0]["url"]) AND !link_compare($conv['author-link'],$own_user[0]["url"]))
1170                                 continue;
1171
1172                         require_once('include/enotify.php');
1173
1174                         $conv_parent = $conv['parent'];
1175
1176                         notification(array(
1177                                 'type'         => NOTIFY_COMMENT,
1178                                 'notify_flags' => $user[0]['notify-flags'],
1179                                 'language'     => $user[0]['language'],
1180                                 'to_name'      => $user[0]['username'],
1181                                 'to_email'     => $user[0]['email'],
1182                                 'uid'          => $user[0]['uid'],
1183                                 'item'         => $postarray,
1184                                 'link'             => $a->get_baseurl() . '/display/' . $user[0]['nickname'] . '/' . $top_item,
1185                                 'source_name'  => $postarray['author-name'],
1186                                 'source_link'  => $postarray['author-link'],
1187                                 'source_photo' => $postarray['author-avatar'],
1188                                 'verb'         => ACTIVITY_POST,
1189                                 'otype'        => 'item',
1190                                 'parent'       => $conv_parent,
1191                         ));
1192
1193                         // only send one notification
1194                         break;
1195                 }
1196         }
1197 }
1198
1199 function statusnet_fetchhometimeline($a, $uid) {
1200         $conversations = array();
1201
1202         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
1203         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1204         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
1205         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
1206         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1207         $create_user = get_pconfig($uid, 'statusnet', 'create_user');
1208
1209         // "create_user" is deactivated, since currently you cannot add users manually by now
1210         $create_user = true;
1211
1212         logger("statusnet_fetchhometimeline: Fetching for user ".$uid, LOGGER_DEBUG);
1213
1214         require_once('library/twitteroauth.php');
1215         require_once('include/items.php');
1216
1217         $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1218
1219         $own_contact = statusnet_fetch_own_contact($a, $uid);
1220
1221         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1222                 intval($own_contact),
1223                 intval($uid));
1224
1225         if(count($r)) {
1226                 $nick = $r[0]["nick"];
1227         } else {
1228                 logger("statusnet_fetchhometimeline: Own statusnet contact not found for user ".$uid, LOGGER_DEBUG);
1229                 return;
1230         }
1231
1232         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1233                 intval($uid));
1234
1235         if(count($r)) {
1236                 $self = $r[0];
1237         } else {
1238                 logger("statusnet_fetchhometimeline: Own contact not found for user ".$uid, LOGGER_DEBUG);
1239                 return;
1240         }
1241
1242         $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1243                 intval($uid));
1244         if(!count($u)) {
1245                 logger("statusnet_fetchhometimeline: Own user not found for user ".$uid, LOGGER_DEBUG);
1246                 return;
1247         }
1248
1249         $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
1250         //$parameters["count"] = 200;
1251
1252
1253         // Fetching timeline
1254         $lastid  = get_pconfig($uid, 'statusnet', 'lasthometimelineid');
1255         //$lastid = 1;
1256
1257         $first_time = ($lastid == "");
1258
1259         if ($lastid <> "")
1260                 $parameters["since_id"] = $lastid;
1261
1262         $items = $connection->get('statuses/home_timeline', $parameters);
1263
1264         if (!is_array($items)) {
1265                 logger("statusnet_fetchhometimeline: Error fetching home timeline: ".print_r($items, true), LOGGER_DEBUG);
1266                 return;
1267         }
1268
1269         $posts = array_reverse($items);
1270
1271         logger("statusnet_fetchhometimeline: Fetching timeline for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1272
1273         if (count($posts)) {
1274                 foreach ($posts as $post) {
1275
1276                         if ($post->id > $lastid)
1277                                 $lastid = $post->id;
1278
1279                         if ($first_time)
1280                                 continue;
1281
1282                         if (isset($post->statusnet_conversation_id)) {
1283                                 if (!isset($conversations[$post->statusnet_conversation_id])) {
1284                                         statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1285                                         $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1286                                 }
1287                         } else {
1288                                 $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1289
1290                                 if (trim($postarray['body']) == "")
1291                                         continue;
1292
1293                                 $item = item_store($postarray);
1294
1295                                 logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted home timeline item '.$item);
1296
1297                                 if ($item != 0)
1298                                         statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1299                         }
1300
1301                 }
1302         }
1303         set_pconfig($uid, 'statusnet', 'lasthometimelineid', $lastid);
1304
1305         // Fetching mentions
1306         $lastid  = get_pconfig($uid, 'statusnet', 'lastmentionid');
1307         $first_time = ($lastid == "");
1308
1309         if ($lastid <> "")
1310                 $parameters["since_id"] = $lastid;
1311
1312         $items = $connection->get('statuses/mentions_timeline', $parameters);
1313
1314         if (!is_array($items)) {
1315                 logger("statusnet_fetchhometimeline: Error fetching mentions: ".print_r($items, true), LOGGER_DEBUG);
1316                 return;
1317         }
1318
1319         $posts = array_reverse($items);
1320
1321         logger("statusnet_fetchhometimeline: Fetching mentions for user ".$uid." ".sizeof($posts)." items", LOGGER_DEBUG);
1322
1323         if (count($posts)) {
1324                 foreach ($posts as $post) {
1325                         if ($post->id > $lastid)
1326                                 $lastid = $post->id;
1327
1328                         if ($first_time)
1329                                 continue;
1330
1331                         $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1332
1333                         if (isset($post->statusnet_conversation_id)) {
1334                                 if (!isset($conversations[$post->statusnet_conversation_id])) {
1335                                         statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1336                                         $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1337                                 }
1338                         } else {
1339                                 if (trim($postarray['body']) != "") {
1340                                         continue;
1341
1342                                         $item = item_store($postarray);
1343
1344                                         logger('statusnet_fetchhometimeline: User '.$self["nick"].' posted mention timeline item '.$item);
1345                                 }
1346                         }
1347
1348                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1349                                 dbesc($postarray['uri']),
1350                                 intval($uid)
1351                         );
1352                         if (count($r))
1353                                 $item = $r[0]['id'];
1354
1355                         if ($item != 0) {
1356                                 require_once('include/enotify.php');
1357                                 notification(array(
1358                                         'type'         => NOTIFY_TAGSELF,
1359                                         'notify_flags' => $u[0]['notify-flags'],
1360                                         'language'     => $u[0]['language'],
1361                                         'to_name'      => $u[0]['username'],
1362                                         'to_email'     => $u[0]['email'],
1363                                         'uid'          => $u[0]['uid'],
1364                                         'item'         => $postarray,
1365                                         'link'         => $a->get_baseurl() . '/display/' . $u[0]['nickname'] . '/' . $item,
1366                                         'source_name'  => $postarray['author-name'],
1367                                         'source_link'  => $postarray['author-link'],
1368                                         'source_photo' => $postarray['author-avatar'],
1369                                         'verb'         => ACTIVITY_TAG,
1370                                         'otype'        => 'item'
1371                                 ));
1372                         }
1373                 }
1374         }
1375
1376         set_pconfig($uid, 'statusnet', 'lastmentionid', $lastid);
1377 }
1378
1379 function statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $conversation) {
1380         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
1381         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1382         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
1383         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
1384         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1385
1386         require_once('library/twitteroauth.php');
1387
1388         $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1389
1390         $parameters["count"] = 200;
1391
1392         $items = $connection->get('statusnet/conversation/'.$conversation, $parameters);
1393         if (is_array($items)) {
1394                 $posts = array_reverse($items);
1395
1396                 foreach($posts AS $post) {
1397                         $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1398
1399                         if (trim($postarray['body']) == "")
1400                                 continue;
1401
1402                         //print_r($postarray);
1403                         $item = item_store($postarray);
1404
1405                         logger('statusnet_complete_conversation: User '.$self["nick"].' posted home timeline item '.$item);
1406
1407                         if ($item != 0)
1408                                 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1409                 }
1410         }
1411 }
1412
1413 function statusnet_convertmsg($a, $body, $no_tags = false) {
1414
1415         require_once("include/oembed.php");
1416         require_once("include/items.php");
1417         require_once("include/network.php");
1418
1419         $URLSearchString = "^\[\]";
1420         $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body,$matches,PREG_SET_ORDER);
1421
1422         $footer = "";
1423         $footerurl = "";
1424         $footerlink = "";
1425         $type = "";
1426
1427         if ($links) {
1428                 foreach ($matches AS $match) {
1429                         $search = "[url=".$match[1]."]".$match[2]."[/url]";
1430
1431                         $expanded_url = original_url($match[1]);
1432
1433                         $oembed_data = oembed_fetch_url($expanded_url, true);
1434
1435                         if ($type == "")
1436                                 $type = $oembed_data->type;
1437                         if ($oembed_data->type == "video") {
1438                                 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1439                                 $type = $oembed_data->type;
1440                                 $footerurl = $expanded_url;
1441                                 $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
1442
1443                                 $body = str_replace($search, $footerlink, $body);
1444                         } elseif (($oembed_data->type == "photo") AND isset($oembed_data->url) AND !$dontincludemedia)
1445                                 $body = str_replace($search, "[url=".$expanded_url."][img]".$oembed_data->url."[/img][/url]", $body);
1446                         elseif ($oembed_data->type != "link")
1447                                 $body = str_replace($search,  "[url=".$expanded_url."]".$expanded_url."[/url]", $body);
1448                         else {
1449                                 $img_str = fetch_url($expanded_url, true, $redirects, 4);
1450
1451                                 $tempfile = tempnam(get_temppath(), "cache");
1452                                 file_put_contents($tempfile, $img_str);
1453                                 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1454                                 unlink($tempfile);
1455
1456                                 if (substr($mime, 0, 6) == "image/") {
1457                                         $type = "photo";
1458                                         $body = str_replace($search, "[img]".$expanded_url."[/img]", $body);
1459                                 } else {
1460                                         $type = $oembed_data->type;
1461                                         $footerurl = $expanded_url;
1462                                         $footerlink = "[url=".$expanded_url."]".$expanded_url."[/url]";
1463
1464                                         $body = str_replace($search, $footerlink, $body);
1465                                 }
1466                         }
1467                 }
1468
1469                 if ($footerurl != "")
1470                         $footer = add_page_info($footerurl);
1471
1472                 if (($footerlink != "") AND (trim($footer) != "")) {
1473                         $removedlink = trim(str_replace($footerlink, "", $body));
1474
1475                         if (strstr($body, $removedlink))
1476                                 $body = $removedlink;
1477
1478                         $body .= $footer;
1479                 }
1480         }
1481
1482         if ($no_tags)
1483                 return(array("body" => $body, "tags" => ""));
1484
1485         $str_tags = '';
1486
1487         $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",$body,$matches,PREG_SET_ORDER);
1488         if($cnt) {
1489                 foreach($matches as $mtch) {
1490                         if(strlen($str_tags))
1491                                 $str_tags .= ',';
1492
1493                         if ($mtch[1] == "#") {
1494                                 // Replacing the hash tags that are directed to the statusnet server with internal links
1495                                 $snhash = "#[url=".$mtch[2]."]".$mtch[3]."[/url]";
1496                                 $frdchash = '#[url='.$a->get_baseurl().'/search?tag='.rawurlencode($mtch[3]).']'.$mtch[3].'[/url]';
1497                                 $body = str_replace($snhash, $frdchash, $body);
1498
1499                                 $str_tags .= $frdchash;
1500                         } else
1501                                 $str_tags .= "@[url=".$mtch[2]."]".$mtch[3]."[/url]";
1502                                 // To-Do:
1503                                 // There is a problem with links with to statusnet groups, so these links are stored with "@" like friendica groups
1504                                 //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1505                 }
1506         }
1507
1508         return(array("body"=>$body, "tags"=>$str_tags));
1509
1510 }
1511
1512 function statusnet_fetch_own_contact($a, $uid) {
1513         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
1514         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1515         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
1516         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
1517         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1518         $own_url = get_pconfig($uid, 'statusnet', 'own_url');
1519
1520         $contact_id = 0;
1521
1522         if ($own_url == "") {
1523                 require_once('library/twitteroauth.php');
1524
1525                 $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1526
1527                 // Fetching user data
1528                 $user = $connection->get('account/verify_credentials');
1529
1530                 set_pconfig($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
1531
1532                 $contact_id = statusnet_fetch_contact($uid, $user, true);
1533
1534         } else {
1535                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1536                         intval($uid), dbesc($own_url));
1537                 if(count($r))
1538                         $contact_id = $r[0]["id"];
1539                 else
1540                         del_pconfig($uid, 'statusnet', 'own_url');
1541
1542         }
1543         return($contact_id);
1544 }
1545
1546 function statusnet_is_retweet($a, $uid, $body) {
1547         $body = trim($body);
1548
1549         // Skip if it isn't a pure repeated messages
1550         // Does it start with a share?
1551         if (strpos($body, "[share") > 0)
1552                 return(false);
1553
1554         // Does it end with a share?
1555         if (strlen($body) > (strrpos($body, "[/share]") + 8))
1556                 return(false);
1557
1558         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1559         // Skip if there is no shared message in there
1560         if ($body == $attributes)
1561                 return(false);
1562
1563         $link = "";
1564         preg_match("/link='(.*?)'/ism", $attributes, $matches);
1565         if ($matches[1] != "")
1566                 $link = $matches[1];
1567
1568         preg_match('/link="(.*?)"/ism', $attributes, $matches);
1569         if ($matches[1] != "")
1570                 $link = $matches[1];
1571
1572         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
1573         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
1574         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
1575         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
1576         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
1577         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1578
1579         $id = preg_replace("=https?://".$hostname."/notice/(.*)=ism", "$1", $link);
1580
1581         if ($id == $link)
1582                 return(false);
1583
1584         logger('statusnet_is_retweet: Retweeting id '.$id.' for user '.$uid, LOGGER_DEBUG);
1585
1586         $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
1587
1588         $result = $connection->post('statuses/retweet/'.$id);
1589
1590         logger('statusnet_is_retweet: result '.print_r($result, true), LOGGER_DEBUG);
1591         return(isset($result->id));
1592 }