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