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