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