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