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