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