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