Massive reformatting of StatusNet
[friendica-addons.git] / statusnet / statusnet.php
1 <?php
2
3 /**
4  * Name: GNU Social Connector
5  * Description: Bidirectional (posting, relaying and reading) connector for GNU Social.
6  * Version: 1.0.5
7  * Author: Tobias Diekershoff <https://f.diekershoff.de/profile/tobias>
8  * Author: Michael Vogel <https://pirati.ca/profile/heluecht>
9  *
10  * Copyright (c) 2011-2013 Tobias Diekershoff, Michael Vogel
11  * All rights reserved.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions are met:
15  *    * Redistributions of source code must retain the above copyright notice,
16  *     this list of conditions and the following disclaimer.
17  *    * Redistributions in binary form must reproduce the above
18  *    * copyright notice, this list of conditions and the following disclaimer in
19  *      the documentation and/or other materials provided with the distribution.
20  *    * Neither the name of the <organization> nor the names of its contributors
21  *      may be used to endorse or promote products derived from this software
22  *      without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27  * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT,
28  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
29  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
31  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
32  * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
33  * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34  *
35  */
36 /*
37  * We have to alter the TwitterOAuth class a little bit to work with any GNU Social
38  * installation abroad. Basically it's only make the API path variable and be happy.
39  *
40  * Thank you guys for the Twitter compatible API!
41  */
42
43 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
44
45 require_once 'library/twitteroauth.php';
46 require_once 'include/enotify.php';
47
48 use Friendica\App;
49 use Friendica\Core\Config;
50 use Friendica\Core\PConfig;
51 use Friendica\Model\GContact;
52 use Friendica\Model\Photo;
53
54 class StatusNetOAuth extends TwitterOAuth
55 {
56         function get_maxlength()
57         {
58                 $config = $this->get($this->host . 'statusnet/config.json');
59                 return $config->site->textlimit;
60         }
61
62         function accessTokenURL()
63         {
64                 return $this->host . 'oauth/access_token';
65         }
66
67         function authenticateURL()
68         {
69                 return $this->host . 'oauth/authenticate';
70         }
71
72         function authorizeURL()
73         {
74                 return $this->host . 'oauth/authorize';
75         }
76
77         function requestTokenURL()
78         {
79                 return $this->host . 'oauth/request_token';
80         }
81
82         function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL)
83         {
84                 parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
85                 $this->host = $apipath;
86         }
87
88         /**
89          * Make an HTTP request
90          *
91          * @return API results
92          *
93          * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
94          */
95         function http($url, $method, $postfields = NULL)
96         {
97                 $this->http_info = array();
98                 $ci = curl_init();
99                 /* Curl settings */
100                 $prx = Config::get('system', 'proxy');
101                 if (strlen($prx)) {
102                         curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
103                         curl_setopt($ci, CURLOPT_PROXY, $prx);
104                         $prxusr = Config::get('system', 'proxyuser');
105                         if (strlen($prxusr)) {
106                                 curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
107                         }
108                 }
109                 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
110                 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
111                 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
112                 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
113                 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
114                 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
115                 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
116                 curl_setopt($ci, CURLOPT_HEADER, FALSE);
117
118                 switch ($method) {
119                         case 'POST':
120                                 curl_setopt($ci, CURLOPT_POST, TRUE);
121                                 if (!empty($postfields)) {
122                                         curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
123                                 }
124                                 break;
125                         case 'DELETE':
126                                 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
127                                 if (!empty($postfields)) {
128                                         $url = "{$url}?{$postfields}";
129                                 }
130                 }
131
132                 curl_setopt($ci, CURLOPT_URL, $url);
133                 $response = curl_exec($ci);
134                 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
135                 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
136                 $this->url = $url;
137                 curl_close($ci);
138                 return $response;
139         }
140 }
141
142 function statusnet_install()
143 {
144         //  we need some hooks, for the configuration and for sending tweets
145         register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
146         register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
147         register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
148         register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
149         register_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
150         register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
151         register_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
152         register_hook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
153         logger("installed GNU Social");
154 }
155
156 function statusnet_uninstall()
157 {
158         unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
159         unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
160         unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
161         unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
162         unregister_hook('jot_networks', 'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
163         unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
164         unregister_hook('prepare_body', 'addon/statusnet/statusnet.php', 'statusnet_prepare_body');
165         unregister_hook('check_item_notification', 'addon/statusnet/statusnet.php', 'statusnet_check_item_notification');
166
167         // old setting - remove only
168         unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
169         unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings');
170         unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
171 }
172
173 function statusnet_check_item_notification(App $a, &$notification_data)
174 {
175         $notification_data["profiles"][] = PConfig::get($notification_data["uid"], 'statusnet', 'own_url');
176 }
177
178 function statusnet_jot_nets(App $a, &$b)
179 {
180         if (!local_user()) {
181                 return;
182         }
183
184         $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
185         if (intval($statusnet_post) == 1) {
186                 $statusnet_defpost = PConfig::get(local_user(), 'statusnet', 'post_by_default');
187                 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
188                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> '
189                         . t('Post to GNU Social') . '</div>';
190         }
191 }
192
193 function statusnet_settings_post(App $a, $post)
194 {
195         if (!local_user()) {
196                 return;
197         }
198         // don't check GNU Social settings if GNU Social submit button is not clicked
199         if (!x($_POST, 'statusnet-submit')) {
200                 return;
201         }
202
203         if (isset($_POST['statusnet-disconnect'])) {
204                 /*               * *
205                  * if the GNU Social-disconnect checkbox is set, clear the GNU Social configuration
206                  */
207                 PConfig::delete(local_user(), 'statusnet', 'consumerkey');
208                 PConfig::delete(local_user(), 'statusnet', 'consumersecret');
209                 PConfig::delete(local_user(), 'statusnet', 'post');
210                 PConfig::delete(local_user(), 'statusnet', 'post_by_default');
211                 PConfig::delete(local_user(), 'statusnet', 'oauthtoken');
212                 PConfig::delete(local_user(), 'statusnet', 'oauthsecret');
213                 PConfig::delete(local_user(), 'statusnet', 'baseapi');
214                 PConfig::delete(local_user(), 'statusnet', 'lastid');
215                 PConfig::delete(local_user(), 'statusnet', 'mirror_posts');
216                 PConfig::delete(local_user(), 'statusnet', 'import');
217                 PConfig::delete(local_user(), 'statusnet', 'create_user');
218                 PConfig::delete(local_user(), 'statusnet', 'own_id');
219         } else {
220                 if (isset($_POST['statusnet-preconf-apiurl'])) {
221                         /*                       * *
222                          * If the user used one of the preconfigured GNU Social server credentials
223                          * use them. All the data are available in the global config.
224                          * Check the API Url never the less and blame the admin if it's not working ^^
225                          */
226                         $globalsn = Config::get('statusnet', 'sites');
227                         foreach ($globalsn as $asn) {
228                                 if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl']) {
229                                         $apibase = $asn['apiurl'];
230                                         $c = fetch_url($apibase . 'statusnet/version.xml');
231                                         if (strlen($c) > 0) {
232                                                 PConfig::set(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey']);
233                                                 PConfig::set(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret']);
234                                                 PConfig::set(local_user(), 'statusnet', 'baseapi', $asn['apiurl']);
235                                                 //PConfig::set(local_user(), 'statusnet', 'application_name', $asn['applicationname'] );
236                                         } else {
237                                                 notice(t('Please contact your site administrator.<br />The provided API URL is not valid.') . EOL . $asn['apiurl'] . EOL);
238                                         }
239                                 }
240                         }
241                         goaway($a->get_baseurl() . '/settings/connectors');
242                 } else {
243                         if (isset($_POST['statusnet-consumersecret'])) {
244                                 //  check if we can reach the API of the GNU Social server
245                                 //  we'll check the API Version for that, if we don't get one we'll try to fix the path but will
246                                 //  resign quickly after this one try to fix the path ;-)
247                                 $apibase = $_POST['statusnet-baseapi'];
248                                 $c = fetch_url($apibase . 'statusnet/version.xml');
249                                 if (strlen($c) > 0) {
250                                         //  ok the API path is correct, let's save the settings
251                                         PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
252                                         PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
253                                         PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
254                                         //PConfig::set(local_user(), 'statusnet', 'application_name', $_POST['statusnet-applicationname'] );
255                                 } else {
256                                         //  the API path is not correct, maybe missing trailing / ?
257                                         $apibase = $apibase . '/';
258                                         $c = fetch_url($apibase . 'statusnet/version.xml');
259                                         if (strlen($c) > 0) {
260                                                 //  ok the API path is now correct, let's save the settings
261                                                 PConfig::set(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
262                                                 PConfig::set(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
263                                                 PConfig::set(local_user(), 'statusnet', 'baseapi', $apibase);
264                                         } else {
265                                                 //  still not the correct API base, let's do noting
266                                                 notice(t('We could not contact the GNU Social API with the Path you entered.') . EOL);
267                                         }
268                                 }
269                                 goaway($a->get_baseurl() . '/settings/connectors');
270                         } else {
271                                 if (isset($_POST['statusnet-pin'])) {
272                                         //  if the user supplied us with a PIN from GNU Social, let the magic of OAuth happen
273                                         $api = PConfig::get(local_user(), 'statusnet', 'baseapi');
274                                         $ckey = PConfig::get(local_user(), 'statusnet', 'consumerkey');
275                                         $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
276                                         //  the token and secret for which the PIN was generated were hidden in the settings
277                                         //  form as token and token2, we need a new connection to GNU Social using these token
278                                         //  and secret to request a Access Token with the PIN
279                                         $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
280                                         $token = $connection->getAccessToken($_POST['statusnet-pin']);
281                                         //  ok, now that we have the Access Token, save them in the user config
282                                         PConfig::set(local_user(), 'statusnet', 'oauthtoken', $token['oauth_token']);
283                                         PConfig::set(local_user(), 'statusnet', 'oauthsecret', $token['oauth_token_secret']);
284                                         PConfig::set(local_user(), 'statusnet', 'post', 1);
285                                         PConfig::set(local_user(), 'statusnet', 'post_taglinks', 1);
286                                         //  reload the Addon Settings page, if we don't do it see Bug #42
287                                         goaway($a->get_baseurl() . '/settings/connectors');
288                                 } else {
289                                         //  if no PIN is supplied in the POST variables, the user has changed the setting
290                                         //  to post a dent for every new __public__ posting to the wall
291                                         PConfig::set(local_user(), 'statusnet', 'post', intval($_POST['statusnet-enable']));
292                                         PConfig::set(local_user(), 'statusnet', 'post_by_default', intval($_POST['statusnet-default']));
293                                         PConfig::set(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
294                                         PConfig::set(local_user(), 'statusnet', 'import', intval($_POST['statusnet-import']));
295                                         PConfig::set(local_user(), 'statusnet', 'create_user', intval($_POST['statusnet-create_user']));
296
297                                         if (!intval($_POST['statusnet-mirror']))
298                                                 PConfig::delete(local_user(), 'statusnet', 'lastid');
299
300                                         info(t('GNU Social settings updated.') . EOL);
301                                 }
302                         }
303                 }
304         }
305 }
306
307 function statusnet_settings(App $a, &$s)
308 {
309         if (!local_user()) {
310                 return;
311         }
312         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
313         /*       * *
314          * 1) Check that we have a base api url and a consumer key & secret
315          * 2) If no OAuthtoken & stuff is present, generate button to get some
316          *    allow the user to cancel the connection process at this step
317          * 3) Checkbox for "Send public notices (respect size limitation)
318          */
319         $api     = PConfig::get(local_user(), 'statusnet', 'baseapi');
320         $ckey    = PConfig::get(local_user(), 'statusnet', 'consumerkey');
321         $csecret = PConfig::get(local_user(), 'statusnet', 'consumersecret');
322         $otoken  = PConfig::get(local_user(), 'statusnet', 'oauthtoken');
323         $osecret = PConfig::get(local_user(), 'statusnet', 'oauthsecret');
324         $enabled = PConfig::get(local_user(), 'statusnet', 'post');
325         $checked = (($enabled) ? ' checked="checked" ' : '');
326         $defenabled = PConfig::get(local_user(), 'statusnet', 'post_by_default');
327         $defchecked = (($defenabled) ? ' checked="checked" ' : '');
328         $mirrorenabled = PConfig::get(local_user(), 'statusnet', 'mirror_posts');
329         $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
330         $import = PConfig::get(local_user(), 'statusnet', 'import');
331         $importselected = array("", "", "");
332         $importselected[$import] = ' selected="selected"';
333         //$importenabled = PConfig::get(local_user(),'statusnet','import');
334         //$importchecked = (($importenabled) ? ' checked="checked" ' : '');
335         $create_userenabled = PConfig::get(local_user(), 'statusnet', 'create_user');
336         $create_userchecked = (($create_userenabled) ? ' checked="checked" ' : '');
337
338         $css = (($enabled) ? '' : '-disabled');
339
340         $s .= '<span id="settings_statusnet_inflated" class="settings-block fakelink" style="display: block;" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
341         $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . t('GNU Social Import/Export/Mirror') . '</h3>';
342         $s .= '</span>';
343         $s .= '<div id="settings_statusnet_expanded" class="settings-block" style="display: none;">';
344         $s .= '<span class="fakelink" onclick="openClose(\'settings_statusnet_expanded\'); openClose(\'settings_statusnet_inflated\');">';
345         $s .= '<img class="connector' . $css . '" src="images/gnusocial.png" /><h3 class="connector">' . t('GNU Social Import/Export/Mirror') . '</h3>';
346         $s .= '</span>';
347
348         if ((!$ckey) && (!$csecret)) {
349                 /*               * *
350                  * no consumer keys
351                  */
352                 $globalsn = Config::get('statusnet', 'sites');
353                 /*               * *
354                  * lets check if we have one or more globally configured GNU Social
355                  * server OAuth credentials in the configuration. If so offer them
356                  * with a little explanation to the user as choice - otherwise
357                  * ignore this option entirely.
358                  */
359                 if (!$globalsn == null) {
360                         $s .= '<h4>' . t('Globally Available GNU Social OAuthKeys') . '</h4>';
361                         $s .= '<p>' . t("There are preconfigured OAuth key pairs for some GNU Social servers available. If you are using one of them, please use these credentials. If not feel free to connect to any other GNU Social instance \x28see below\x29.") . '</p>';
362                         $s .= '<div id="statusnet-preconf-wrapper">';
363                         foreach ($globalsn as $asn) {
364                                 $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="' . $asn['apiurl'] . '">' . $asn['sitename'] . '<br />';
365                         }
366                         $s .= '<p></p><div class="clear"></div></div>';
367                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
368                 }
369                 $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
370                 $s .= '<p>' . t('No consumer key pair for GNU Social found. Register your Friendica Account as an desktop client on your GNU Social 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 GNU Social installation.') . '</p>';
371                 $s .= '<div id="statusnet-consumer-wrapper">';
372                 $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">' . t('OAuth Consumer Key') . '</label>';
373                 $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
374                 $s .= '<div class="clear"></div>';
375                 $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">' . t('OAuth Consumer Secret') . '</label>';
376                 $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
377                 $s .= '<div class="clear"></div>';
378                 $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">' . t("Base API Path \x28remember the trailing /\x29") . '</label>';
379                 $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
380                 $s .= '<div class="clear"></div>';
381                 //$s .= '<label id="statusnet-applicationname-label" for="statusnet-applicationname">'.t('GNU Socialapplication name').'</label>';
382                 //$s .= '<input id="statusnet-applicationname" type="text" name="statusnet-applicationname" size="35" /><br />';
383                 $s .= '<p></p><div class="clear"></div>';
384                 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
385                 $s .= '</div>';
386         } else {
387                 /*               * *
388                  * ok we have a consumer key pair now look into the OAuth stuff
389                  */
390                 if ((!$otoken) && (!$osecret)) {
391                         /*                       * *
392                          * the user has not yet connected the account to GNU Social
393                          * get a temporary OAuth key/secret pair and display a button with
394                          * which the user can request a PIN to connect the account to a
395                          * account at GNU Social
396                          */
397                         $connection = new StatusNetOAuth($api, $ckey, $csecret);
398                         $request_token = $connection->getRequestToken('oob');
399                         $token = $request_token['oauth_token'];
400                         /*                       * *
401                          *  make some nice form
402                          */
403                         $s .= '<p>' . t('To connect to your GNU Social account click the button below to get a security code from GNU Social which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to GNU Social.') . '</p>';
404                         $s .= '<a href="' . $connection->getAuthorizeURL($token, False) . '" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="' . t('Log in with GNU Social') . '"></a>';
405                         $s .= '<div id="statusnet-pin-wrapper">';
406                         $s .= '<label id="statusnet-pin-label" for="statusnet-pin">' . t('Copy the security code from GNU Social here') . '</label>';
407                         $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
408                         $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="' . $token . '" />';
409                         $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="' . $request_token['oauth_token_secret'] . '" />';
410                         $s .= '</div><div class="clear"></div>';
411                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
412                         $s .= '<h4>' . t('Cancel Connection Process') . '</h4>';
413                         $s .= '<div id="statusnet-cancel-wrapper">';
414                         $s .= '<p>' . t('Current GNU Social API is') . ': ' . $api . '</p>';
415                         $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">' . t('Cancel GNU Social Connection') . '</label>';
416                         $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
417                         $s .= '</div><div class="clear"></div>';
418                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
419                 } else {
420                         /*                       * *
421                          *  we have an OAuth key / secret pair for the user
422                          *  so let's give a chance to disable the postings to GNU Social
423                          */
424                         $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
425                         $details = $connection->get('account/verify_credentials');
426                         $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>';
427                         $s .= '<p>' . t('If enabled all your <strong>public</strong> postings can be posted to the associated GNU Social account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.') . '</p>';
428                         if ($a->user['hidewall']) {
429                                 $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 GNU Social will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') . '</p>';
430                         }
431                         $s .= '<div id="statusnet-enable-wrapper">';
432                         $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">' . t('Allow posting to GNU Social') . '</label>';
433                         $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
434                         $s .= '<div class="clear"></div>';
435                         $s .= '<label id="statusnet-default-label" for="statusnet-default">' . t('Send public postings to GNU Social by default') . '</label>';
436                         $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
437                         $s .= '<div class="clear"></div>';
438
439                         $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">' . t('Mirror all posts from GNU Social that are no replies or repeated messages') . '</label>';
440                         $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" ' . $mirrorchecked . '/>';
441
442                         $s .= '<div class="clear"></div>';
443                         $s .= '</div>';
444
445                         $s .= '<label id="statusnet-import-label" for="statusnet-import">' . t('Import the remote timeline') . '</label>';
446                         //$s .= '<input id="statusnet-import" type="checkbox" name="statusnet-import" value="1" '. $importchecked . '/>';
447
448                         $s .= '<select name="statusnet-import" id="statusnet-import" />';
449                         $s .= '<option value="0" ' . $importselected[0] . '>' . t("Disabled") . '</option>';
450                         $s .= '<option value="1" ' . $importselected[1] . '>' . t("Full Timeline") . '</option>';
451                         $s .= '<option value="2" ' . $importselected[2] . '>' . t("Only Mentions") . '</option>';
452                         $s .= '</select>';
453                         $s .= '<div class="clear"></div>';
454                         /*
455                           $s .= '<label id="statusnet-create_user-label" for="statusnet-create_user">'.t('Automatically create contacts').'</label>';
456                           $s .= '<input id="statusnet-create_user" type="checkbox" name="statusnet-create_user" value="1" '. $create_userchecked . '/>';
457                           $s .= '<div class="clear"></div>';
458                          */
459                         $s .= '<div id="statusnet-disconnect-wrapper">';
460                         $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">' . t('Clear OAuth configuration') . '</label>';
461                         $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
462                         $s .= '</div><div class="clear"></div>';
463                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Save Settings') . '" /></div>';
464                 }
465         }
466         $s .= '</div><div class="clear"></div>';
467 }
468
469 function statusnet_post_local(App $a, &$b)
470 {
471         if ($b['edit']) {
472                 return;
473         }
474
475         if (!local_user() || (local_user() != $b['uid'])) {
476                 return;
477         }
478
479         $statusnet_post = PConfig::get(local_user(), 'statusnet', 'post');
480         $statusnet_enable = (($statusnet_post && x($_REQUEST, 'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
481
482         // if API is used, default to the chosen settings
483         if ($b['api_source'] && intval(PConfig::get(local_user(), 'statusnet', 'post_by_default'))) {
484                 $statusnet_enable = 1;
485         }
486
487         if (!$statusnet_enable) {
488                 return;
489         }
490
491         if (strlen($b['postopts'])) {
492                 $b['postopts'] .= ',';
493         }
494
495         $b['postopts'] .= 'statusnet';
496 }
497
498 function statusnet_action(App $a, $uid, $pid, $action)
499 {
500         $api = PConfig::get($uid, 'statusnet', 'baseapi');
501         $ckey = PConfig::get($uid, 'statusnet', 'consumerkey');
502         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
503         $otoken = PConfig::get($uid, 'statusnet', 'oauthtoken');
504         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
505
506         $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
507
508         logger("statusnet_action '" . $action . "' ID: " . $pid, LOGGER_DATA);
509
510         switch ($action) {
511                 case "delete":
512                         $result = $connection->post("statuses/destroy/" . $pid);
513                         break;
514                 case "like":
515                         $result = $connection->post("favorites/create/" . $pid);
516                         break;
517                 case "unlike":
518                         $result = $connection->post("favorites/destroy/" . $pid);
519                         break;
520         }
521         logger("statusnet_action '" . $action . "' send, result: " . print_r($result, true), LOGGER_DEBUG);
522 }
523
524 function statusnet_post_hook(App $a, &$b)
525 {
526         /**
527          * Post to GNU Social
528          */
529         if (!PConfig::get($b["uid"], 'statusnet', 'import')) {
530                 if ($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
531                         return;
532         }
533
534         $api = PConfig::get($b["uid"], 'statusnet', 'baseapi');
535         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
536
537         if ($b['parent'] != $b['id']) {
538                 logger("statusnet_post_hook: parameter " . print_r($b, true), LOGGER_DATA);
539
540                 // Looking if its a reply to a GNU Social post
541                 $hostlength = strlen($hostname) + 2;
542                 if ((substr($b["parent-uri"], 0, $hostlength) != $hostname . "::") && (substr($b["extid"], 0, $hostlength) != $hostname . "::") && (substr($b["thr-parent"], 0, $hostlength) != $hostname . "::")) {
543                         logger("statusnet_post_hook: no GNU Social post " . $b["parent"]);
544                         return;
545                 }
546
547                 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
548                         FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
549                         WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1", dbesc($b["thr-parent"]), intval($b["uid"]));
550
551                 if (!count($r)) {
552                         logger("statusnet_post_hook: no parent found " . $b["thr-parent"]);
553                         return;
554                 } else {
555                         $iscomment = true;
556                         $orig_post = $r[0];
557                 }
558
559                 //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
560                 //$nicknameplain = "@".$orig_post["contact_nick"];
561
562                 $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
563
564                 $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
565                 $nicknameplain = "@" . $nick;
566
567                 logger("statusnet_post_hook: comparing " . $nickname . " and " . $nicknameplain . " with " . $b["body"], LOGGER_DEBUG);
568                 if ((strpos($b["body"], $nickname) === false) && (strpos($b["body"], $nicknameplain) === false))
569                         $b["body"] = $nickname . " " . $b["body"];
570
571                 logger("statusnet_post_hook: parent found " . print_r($orig_post, true), LOGGER_DEBUG);
572         } else {
573                 $iscomment = false;
574
575                 if ($b['private'] || !strstr($b['postopts'], 'statusnet'))
576                         return;
577
578                 // Dont't post if the post doesn't belong to us.
579                 // This is a check for forum postings
580                 $self = dba::select('contact', array('id'), array('uid' => $b['uid'], 'self' => true), array('limit' => 1));
581                 if ($b['contact-id'] != $self['id']) {
582                         return;
583                 }
584         }
585
586         if (($b['verb'] == ACTIVITY_POST) && $b['deleted']) {
587                 statusnet_action($a, $b["uid"], substr($orig_post["uri"], $hostlength), "delete");
588         }
589
590         if ($b['verb'] == ACTIVITY_LIKE) {
591                 logger("statusnet_post_hook: parameter 2 " . substr($b["thr-parent"], $hostlength), LOGGER_DEBUG);
592                 if ($b['deleted'])
593                         statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "unlike");
594                 else
595                         statusnet_action($a, $b["uid"], substr($b["thr-parent"], $hostlength), "like");
596                 return;
597         }
598
599         if ($b['deleted'] || ($b['created'] !== $b['edited'])) {
600                 return;
601         }
602
603         // if posts comes from GNU Social don't send it back
604         if ($b['extid'] == NETWORK_STATUSNET) {
605                 return;
606         }
607
608         if ($b['app'] == "StatusNet") {
609                 return;
610         }
611
612         logger('GNU Socialpost invoked');
613
614         PConfig::load($b['uid'], 'statusnet');
615
616         $api     = PConfig::get($b['uid'], 'statusnet', 'baseapi');
617         $ckey    = PConfig::get($b['uid'], 'statusnet', 'consumerkey');
618         $csecret = PConfig::get($b['uid'], 'statusnet', 'consumersecret');
619         $otoken  = PConfig::get($b['uid'], 'statusnet', 'oauthtoken');
620         $osecret = PConfig::get($b['uid'], 'statusnet', 'oauthsecret');
621
622         if ($ckey && $csecret && $otoken && $osecret) {
623                 // If it's a repeated message from GNU Social then do a native retweet and exit
624                 if (statusnet_is_retweet($a, $b['uid'], $b['body'])) {
625                         return;
626                 }
627
628                 require_once 'include/bbcode.php';
629                 $dent = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
630                 $max_char = $dent->get_maxlength(); // max. length for a dent
631
632                 PConfig::set($b['uid'], 'statusnet', 'max_char', $max_char);
633
634                 $tempfile = "";
635                 require_once "include/plaintext.php";
636                 require_once "include/network.php";
637                 $msgarr = plaintext($a, $b, $max_char, true, 7);
638                 $msg = $msgarr["text"];
639
640                 if (($msg == "") && isset($msgarr["title"]))
641                         $msg = shortenmsg($msgarr["title"], $max_char - 50);
642
643                 $image = "";
644
645                 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
646                         if ((strlen($msgarr["url"]) > 20) &&
647                                 ((strlen($msg . " \n" . $msgarr["url"]) > $max_char))) {
648                                 $msg .= " \n" . short_link($msgarr["url"]);
649                         } else {
650                                 $msg .= " \n" . $msgarr["url"];
651                         }
652                 } elseif (isset($msgarr["image"]) && ($msgarr["type"] != "video")) {
653                         $image = $msgarr["image"];
654                 }
655
656                 if ($image != "") {
657                         $img_str = fetch_url($image);
658                         $tempfile = tempnam(get_temppath(), "cache");
659                         file_put_contents($tempfile, $img_str);
660                         $postdata = array("status" => $msg, "media[]" => $tempfile);
661                 } else {
662                         $postdata = array("status" => $msg);
663                 }
664
665                 // and now dent it :-)
666                 if (strlen($msg)) {
667                         if ($iscomment) {
668                                 $postdata["in_reply_to_status_id"] = substr($orig_post["uri"], $hostlength);
669                                 logger('statusnet_post send reply ' . print_r($postdata, true), LOGGER_DEBUG);
670                         }
671
672                         // New code that is able to post pictures
673                         require_once "addon/statusnet/codebird.php";
674                         $cb = \CodebirdSN\CodebirdSN::getInstance();
675                         $cb->setAPIEndpoint($api);
676                         $cb->setConsumerKey($ckey, $csecret);
677                         $cb->setToken($otoken, $osecret);
678                         $result = $cb->statuses_update($postdata);
679                         //$result = $dent->post('statuses/update', $postdata);
680                         logger('statusnet_post send, result: ' . print_r($result, true) .
681                                 "\nmessage: " . $msg, LOGGER_DEBUG . "\nOriginal post: " . print_r($b, true) . "\nPost Data: " . print_r($postdata, true));
682
683                         if ($result->source) {
684                                 PConfig::set($b["uid"], "statusnet", "application_name", strip_tags($result->source));
685                         }
686
687                         if ($result->error) {
688                                 logger('Send to GNU Social failed: "' . $result->error . '"');
689                         } elseif ($iscomment) {
690                                 logger('statusnet_post: Update extid ' . $result->id . " for post id " . $b['id']);
691                                 q("UPDATE `item` SET `extid` = '%s', `body` = '%s' WHERE `id` = %d",
692                                         dbesc($hostname . "::" . $result->id),
693                                         dbesc($result->text),
694                                         intval($b['id'])
695                                 );
696                         }
697                 }
698                 if ($tempfile != "") {
699                         unlink($tempfile);
700                 }
701         }
702 }
703
704 function statusnet_plugin_admin_post(App $a)
705 {
706         $sites = array();
707
708         foreach ($_POST['sitename'] as $id => $sitename) {
709                 $sitename = trim($sitename);
710                 $apiurl = trim($_POST['apiurl'][$id]);
711                 if (!(substr($apiurl, -1) == '/')) {
712                         $apiurl = $apiurl . '/';
713                 }
714                 $secret = trim($_POST['secret'][$id]);
715                 $key = trim($_POST['key'][$id]);
716                 //$applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
717                 if ($sitename != "" &&
718                         $apiurl != "" &&
719                         $secret != "" &&
720                         $key != "" &&
721                         !x($_POST['delete'][$id])) {
722
723                         $sites[] = Array(
724                                 'sitename' => $sitename,
725                                 'apiurl' => $apiurl,
726                                 'consumersecret' => $secret,
727                                 'consumerkey' => $key,
728                                 //'applicationname' => $applicationname
729                         );
730                 }
731         }
732
733         $sites = Config::set('statusnet', 'sites', $sites);
734 }
735
736 function statusnet_plugin_admin(App $a, &$o)
737 {
738         $sites = Config::get('statusnet', 'sites');
739         $sitesform = array();
740         if (is_array($sites)) {
741                 foreach ($sites as $id => $s) {
742                         $sitesform[] = Array(
743                                 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
744                                 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], t("Base API Path \x28remember the trailing /\x29")),
745                                 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
746                                 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
747                                 //'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
748                                 'delete' => Array("delete[$id]", "Delete", False, "Check to delete this preset"),
749                         );
750                 }
751         }
752         /* empty form to add new site */
753         $id++;
754         $sitesform[] = Array(
755                 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
756                 'apiurl' => Array("apiurl[$id]", "Api url", "", t("Base API Path \x28remember the trailing /\x29")),
757                 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
758                 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
759                 //'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
760         );
761
762         $t = get_markup_template("admin.tpl", "addon/statusnet/");
763         $o = replace_macros($t, array(
764                 '$submit' => t('Save Settings'),
765                 '$sites' => $sitesform,
766         ));
767 }
768
769 function statusnet_prepare_body(App $a, &$b)
770 {
771         if ($b["item"]["network"] != NETWORK_STATUSNET) {
772                 return;
773         }
774
775         if ($b["preview"]) {
776                 $max_char = PConfig::get(local_user(), 'statusnet', 'max_char');
777                 if (intval($max_char) == 0) {
778                         $max_char = 140;
779                 }
780
781                 require_once "include/plaintext.php";
782                 $item = $b["item"];
783                 $item["plink"] = $a->get_baseurl() . "/display/" . $a->user["nickname"] . "/" . $item["parent"];
784
785                 $r = q("SELECT `item`.`author-link`, `item`.`uri`, `contact`.`nick` AS contact_nick
786                         FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
787                         WHERE `item`.`uri` = '%s' AND `item`.`uid` = %d LIMIT 1",
788                         dbesc($item["thr-parent"]),
789                         intval(local_user()));
790
791                 if (count($r)) {
792                         $orig_post = $r[0];
793                         //$nickname = "@[url=".$orig_post["author-link"]."]".$orig_post["contact_nick"]."[/url]";
794                         //$nicknameplain = "@".$orig_post["contact_nick"];
795
796                         $nick = preg_replace("=https?://(.*)/(.*)=ism", "$2", $orig_post["author-link"]);
797
798                         $nickname = "@[url=" . $orig_post["author-link"] . "]" . $nick . "[/url]";
799                         $nicknameplain = "@" . $nick;
800
801                         if ((strpos($item["body"], $nickname) === false) && (strpos($item["body"], $nicknameplain) === false)) {
802                                 $item["body"] = $nickname . " " . $item["body"];
803                         }
804                 }
805
806                 $msgarr = plaintext($a, $item, $max_char, true, 7);
807                 $msg = $msgarr["text"];
808
809                 if (isset($msgarr["url"]) && ($msgarr["type"] != "photo")) {
810                         $msg .= " " . $msgarr["url"];
811                 }
812
813                 if (isset($msgarr["image"])) {
814                         $msg .= " " . $msgarr["image"];
815                 }
816
817                 $b['html'] = nl2br(htmlspecialchars($msg));
818         }
819 }
820
821 function statusnet_cron(App $a, $b)
822 {
823         $last = Config::get('statusnet', 'last_poll');
824
825         $poll_interval = intval(Config::get('statusnet', 'poll_interval'));
826         if (!$poll_interval) {
827                 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
828         }
829
830         if ($last) {
831                 $next = $last + ($poll_interval * 60);
832                 if ($next > time()) {
833                         logger('statusnet: poll intervall not reached');
834                         return;
835                 }
836         }
837         logger('statusnet: cron_start');
838
839         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
840         if (count($r)) {
841                 foreach ($r as $rr) {
842                         logger('statusnet: fetching for user ' . $rr['uid']);
843                         statusnet_fetchtimeline($a, $rr['uid']);
844                 }
845         }
846
847         $abandon_days = intval(Config::get('system', 'account_abandon_days'));
848         if ($abandon_days < 1) {
849                 $abandon_days = 0;
850         }
851
852         $abandon_limit = date("Y-m-d H:i:s", time() - $abandon_days * 86400);
853
854         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'import' AND `v` ORDER BY RAND()");
855         if (count($r)) {
856                 foreach ($r as $rr) {
857                         if ($abandon_days != 0) {
858                                 $user = q("SELECT `login_date` FROM `user` WHERE uid=%d AND `login_date` >= '%s'", $rr['uid'], $abandon_limit);
859                                 if (!count($user)) {
860                                         logger('abandoned account: timeline from user ' . $rr['uid'] . ' will not be imported');
861                                         continue;
862                                 }
863                         }
864
865                         logger('statusnet: importing timeline from user ' . $rr['uid']);
866                         statusnet_fetchhometimeline($a, $rr["uid"], $rr["v"]);
867                 }
868         }
869
870         logger('statusnet: cron_end');
871
872         Config::set('statusnet', 'last_poll', time());
873 }
874
875 function statusnet_fetchtimeline(App $a, $uid)
876 {
877         $ckey    = PConfig::get($uid, 'statusnet', 'consumerkey');
878         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
879         $api     = PConfig::get($uid, 'statusnet', 'baseapi');
880         $otoken  = PConfig::get($uid, 'statusnet', 'oauthtoken');
881         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
882         $lastid  = PConfig::get($uid, 'statusnet', 'lastid');
883
884         require_once 'mod/item.php';
885         require_once 'include/items.php';
886
887         //  get the application name for the SN app
888         //  1st try personal config, then system config and fallback to the
889         //  hostname of the node if neither one is set.
890         $application_name = PConfig::get($uid, 'statusnet', 'application_name');
891         if ($application_name == "") {
892                 $application_name = Config::get('statusnet', 'application_name');
893         }
894         if ($application_name == "") {
895                 $application_name = $a->get_hostname();
896         }
897
898         $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
899
900         $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
901
902         $first_time = ($lastid == "");
903
904         if ($lastid <> "") {
905                 $parameters["since_id"] = $lastid;
906         }
907
908         $items = $connection->get('statuses/user_timeline', $parameters);
909
910         if (!is_array($items)) {
911                 return;
912         }
913
914         $posts = array_reverse($items);
915
916         if (count($posts)) {
917                 foreach ($posts as $post) {
918                         if ($post->id > $lastid)
919                                 $lastid = $post->id;
920
921                         if ($first_time) {
922                                 continue;
923                         }
924
925                         if ($post->source == "activity") {
926                                 continue;
927                         }
928
929                         if (is_object($post->retweeted_status)) {
930                                 continue;
931                         }
932
933                         if ($post->in_reply_to_status_id != "") {
934                                 continue;
935                         }
936
937                         if (!stristr($post->source, $application_name)) {
938                                 $_SESSION["authenticated"] = true;
939                                 $_SESSION["uid"] = $uid;
940
941                                 unset($_REQUEST);
942                                 $_REQUEST["type"] = "wall";
943                                 $_REQUEST["api_source"] = true;
944                                 $_REQUEST["profile_uid"] = $uid;
945                                 //$_REQUEST["source"] = "StatusNet";
946                                 $_REQUEST["source"] = $post->source;
947                                 $_REQUEST["extid"] = NETWORK_STATUSNET;
948
949                                 if (isset($post->id)) {
950                                         $_REQUEST['message_id'] = item_new_uri($a->get_hostname(), $uid, NETWORK_STATUSNET . ":" . $post->id);
951                                 }
952
953                                 //$_REQUEST["date"] = $post->created_at;
954
955                                 $_REQUEST["title"] = "";
956
957                                 $_REQUEST["body"] = add_page_info_to_body($post->text, true);
958                                 if (is_string($post->place->name)) {
959                                         $_REQUEST["location"] = $post->place->name;
960                                 }
961
962                                 if (is_string($post->place->full_name)) {
963                                         $_REQUEST["location"] = $post->place->full_name;
964                                 }
965
966                                 if (is_array($post->geo->coordinates)) {
967                                         $_REQUEST["coord"] = $post->geo->coordinates[0] . " " . $post->geo->coordinates[1];
968                                 }
969
970                                 if (is_array($post->coordinates->coordinates)) {
971                                         $_REQUEST["coord"] = $post->coordinates->coordinates[1] . " " . $post->coordinates->coordinates[0];
972                                 }
973
974                                 //print_r($_REQUEST);
975                                 if ($_REQUEST["body"] != "") {
976                                         logger('statusnet: posting for user ' . $uid);
977
978                                         item_post($a);
979                                 }
980                         }
981                 }
982         }
983         PConfig::set($uid, 'statusnet', 'lastid', $lastid);
984 }
985
986 function statusnet_address($contact)
987 {
988         $hostname = normalise_link($contact->statusnet_profile_url);
989         $nickname = $contact->screen_name;
990
991         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $contact->statusnet_profile_url);
992
993         $address = $contact->screen_name . "@" . $hostname;
994
995         return $address;
996 }
997
998 function statusnet_fetch_contact($uid, $contact, $create_user)
999 {
1000         if ($contact->statusnet_profile_url == "") {
1001                 return -1;
1002         }
1003
1004         GContact::update(array("url" => $contact->statusnet_profile_url,
1005                 "network" => NETWORK_STATUSNET, "photo" => $contact->profile_image_url,
1006                 "name" => $contact->name, "nick" => $contact->screen_name,
1007                 "location" => $contact->location, "about" => $contact->description,
1008                 "addr" => statusnet_address($contact), "generation" => 3));
1009
1010         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' AND `network` = '%s'LIMIT 1", intval($uid), dbesc(normalise_link($contact->statusnet_profile_url)), dbesc(NETWORK_STATUSNET));
1011
1012         if (!count($r) && !$create_user) {
1013                 return 0;
1014         }
1015
1016         if (count($r) && ($r[0]["readonly"] || $r[0]["blocked"])) {
1017                 logger("statusnet_fetch_contact: Contact '" . $r[0]["nick"] . "' is blocked or readonly.", LOGGER_DEBUG);
1018                 return -1;
1019         }
1020
1021         if (!count($r)) {
1022                 // create contact record
1023                 q("INSERT INTO `contact` ( `uid`, `created`, `url`, `nurl`, `addr`, `alias`, `notify`, `poll`,
1024                                         `name`, `nick`, `photo`, `network`, `rel`, `priority`,
1025                                         `location`, `about`, `writable`, `blocked`, `readonly`, `pending` )
1026                                         VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, '%s', '%s', %d, 0, 0, 0 ) ",
1027                         intval($uid),
1028                         dbesc(datetime_convert()),
1029                         dbesc($contact->statusnet_profile_url),
1030                         dbesc(normalise_link($contact->statusnet_profile_url)),
1031                         dbesc(statusnet_address($contact)),
1032                         dbesc(normalise_link($contact->statusnet_profile_url)),
1033                         dbesc(''),
1034                         dbesc(''),
1035                         dbesc($contact->name),
1036                         dbesc($contact->screen_name),
1037                         dbesc($contact->profile_image_url),
1038                         dbesc(NETWORK_STATUSNET),
1039                         intval(CONTACT_IS_FRIEND),
1040                         intval(1),
1041                         dbesc($contact->location),
1042                         dbesc($contact->description),
1043                         intval(1)
1044                 );
1045
1046                 $r = q("SELECT * FROM `contact` WHERE `alias` = '%s' AND `uid` = %d AND `network` = '%s' LIMIT 1",
1047                         dbesc($contact->statusnet_profile_url),
1048                         intval($uid),
1049                         dbesc(NETWORK_STATUSNET));
1050
1051                 if (!count($r)) {
1052                         return false;
1053                 }
1054
1055                 $contact_id = $r[0]['id'];
1056
1057                 $g = q("SELECT def_gid FROM user WHERE uid = %d LIMIT 1",
1058                         intval($uid)
1059                 );
1060
1061                 if ($g && intval($g[0]['def_gid'])) {
1062                         require_once 'include/group.php';
1063                         group_add_member($uid, '', $contact_id, $g[0]['def_gid']);
1064                 }
1065
1066                 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $contact_id);
1067
1068                 q("UPDATE `contact` SET `photo` = '%s',
1069                                         `thumb` = '%s',
1070                                         `micro` = '%s',
1071                                         `avatar-date` = '%s'
1072                                 WHERE `id` = %d",
1073                         dbesc($photos[0]),
1074                         dbesc($photos[1]),
1075                         dbesc($photos[2]),
1076                         dbesc(datetime_convert()),
1077                         intval($contact_id)
1078                 );
1079         } else {
1080                 // update profile photos once every two weeks as we have no notification of when they change.
1081                 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1082                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('', '', 'now -12 hours'));
1083
1084                 // check that we have all the photos, this has been known to fail on occasion
1085                 if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1086                         logger("statusnet_fetch_contact: Updating contact " . $contact->screen_name, LOGGER_DEBUG);
1087
1088                         $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']);
1089
1090                         q("UPDATE `contact` SET `photo` = '%s',
1091                                                 `thumb` = '%s',
1092                                                 `micro` = '%s',
1093                                                 `name-date` = '%s',
1094                                                 `uri-date` = '%s',
1095                                                 `avatar-date` = '%s',
1096                                                 `url` = '%s',
1097                                                 `nurl` = '%s',
1098                                                 `addr` = '%s',
1099                                                 `name` = '%s',
1100                                                 `nick` = '%s',
1101                                                 `location` = '%s',
1102                                                 `about` = '%s'
1103                                         WHERE `id` = %d",
1104                                 dbesc($photos[0]),
1105                                 dbesc($photos[1]),
1106                                 dbesc($photos[2]),
1107                                 dbesc(datetime_convert()),
1108                                 dbesc(datetime_convert()),
1109                                 dbesc(datetime_convert()),
1110                                 dbesc($contact->statusnet_profile_url),
1111                                 dbesc(normalise_link($contact->statusnet_profile_url)),
1112                                 dbesc(statusnet_address($contact)),
1113                                 dbesc($contact->name),
1114                                 dbesc($contact->screen_name),
1115                                 dbesc($contact->location),
1116                                 dbesc($contact->description),
1117                                 intval($r[0]['id'])
1118                         );
1119                 }
1120         }
1121
1122         return $r[0]["id"];
1123 }
1124
1125 function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1126 {
1127         $ckey    = PConfig::get($uid, 'statusnet', 'consumerkey');
1128         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1129         $api     = PConfig::get($uid, 'statusnet', 'baseapi');
1130         $otoken  = PConfig::get($uid, 'statusnet', 'oauthtoken');
1131         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1132
1133         require_once "addon/statusnet/codebird.php";
1134
1135         $cb = \Codebird\Codebird::getInstance();
1136         $cb->setConsumerKey($ckey, $csecret);
1137         $cb->setToken($otoken, $osecret);
1138
1139         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1140                 intval($uid));
1141
1142         if (count($r)) {
1143                 $self = $r[0];
1144         } else {
1145                 return;
1146         }
1147
1148         $parameters = array();
1149
1150         if ($screen_name != "") {
1151                 $parameters["screen_name"] = $screen_name;
1152         }
1153
1154         if ($user_id != "") {
1155                 $parameters["user_id"] = $user_id;
1156         }
1157
1158         // Fetching user data
1159         $user = $cb->users_show($parameters);
1160
1161         if (!is_object($user)) {
1162                 return;
1163         }
1164
1165         $contact_id = statusnet_fetch_contact($uid, $user, true);
1166
1167         return $contact_id;
1168 }
1169
1170 function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact)
1171 {
1172         require_once "include/html2bbcode.php";
1173
1174         logger("statusnet_createpost: start", LOGGER_DEBUG);
1175
1176         $api = PConfig::get($uid, 'statusnet', 'baseapi');
1177         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1178
1179         $postarray = array();
1180         $postarray['network'] = NETWORK_STATUSNET;
1181         $postarray['gravity'] = 0;
1182         $postarray['uid'] = $uid;
1183         $postarray['wall'] = 0;
1184
1185         if (is_object($post->retweeted_status)) {
1186                 $content = $post->retweeted_status;
1187                 statusnet_fetch_contact($uid, $content->user, false);
1188         } else {
1189                 $content = $post;
1190         }
1191
1192         $postarray['uri'] = $hostname . "::" . $content->id;
1193
1194         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1195                         dbesc($postarray['uri']),
1196                         intval($uid)
1197         );
1198
1199         if (count($r)) {
1200                 return array();
1201         }
1202
1203         $contactid = 0;
1204
1205         if ($content->in_reply_to_status_id != "") {
1206
1207                 $parent = $hostname . "::" . $content->in_reply_to_status_id;
1208
1209                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1210                                 dbesc($parent),
1211                                 intval($uid)
1212                 );
1213                 if (count($r)) {
1214                         $postarray['thr-parent'] = $r[0]["uri"];
1215                         $postarray['parent-uri'] = $r[0]["parent-uri"];
1216                         $postarray['parent'] = $r[0]["parent"];
1217                         $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1218                 } else {
1219                         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1220                                         dbesc($parent),
1221                                         intval($uid)
1222                         );
1223                         if (count($r)) {
1224                                 $postarray['thr-parent'] = $r[0]['uri'];
1225                                 $postarray['parent-uri'] = $r[0]['parent-uri'];
1226                                 $postarray['parent'] = $r[0]['parent'];
1227                                 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1228                         } else {
1229                                 $postarray['thr-parent'] = $postarray['uri'];
1230                                 $postarray['parent-uri'] = $postarray['uri'];
1231                                 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1232                         }
1233                 }
1234
1235                 // Is it me?
1236                 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1237
1238                 if ($content->user->id == $own_url) {
1239                         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1240                                 intval($uid));
1241
1242                         if (count($r)) {
1243                                 $contactid = $r[0]["id"];
1244
1245                                 $postarray['owner-name'] = $r[0]["name"];
1246                                 $postarray['owner-link'] = $r[0]["url"];
1247                                 $postarray['owner-avatar'] = $r[0]["photo"];
1248                         } else {
1249                                 return array();
1250                         }
1251                 }
1252                 // Don't create accounts of people who just comment something
1253                 $create_user = false;
1254         } else {
1255                 $postarray['parent-uri'] = $postarray['uri'];
1256                 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1257         }
1258
1259         if ($contactid == 0) {
1260                 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1261                 $postarray['owner-name'] = $post->user->name;
1262                 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1263                 $postarray['owner-avatar'] = $post->user->profile_image_url;
1264         }
1265         if (($contactid == 0) && !$only_existing_contact) {
1266                 $contactid = $self['id'];
1267         } elseif ($contactid <= 0) {
1268                 return array();
1269         }
1270
1271         $postarray['contact-id'] = $contactid;
1272
1273         $postarray['verb'] = ACTIVITY_POST;
1274
1275         $postarray['author-name'] = $content->user->name;
1276         $postarray['author-link'] = $content->user->statusnet_profile_url;
1277         $postarray['author-avatar'] = $content->user->profile_image_url;
1278
1279         // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1280         $hostname = str_replace("/api/", "/notice/", PConfig::get($uid, 'statusnet', 'baseapi'));
1281
1282         $postarray['plink'] = $hostname . $content->id;
1283         $postarray['app'] = strip_tags($content->source);
1284
1285         if ($content->user->protected) {
1286                 $postarray['private'] = 1;
1287                 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1288         }
1289
1290         $postarray['body'] = html2bbcode($content->statusnet_html);
1291
1292         $converted = statusnet_convertmsg($a, $postarray['body'], false);
1293         $postarray['body'] = $converted["body"];
1294         $postarray['tag'] = $converted["tags"];
1295
1296         $postarray['created'] = datetime_convert('UTC', 'UTC', $content->created_at);
1297         $postarray['edited'] = datetime_convert('UTC', 'UTC', $content->created_at);
1298
1299         if (is_string($content->place->name)) {
1300                 $postarray["location"] = $content->place->name;
1301         }
1302
1303         if (is_string($content->place->full_name)) {
1304                 $postarray["location"] = $content->place->full_name;
1305         }
1306
1307         if (is_array($content->geo->coordinates)) {
1308                 $postarray["coord"] = $content->geo->coordinates[0] . " " . $content->geo->coordinates[1];
1309         }
1310
1311         if (is_array($content->coordinates->coordinates)) {
1312                 $postarray["coord"] = $content->coordinates->coordinates[1] . " " . $content->coordinates->coordinates[0];
1313         }
1314
1315         logger("statusnet_createpost: end", LOGGER_DEBUG);
1316
1317         return $postarray;
1318 }
1319
1320 function statusnet_checknotification(App $a, $uid, $own_url, $top_item, $postarray)
1321 {
1322         // This function necer worked and need cleanup
1323         $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1324                         intval($uid)
1325         );
1326
1327         if (!count($user)) {
1328                 return;
1329         }
1330
1331         // Is it me?
1332         if (link_compare($user[0]["url"], $postarray['author-link'])) {
1333                 return;
1334         }
1335
1336         $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1337                         intval($uid),
1338                         dbesc($own_url)
1339         );
1340
1341         if (!count($own_user)) {
1342                 return;
1343         }
1344
1345         // Is it me from GNU Social?
1346         if (link_compare($own_user[0]["url"], $postarray['author-link'])) {
1347                 return;
1348         }
1349
1350         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1351                         dbesc($postarray['parent-uri']),
1352                         intval($uid)
1353         );
1354
1355         if (count($myconv)) {
1356                 foreach ($myconv as $conv) {
1357                         // now if we find a match, it means we're in this conversation
1358                         if (!link_compare($conv['author-link'], $user[0]["url"]) && !link_compare($conv['author-link'], $own_user[0]["url"])) {
1359                                 continue;
1360                         }
1361
1362                         require_once 'include/enotify.php';
1363
1364                         $conv_parent = $conv['parent'];
1365
1366                         notification(array(
1367                                 'type' => NOTIFY_COMMENT,
1368                                 'notify_flags' => $user[0]['notify-flags'],
1369                                 'language' => $user[0]['language'],
1370                                 'to_name' => $user[0]['username'],
1371                                 'to_email' => $user[0]['email'],
1372                                 'uid' => $user[0]['uid'],
1373                                 'item' => $postarray,
1374                                 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($top_item)),
1375                                 'source_name' => $postarray['author-name'],
1376                                 'source_link' => $postarray['author-link'],
1377                                 'source_photo' => $postarray['author-avatar'],
1378                                 'verb' => ACTIVITY_POST,
1379                                 'otype' => 'item',
1380                                 'parent' => $conv_parent,
1381                         ));
1382
1383                         // only send one notification
1384                         break;
1385                 }
1386         }
1387 }
1388
1389 function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
1390 {
1391         $conversations = array();
1392
1393         $ckey    = PConfig::get($uid, 'statusnet', 'consumerkey');
1394         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1395         $api     = PConfig::get($uid, 'statusnet', 'baseapi');
1396         $otoken  = PConfig::get($uid, 'statusnet', 'oauthtoken');
1397         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1398         $create_user = PConfig::get($uid, 'statusnet', 'create_user');
1399
1400         // "create_user" is deactivated, since currently you cannot add users manually by now
1401         $create_user = true;
1402
1403         logger("statusnet_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG);
1404
1405         require_once 'library/twitteroauth.php';
1406         require_once 'include/items.php';
1407
1408         $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1409
1410         $own_contact = statusnet_fetch_own_contact($a, $uid);
1411
1412         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1413                 intval($own_contact),
1414                 intval($uid));
1415
1416         if (count($r)) {
1417                 $nick = $r[0]["nick"];
1418         } else {
1419                 logger("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, LOGGER_DEBUG);
1420                 return;
1421         }
1422
1423         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1424                 intval($uid));
1425
1426         if (count($r)) {
1427                 $self = $r[0];
1428         } else {
1429                 logger("statusnet_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG);
1430                 return;
1431         }
1432
1433         $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1434                 intval($uid));
1435         if (!count($u)) {
1436                 logger("statusnet_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG);
1437                 return;
1438         }
1439
1440         $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
1441         //$parameters["count"] = 200;
1442
1443         if ($mode == 1) {
1444                 // Fetching timeline
1445                 $lastid = PConfig::get($uid, 'statusnet', 'lasthometimelineid');
1446                 //$lastid = 1;
1447
1448                 $first_time = ($lastid == "");
1449
1450                 if ($lastid != "") {
1451                         $parameters["since_id"] = $lastid;
1452                 }
1453
1454                 $items = $connection->get('statuses/home_timeline', $parameters);
1455
1456                 if (!is_array($items)) {
1457                         if (is_object($items) && isset($items->error)) {
1458                                 $errormsg = $items->error;
1459                         } elseif (is_object($items)) {
1460                                 $errormsg = print_r($items, true);
1461                         } elseif (is_string($items) || is_float($items) || is_int($items)) {
1462                                 $errormsg = $items;
1463                         } else {
1464                                 $errormsg = "Unknown error";
1465                         }
1466
1467                         logger("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, LOGGER_DEBUG);
1468                         return;
1469                 }
1470
1471                 $posts = array_reverse($items);
1472
1473                 logger("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1474
1475                 if (count($posts)) {
1476                         foreach ($posts as $post) {
1477
1478                                 if ($post->id > $lastid) {
1479                                         $lastid = $post->id;
1480                                 }
1481
1482                                 if ($first_time) {
1483                                         continue;
1484                                 }
1485
1486                                 if (isset($post->statusnet_conversation_id)) {
1487                                         if (!isset($conversations[$post->statusnet_conversation_id])) {
1488                                                 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1489                                                 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1490                                         }
1491                                 } else {
1492                                         $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1493
1494                                         if (trim($postarray['body']) == "") {
1495                                                 continue;
1496                                         }
1497
1498                                         $item = item_store($postarray);
1499                                         $postarray["id"] = $item;
1500
1501                                         logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1502
1503                                         if ($item && !function_exists("check_item_notification")) {
1504                                                 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1505                                         }
1506                                 }
1507                         }
1508                 }
1509                 PConfig::set($uid, 'statusnet', 'lasthometimelineid', $lastid);
1510         }
1511
1512         // Fetching mentions
1513         $lastid = PConfig::get($uid, 'statusnet', 'lastmentionid');
1514         $first_time = ($lastid == "");
1515
1516         if ($lastid != "") {
1517                 $parameters["since_id"] = $lastid;
1518         }
1519
1520         $items = $connection->get('statuses/mentions_timeline', $parameters);
1521
1522         if (!is_array($items)) {
1523                 logger("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG);
1524                 return;
1525         }
1526
1527         $posts = array_reverse($items);
1528
1529         logger("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1530
1531         if (count($posts)) {
1532                 foreach ($posts as $post) {
1533                         if ($post->id > $lastid) {
1534                                 $lastid = $post->id;
1535                         }
1536
1537                         if ($first_time) {
1538                                 continue;
1539                         }
1540
1541                         $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1542
1543                         if (isset($post->statusnet_conversation_id)) {
1544                                 if (!isset($conversations[$post->statusnet_conversation_id])) {
1545                                         statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1546                                         $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1547                                 }
1548                         } else {
1549                                 if (trim($postarray['body']) == "") {
1550                                         continue;
1551                                 }
1552
1553                                 $item = item_store($postarray);
1554                                 $postarray["id"] = $item;
1555
1556                                 logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1557
1558                                 if ($item && function_exists("check_item_notification")) {
1559                                         check_item_notification($item, $uid, NOTIFY_TAGSELF);
1560                                 }
1561                         }
1562
1563                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1564                                 dbesc($postarray['uri']),
1565                                 intval($uid)
1566                         );
1567                         if (count($r)) {
1568                                 $item = $r[0]['id'];
1569                                 $parent_id = $r[0]['parent'];
1570                         }
1571
1572                         if (($item != 0) && !function_exists("check_item_notification")) {
1573                                 require_once 'include/enotify.php';
1574                                 notification(array(
1575                                         'type'         => NOTIFY_TAGSELF,
1576                                         'notify_flags' => $u[0]['notify-flags'],
1577                                         'language'     => $u[0]['language'],
1578                                         'to_name'      => $u[0]['username'],
1579                                         'to_email'     => $u[0]['email'],
1580                                         'uid'          => $u[0]['uid'],
1581                                         'item'         => $postarray,
1582                                         'link'         => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($item)),
1583                                         'source_name'  => $postarray['author-name'],
1584                                         'source_link'  => $postarray['author-link'],
1585                                         'source_photo' => $postarray['author-avatar'],
1586                                         'verb'         => ACTIVITY_TAG,
1587                                         'otype'        => 'item',
1588                                         'parent'       => $parent_id,
1589                                 ));
1590                         }
1591                 }
1592         }
1593
1594         PConfig::set($uid, 'statusnet', 'lastmentionid', $lastid);
1595 }
1596
1597 function statusnet_complete_conversation(App $a, $uid, $self, $create_user, $nick, $conversation)
1598 {
1599         $ckey    = PConfig::get($uid, 'statusnet', 'consumerkey');
1600         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1601         $api     = PConfig::get($uid, 'statusnet', 'baseapi');
1602         $otoken  = PConfig::get($uid, 'statusnet', 'oauthtoken');
1603         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1604         $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1605
1606         require_once 'library/twitteroauth.php';
1607
1608         $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1609
1610         $parameters["count"] = 200;
1611
1612         $items = $connection->get('statusnet/conversation/' . $conversation, $parameters);
1613         if (is_array($items)) {
1614                 $posts = array_reverse($items);
1615
1616                 foreach ($posts AS $post) {
1617                         $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1618
1619                         if (trim($postarray['body']) == "") {
1620                                 continue;
1621                         }
1622
1623                         $item = item_store($postarray);
1624                         $postarray["id"] = $item;
1625
1626                         logger('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1627
1628                         if ($item && !function_exists("check_item_notification")) {
1629                                 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1630                         }
1631                 }
1632         }
1633 }
1634
1635 function statusnet_convertmsg(App $a, $body, $no_tags = false)
1636 {
1637         require_once "include/oembed.php";
1638         require_once "include/items.php";
1639         require_once "include/network.php";
1640
1641         $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism", "$1.$2.$3.$4/$5", $body);
1642
1643         $URLSearchString = "^\[\]";
1644         $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1645
1646         $footer = "";
1647         $footerurl = "";
1648         $footerlink = "";
1649         $type = "";
1650
1651         if ($links) {
1652                 foreach ($matches AS $match) {
1653                         $search = "[url=" . $match[1] . "]" . $match[2] . "[/url]";
1654
1655                         logger("statusnet_convertmsg: expanding url " . $match[1], LOGGER_DEBUG);
1656
1657                         $expanded_url = original_url($match[1]);
1658
1659                         logger("statusnet_convertmsg: fetching data for " . $expanded_url, LOGGER_DEBUG);
1660
1661                         $oembed_data = oembed_fetch_url($expanded_url, true);
1662
1663                         logger("statusnet_convertmsg: fetching data: done", LOGGER_DEBUG);
1664
1665                         if ($type == "") {
1666                                 $type = $oembed_data->type;
1667                         }
1668
1669                         if ($oembed_data->type == "video") {
1670                                 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1671                                 $type = $oembed_data->type;
1672                                 $footerurl = $expanded_url;
1673                                 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1674
1675                                 $body = str_replace($search, $footerlink, $body);
1676                         } elseif (($oembed_data->type == "photo") && isset($oembed_data->url) && !$dontincludemedia) {
1677                                 $body = str_replace($search, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1678                         } elseif ($oembed_data->type != "link") {
1679                                 $body = str_replace($search, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1680                         } else {
1681                                 $img_str = fetch_url($expanded_url, true, $redirects, 4);
1682
1683                                 $tempfile = tempnam(get_temppath(), "cache");
1684                                 file_put_contents($tempfile, $img_str);
1685                                 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1686                                 unlink($tempfile);
1687
1688                                 if (substr($mime, 0, 6) == "image/") {
1689                                         $type = "photo";
1690                                         $body = str_replace($search, "[img]" . $expanded_url . "[/img]", $body);
1691                                 } else {
1692                                         $type = $oembed_data->type;
1693                                         $footerurl = $expanded_url;
1694                                         $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1695
1696                                         $body = str_replace($search, $footerlink, $body);
1697                                 }
1698                         }
1699                 }
1700
1701                 if ($footerurl != "") {
1702                         $footer = add_page_info($footerurl);
1703                 }
1704
1705                 if (($footerlink != "") && (trim($footer) != "")) {
1706                         $removedlink = trim(str_replace($footerlink, "", $body));
1707
1708                         if (($removedlink == "") || strstr($body, $removedlink)) {
1709                                 $body = $removedlink;
1710                         }
1711
1712                         $body .= $footer;
1713                 }
1714         }
1715
1716         if ($no_tags) {
1717                 return array("body" => $body, "tags" => "");
1718         }
1719
1720         $str_tags = '';
1721
1722         $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1723         if ($cnt) {
1724                 foreach ($matches as $mtch) {
1725                         if (strlen($str_tags)) {
1726                                 $str_tags .= ',';
1727                         }
1728
1729                         if ($mtch[1] == "#") {
1730                                 // Replacing the hash tags that are directed to the GNU Social server with internal links
1731                                 $snhash = "#[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1732                                 $frdchash = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($mtch[3]) . ']' . $mtch[3] . '[/url]';
1733                                 $body = str_replace($snhash, $frdchash, $body);
1734
1735                                 $str_tags .= $frdchash;
1736                         } else {
1737                                 $str_tags .= "@[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1738                         }
1739                         // To-Do:
1740                         // There is a problem with links with to GNU Social groups, so these links are stored with "@" like friendica groups
1741                         //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1742                 }
1743         }
1744
1745         return array("body" => $body, "tags" => $str_tags);
1746 }
1747
1748 function statusnet_fetch_own_contact(App $a, $uid)
1749 {
1750         $ckey    = PConfig::get($uid, 'statusnet', 'consumerkey');
1751         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1752         $api     = PConfig::get($uid, 'statusnet', 'baseapi');
1753         $otoken  = PConfig::get($uid, 'statusnet', 'oauthtoken');
1754         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1755         $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1756
1757         $contact_id = 0;
1758
1759         if ($own_url == "") {
1760                 require_once 'library/twitteroauth.php';
1761
1762                 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1763
1764                 // Fetching user data
1765                 $user = $connection->get('account/verify_credentials');
1766
1767                 PConfig::set($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
1768
1769                 $contact_id = statusnet_fetch_contact($uid, $user, true);
1770         } else {
1771                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1772                         intval($uid), dbesc($own_url));
1773                 if (count($r)) {
1774                         $contact_id = $r[0]["id"];
1775                 } else {
1776                         PConfig::delete($uid, 'statusnet', 'own_url');
1777                 }
1778         }
1779         return $contact_id;
1780 }
1781
1782 function statusnet_is_retweet(App $a, $uid, $body)
1783 {
1784         $body = trim($body);
1785
1786         // Skip if it isn't a pure repeated messages
1787         // Does it start with a share?
1788         if (strpos($body, "[share") > 0) {
1789                 return false;
1790         }
1791
1792         // Does it end with a share?
1793         if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1794                 return false;
1795         }
1796
1797         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1798         // Skip if there is no shared message in there
1799         if ($body == $attributes) {
1800                 return false;
1801         }
1802
1803         $link = "";
1804         preg_match("/link='(.*?)'/ism", $attributes, $matches);
1805         if ($matches[1] != "") {
1806                 $link = $matches[1];
1807         }
1808
1809         preg_match('/link="(.*?)"/ism', $attributes, $matches);
1810         if ($matches[1] != "") {
1811                 $link = $matches[1];
1812         }
1813
1814         $ckey    = PConfig::get($uid, 'statusnet', 'consumerkey');
1815         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1816         $api     = PConfig::get($uid, 'statusnet', 'baseapi');
1817         $otoken  = PConfig::get($uid, 'statusnet', 'oauthtoken');
1818         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1819         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1820
1821         $id = preg_replace("=https?://" . $hostname . "/notice/(.*)=ism", "$1", $link);
1822
1823         if ($id == $link) {
1824                 return false;
1825         }
1826
1827         logger('statusnet_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG);
1828
1829         $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1830
1831         $result = $connection->post('statuses/retweet/' . $id);
1832
1833         logger('statusnet_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);
1834
1835         return isset($result->id);
1836 }