Use new Model methods for group
[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                         require_once 'include/group.php';
1060                 Group::addMember(User::getDefaultGroup($uid), $contact_id);
1061
1062                 $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $contact_id);
1063
1064                 q("UPDATE `contact` SET `photo` = '%s',
1065                                         `thumb` = '%s',
1066                                         `micro` = '%s',
1067                                         `avatar-date` = '%s'
1068                                 WHERE `id` = %d",
1069                         dbesc($photos[0]),
1070                         dbesc($photos[1]),
1071                         dbesc($photos[2]),
1072                         dbesc(datetime_convert()),
1073                         intval($contact_id)
1074                 );
1075         } else {
1076                 // update profile photos once every two weeks as we have no notification of when they change.
1077                 //$update_photo = (($r[0]['avatar-date'] < datetime_convert('','','now -2 days')) ? true : false);
1078                 $update_photo = ($r[0]['avatar-date'] < datetime_convert('', '', 'now -12 hours'));
1079
1080                 // check that we have all the photos, this has been known to fail on occasion
1081                 if ((!$r[0]['photo']) || (!$r[0]['thumb']) || (!$r[0]['micro']) || ($update_photo)) {
1082                         logger("statusnet_fetch_contact: Updating contact " . $contact->screen_name, LOGGER_DEBUG);
1083
1084                         $photos = Photo::importProfilePhoto($contact->profile_image_url, $uid, $r[0]['id']);
1085
1086                         q("UPDATE `contact` SET `photo` = '%s',
1087                                                 `thumb` = '%s',
1088                                                 `micro` = '%s',
1089                                                 `name-date` = '%s',
1090                                                 `uri-date` = '%s',
1091                                                 `avatar-date` = '%s',
1092                                                 `url` = '%s',
1093                                                 `nurl` = '%s',
1094                                                 `addr` = '%s',
1095                                                 `name` = '%s',
1096                                                 `nick` = '%s',
1097                                                 `location` = '%s',
1098                                                 `about` = '%s'
1099                                         WHERE `id` = %d",
1100                                 dbesc($photos[0]),
1101                                 dbesc($photos[1]),
1102                                 dbesc($photos[2]),
1103                                 dbesc(datetime_convert()),
1104                                 dbesc(datetime_convert()),
1105                                 dbesc(datetime_convert()),
1106                                 dbesc($contact->statusnet_profile_url),
1107                                 dbesc(normalise_link($contact->statusnet_profile_url)),
1108                                 dbesc(statusnet_address($contact)),
1109                                 dbesc($contact->name),
1110                                 dbesc($contact->screen_name),
1111                                 dbesc($contact->location),
1112                                 dbesc($contact->description),
1113                                 intval($r[0]['id'])
1114                         );
1115                 }
1116         }
1117
1118         return $r[0]["id"];
1119 }
1120
1121 function statusnet_fetchuser(App $a, $uid, $screen_name = "", $user_id = "")
1122 {
1123         $ckey    = PConfig::get($uid, 'statusnet', 'consumerkey');
1124         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1125         $api     = PConfig::get($uid, 'statusnet', 'baseapi');
1126         $otoken  = PConfig::get($uid, 'statusnet', 'oauthtoken');
1127         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1128
1129         require_once "addon/statusnet/codebird.php";
1130
1131         $cb = \Codebird\Codebird::getInstance();
1132         $cb->setConsumerKey($ckey, $csecret);
1133         $cb->setToken($otoken, $osecret);
1134
1135         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1136                 intval($uid));
1137
1138         if (count($r)) {
1139                 $self = $r[0];
1140         } else {
1141                 return;
1142         }
1143
1144         $parameters = array();
1145
1146         if ($screen_name != "") {
1147                 $parameters["screen_name"] = $screen_name;
1148         }
1149
1150         if ($user_id != "") {
1151                 $parameters["user_id"] = $user_id;
1152         }
1153
1154         // Fetching user data
1155         $user = $cb->users_show($parameters);
1156
1157         if (!is_object($user)) {
1158                 return;
1159         }
1160
1161         $contact_id = statusnet_fetch_contact($uid, $user, true);
1162
1163         return $contact_id;
1164 }
1165
1166 function statusnet_createpost(App $a, $uid, $post, $self, $create_user, $only_existing_contact)
1167 {
1168         require_once "include/html2bbcode.php";
1169
1170         logger("statusnet_createpost: start", LOGGER_DEBUG);
1171
1172         $api = PConfig::get($uid, 'statusnet', 'baseapi');
1173         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1174
1175         $postarray = array();
1176         $postarray['network'] = NETWORK_STATUSNET;
1177         $postarray['gravity'] = 0;
1178         $postarray['uid'] = $uid;
1179         $postarray['wall'] = 0;
1180
1181         if (is_object($post->retweeted_status)) {
1182                 $content = $post->retweeted_status;
1183                 statusnet_fetch_contact($uid, $content->user, false);
1184         } else {
1185                 $content = $post;
1186         }
1187
1188         $postarray['uri'] = $hostname . "::" . $content->id;
1189
1190         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1191                         dbesc($postarray['uri']),
1192                         intval($uid)
1193         );
1194
1195         if (count($r)) {
1196                 return array();
1197         }
1198
1199         $contactid = 0;
1200
1201         if ($content->in_reply_to_status_id != "") {
1202
1203                 $parent = $hostname . "::" . $content->in_reply_to_status_id;
1204
1205                 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1206                                 dbesc($parent),
1207                                 intval($uid)
1208                 );
1209                 if (count($r)) {
1210                         $postarray['thr-parent'] = $r[0]["uri"];
1211                         $postarray['parent-uri'] = $r[0]["parent-uri"];
1212                         $postarray['parent'] = $r[0]["parent"];
1213                         $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1214                 } else {
1215                         $r = q("SELECT * FROM `item` WHERE `extid` = '%s' AND `uid` = %d LIMIT 1",
1216                                         dbesc($parent),
1217                                         intval($uid)
1218                         );
1219                         if (count($r)) {
1220                                 $postarray['thr-parent'] = $r[0]['uri'];
1221                                 $postarray['parent-uri'] = $r[0]['parent-uri'];
1222                                 $postarray['parent'] = $r[0]['parent'];
1223                                 $postarray['object-type'] = ACTIVITY_OBJ_COMMENT;
1224                         } else {
1225                                 $postarray['thr-parent'] = $postarray['uri'];
1226                                 $postarray['parent-uri'] = $postarray['uri'];
1227                                 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1228                         }
1229                 }
1230
1231                 // Is it me?
1232                 $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1233
1234                 if ($content->user->id == $own_url) {
1235                         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1236                                 intval($uid));
1237
1238                         if (count($r)) {
1239                                 $contactid = $r[0]["id"];
1240
1241                                 $postarray['owner-name'] = $r[0]["name"];
1242                                 $postarray['owner-link'] = $r[0]["url"];
1243                                 $postarray['owner-avatar'] = $r[0]["photo"];
1244                         } else {
1245                                 return array();
1246                         }
1247                 }
1248                 // Don't create accounts of people who just comment something
1249                 $create_user = false;
1250         } else {
1251                 $postarray['parent-uri'] = $postarray['uri'];
1252                 $postarray['object-type'] = ACTIVITY_OBJ_NOTE;
1253         }
1254
1255         if ($contactid == 0) {
1256                 $contactid = statusnet_fetch_contact($uid, $post->user, $create_user);
1257                 $postarray['owner-name'] = $post->user->name;
1258                 $postarray['owner-link'] = $post->user->statusnet_profile_url;
1259                 $postarray['owner-avatar'] = $post->user->profile_image_url;
1260         }
1261         if (($contactid == 0) && !$only_existing_contact) {
1262                 $contactid = $self['id'];
1263         } elseif ($contactid <= 0) {
1264                 return array();
1265         }
1266
1267         $postarray['contact-id'] = $contactid;
1268
1269         $postarray['verb'] = ACTIVITY_POST;
1270
1271         $postarray['author-name'] = $content->user->name;
1272         $postarray['author-link'] = $content->user->statusnet_profile_url;
1273         $postarray['author-avatar'] = $content->user->profile_image_url;
1274
1275         // To-Do: Maybe unreliable? Can the api be entered without trailing "/"?
1276         $hostname = str_replace("/api/", "/notice/", PConfig::get($uid, 'statusnet', 'baseapi'));
1277
1278         $postarray['plink'] = $hostname . $content->id;
1279         $postarray['app'] = strip_tags($content->source);
1280
1281         if ($content->user->protected) {
1282                 $postarray['private'] = 1;
1283                 $postarray['allow_cid'] = '<' . $self['id'] . '>';
1284         }
1285
1286         $postarray['body'] = html2bbcode($content->statusnet_html);
1287
1288         $converted = statusnet_convertmsg($a, $postarray['body'], false);
1289         $postarray['body'] = $converted["body"];
1290         $postarray['tag'] = $converted["tags"];
1291
1292         $postarray['created'] = datetime_convert('UTC', 'UTC', $content->created_at);
1293         $postarray['edited'] = datetime_convert('UTC', 'UTC', $content->created_at);
1294
1295         if (is_string($content->place->name)) {
1296                 $postarray["location"] = $content->place->name;
1297         }
1298
1299         if (is_string($content->place->full_name)) {
1300                 $postarray["location"] = $content->place->full_name;
1301         }
1302
1303         if (is_array($content->geo->coordinates)) {
1304                 $postarray["coord"] = $content->geo->coordinates[0] . " " . $content->geo->coordinates[1];
1305         }
1306
1307         if (is_array($content->coordinates->coordinates)) {
1308                 $postarray["coord"] = $content->coordinates->coordinates[1] . " " . $content->coordinates->coordinates[0];
1309         }
1310
1311         logger("statusnet_createpost: end", LOGGER_DEBUG);
1312
1313         return $postarray;
1314 }
1315
1316 function statusnet_checknotification(App $a, $uid, $own_url, $top_item, $postarray)
1317 {
1318         // This function necer worked and need cleanup
1319         $user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1",
1320                         intval($uid)
1321         );
1322
1323         if (!count($user)) {
1324                 return;
1325         }
1326
1327         // Is it me?
1328         if (link_compare($user[0]["url"], $postarray['author-link'])) {
1329                 return;
1330         }
1331
1332         $own_user = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1333                         intval($uid),
1334                         dbesc($own_url)
1335         );
1336
1337         if (!count($own_user)) {
1338                 return;
1339         }
1340
1341         // Is it me from GNU Social?
1342         if (link_compare($own_user[0]["url"], $postarray['author-link'])) {
1343                 return;
1344         }
1345
1346         $myconv = q("SELECT `author-link`, `author-avatar`, `parent` FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `parent` != 0 AND `deleted` = 0",
1347                         dbesc($postarray['parent-uri']),
1348                         intval($uid)
1349         );
1350
1351         if (count($myconv)) {
1352                 foreach ($myconv as $conv) {
1353                         // now if we find a match, it means we're in this conversation
1354                         if (!link_compare($conv['author-link'], $user[0]["url"]) && !link_compare($conv['author-link'], $own_user[0]["url"])) {
1355                                 continue;
1356                         }
1357
1358                         require_once 'include/enotify.php';
1359
1360                         $conv_parent = $conv['parent'];
1361
1362                         notification(array(
1363                                 'type' => NOTIFY_COMMENT,
1364                                 'notify_flags' => $user[0]['notify-flags'],
1365                                 'language' => $user[0]['language'],
1366                                 'to_name' => $user[0]['username'],
1367                                 'to_email' => $user[0]['email'],
1368                                 'uid' => $user[0]['uid'],
1369                                 'item' => $postarray,
1370                                 'link' => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($top_item)),
1371                                 'source_name' => $postarray['author-name'],
1372                                 'source_link' => $postarray['author-link'],
1373                                 'source_photo' => $postarray['author-avatar'],
1374                                 'verb' => ACTIVITY_POST,
1375                                 'otype' => 'item',
1376                                 'parent' => $conv_parent,
1377                         ));
1378
1379                         // only send one notification
1380                         break;
1381                 }
1382         }
1383 }
1384
1385 function statusnet_fetchhometimeline(App $a, $uid, $mode = 1)
1386 {
1387         $conversations = array();
1388
1389         $ckey    = PConfig::get($uid, 'statusnet', 'consumerkey');
1390         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1391         $api     = PConfig::get($uid, 'statusnet', 'baseapi');
1392         $otoken  = PConfig::get($uid, 'statusnet', 'oauthtoken');
1393         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1394         $create_user = PConfig::get($uid, 'statusnet', 'create_user');
1395
1396         // "create_user" is deactivated, since currently you cannot add users manually by now
1397         $create_user = true;
1398
1399         logger("statusnet_fetchhometimeline: Fetching for user " . $uid, LOGGER_DEBUG);
1400
1401         require_once 'library/twitteroauth.php';
1402         require_once 'include/items.php';
1403
1404         $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1405
1406         $own_contact = statusnet_fetch_own_contact($a, $uid);
1407
1408         $r = q("SELECT * FROM `contact` WHERE `id` = %d AND `uid` = %d LIMIT 1",
1409                 intval($own_contact),
1410                 intval($uid));
1411
1412         if (count($r)) {
1413                 $nick = $r[0]["nick"];
1414         } else {
1415                 logger("statusnet_fetchhometimeline: Own GNU Social contact not found for user " . $uid, LOGGER_DEBUG);
1416                 return;
1417         }
1418
1419         $r = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
1420                 intval($uid));
1421
1422         if (count($r)) {
1423                 $self = $r[0];
1424         } else {
1425                 logger("statusnet_fetchhometimeline: Own contact not found for user " . $uid, LOGGER_DEBUG);
1426                 return;
1427         }
1428
1429         $u = q("SELECT * FROM user WHERE uid = %d LIMIT 1",
1430                 intval($uid));
1431         if (!count($u)) {
1432                 logger("statusnet_fetchhometimeline: Own user not found for user " . $uid, LOGGER_DEBUG);
1433                 return;
1434         }
1435
1436         $parameters = array("exclude_replies" => false, "trim_user" => false, "contributor_details" => true, "include_rts" => true);
1437         //$parameters["count"] = 200;
1438
1439         if ($mode == 1) {
1440                 // Fetching timeline
1441                 $lastid = PConfig::get($uid, 'statusnet', 'lasthometimelineid');
1442                 //$lastid = 1;
1443
1444                 $first_time = ($lastid == "");
1445
1446                 if ($lastid != "") {
1447                         $parameters["since_id"] = $lastid;
1448                 }
1449
1450                 $items = $connection->get('statuses/home_timeline', $parameters);
1451
1452                 if (!is_array($items)) {
1453                         if (is_object($items) && isset($items->error)) {
1454                                 $errormsg = $items->error;
1455                         } elseif (is_object($items)) {
1456                                 $errormsg = print_r($items, true);
1457                         } elseif (is_string($items) || is_float($items) || is_int($items)) {
1458                                 $errormsg = $items;
1459                         } else {
1460                                 $errormsg = "Unknown error";
1461                         }
1462
1463                         logger("statusnet_fetchhometimeline: Error fetching home timeline: " . $errormsg, LOGGER_DEBUG);
1464                         return;
1465                 }
1466
1467                 $posts = array_reverse($items);
1468
1469                 logger("statusnet_fetchhometimeline: Fetching timeline for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1470
1471                 if (count($posts)) {
1472                         foreach ($posts as $post) {
1473
1474                                 if ($post->id > $lastid) {
1475                                         $lastid = $post->id;
1476                                 }
1477
1478                                 if ($first_time) {
1479                                         continue;
1480                                 }
1481
1482                                 if (isset($post->statusnet_conversation_id)) {
1483                                         if (!isset($conversations[$post->statusnet_conversation_id])) {
1484                                                 statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1485                                                 $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1486                                         }
1487                                 } else {
1488                                         $postarray = statusnet_createpost($a, $uid, $post, $self, $create_user, true);
1489
1490                                         if (trim($postarray['body']) == "") {
1491                                                 continue;
1492                                         }
1493
1494                                         $item = item_store($postarray);
1495                                         $postarray["id"] = $item;
1496
1497                                         logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1498
1499                                         if ($item && !function_exists("check_item_notification")) {
1500                                                 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1501                                         }
1502                                 }
1503                         }
1504                 }
1505                 PConfig::set($uid, 'statusnet', 'lasthometimelineid', $lastid);
1506         }
1507
1508         // Fetching mentions
1509         $lastid = PConfig::get($uid, 'statusnet', 'lastmentionid');
1510         $first_time = ($lastid == "");
1511
1512         if ($lastid != "") {
1513                 $parameters["since_id"] = $lastid;
1514         }
1515
1516         $items = $connection->get('statuses/mentions_timeline', $parameters);
1517
1518         if (!is_array($items)) {
1519                 logger("statusnet_fetchhometimeline: Error fetching mentions: " . print_r($items, true), LOGGER_DEBUG);
1520                 return;
1521         }
1522
1523         $posts = array_reverse($items);
1524
1525         logger("statusnet_fetchhometimeline: Fetching mentions for user " . $uid . " " . sizeof($posts) . " items", LOGGER_DEBUG);
1526
1527         if (count($posts)) {
1528                 foreach ($posts as $post) {
1529                         if ($post->id > $lastid) {
1530                                 $lastid = $post->id;
1531                         }
1532
1533                         if ($first_time) {
1534                                 continue;
1535                         }
1536
1537                         $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1538
1539                         if (isset($post->statusnet_conversation_id)) {
1540                                 if (!isset($conversations[$post->statusnet_conversation_id])) {
1541                                         statusnet_complete_conversation($a, $uid, $self, $create_user, $nick, $post->statusnet_conversation_id);
1542                                         $conversations[$post->statusnet_conversation_id] = $post->statusnet_conversation_id;
1543                                 }
1544                         } else {
1545                                 if (trim($postarray['body']) == "") {
1546                                         continue;
1547                                 }
1548
1549                                 $item = item_store($postarray);
1550                                 $postarray["id"] = $item;
1551
1552                                 logger('statusnet_fetchhometimeline: User ' . $self["nick"] . ' posted mention timeline item ' . $item);
1553
1554                                 if ($item && function_exists("check_item_notification")) {
1555                                         check_item_notification($item, $uid, NOTIFY_TAGSELF);
1556                                 }
1557                         }
1558
1559                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d LIMIT 1",
1560                                 dbesc($postarray['uri']),
1561                                 intval($uid)
1562                         );
1563                         if (count($r)) {
1564                                 $item = $r[0]['id'];
1565                                 $parent_id = $r[0]['parent'];
1566                         }
1567
1568                         if (($item != 0) && !function_exists("check_item_notification")) {
1569                                 require_once 'include/enotify.php';
1570                                 notification(array(
1571                                         'type'         => NOTIFY_TAGSELF,
1572                                         'notify_flags' => $u[0]['notify-flags'],
1573                                         'language'     => $u[0]['language'],
1574                                         'to_name'      => $u[0]['username'],
1575                                         'to_email'     => $u[0]['email'],
1576                                         'uid'          => $u[0]['uid'],
1577                                         'item'         => $postarray,
1578                                         'link'         => $a->get_baseurl() . '/display/' . urlencode(get_item_guid($item)),
1579                                         'source_name'  => $postarray['author-name'],
1580                                         'source_link'  => $postarray['author-link'],
1581                                         'source_photo' => $postarray['author-avatar'],
1582                                         'verb'         => ACTIVITY_TAG,
1583                                         'otype'        => 'item',
1584                                         'parent'       => $parent_id,
1585                                 ));
1586                         }
1587                 }
1588         }
1589
1590         PConfig::set($uid, 'statusnet', 'lastmentionid', $lastid);
1591 }
1592
1593 function statusnet_complete_conversation(App $a, $uid, $self, $create_user, $nick, $conversation)
1594 {
1595         $ckey    = PConfig::get($uid, 'statusnet', 'consumerkey');
1596         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1597         $api     = PConfig::get($uid, 'statusnet', 'baseapi');
1598         $otoken  = PConfig::get($uid, 'statusnet', 'oauthtoken');
1599         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1600         $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1601
1602         require_once 'library/twitteroauth.php';
1603
1604         $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1605
1606         $parameters["count"] = 200;
1607
1608         $items = $connection->get('statusnet/conversation/' . $conversation, $parameters);
1609         if (is_array($items)) {
1610                 $posts = array_reverse($items);
1611
1612                 foreach ($posts AS $post) {
1613                         $postarray = statusnet_createpost($a, $uid, $post, $self, false, false);
1614
1615                         if (trim($postarray['body']) == "") {
1616                                 continue;
1617                         }
1618
1619                         $item = item_store($postarray);
1620                         $postarray["id"] = $item;
1621
1622                         logger('statusnet_complete_conversation: User ' . $self["nick"] . ' posted home timeline item ' . $item);
1623
1624                         if ($item && !function_exists("check_item_notification")) {
1625                                 statusnet_checknotification($a, $uid, $nick, $item, $postarray);
1626                         }
1627                 }
1628         }
1629 }
1630
1631 function statusnet_convertmsg(App $a, $body, $no_tags = false)
1632 {
1633         require_once "include/oembed.php";
1634         require_once "include/items.php";
1635         require_once "include/network.php";
1636
1637         $body = preg_replace("=\[url\=https?://([0-9]*).([0-9]*).([0-9]*).([0-9]*)/([0-9]*)\](.*?)\[\/url\]=ism", "$1.$2.$3.$4/$5", $body);
1638
1639         $URLSearchString = "^\[\]";
1640         $links = preg_match_all("/[^!#@]\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1641
1642         $footer = "";
1643         $footerurl = "";
1644         $footerlink = "";
1645         $type = "";
1646
1647         if ($links) {
1648                 foreach ($matches AS $match) {
1649                         $search = "[url=" . $match[1] . "]" . $match[2] . "[/url]";
1650
1651                         logger("statusnet_convertmsg: expanding url " . $match[1], LOGGER_DEBUG);
1652
1653                         $expanded_url = original_url($match[1]);
1654
1655                         logger("statusnet_convertmsg: fetching data for " . $expanded_url, LOGGER_DEBUG);
1656
1657                         $oembed_data = oembed_fetch_url($expanded_url, true);
1658
1659                         logger("statusnet_convertmsg: fetching data: done", LOGGER_DEBUG);
1660
1661                         if ($type == "") {
1662                                 $type = $oembed_data->type;
1663                         }
1664
1665                         if ($oembed_data->type == "video") {
1666                                 //$body = str_replace($search, "[video]".$expanded_url."[/video]", $body);
1667                                 $type = $oembed_data->type;
1668                                 $footerurl = $expanded_url;
1669                                 $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1670
1671                                 $body = str_replace($search, $footerlink, $body);
1672                         } elseif (($oembed_data->type == "photo") && isset($oembed_data->url) && !$dontincludemedia) {
1673                                 $body = str_replace($search, "[url=" . $expanded_url . "][img]" . $oembed_data->url . "[/img][/url]", $body);
1674                         } elseif ($oembed_data->type != "link") {
1675                                 $body = str_replace($search, "[url=" . $expanded_url . "]" . $expanded_url . "[/url]", $body);
1676                         } else {
1677                                 $img_str = fetch_url($expanded_url, true, $redirects, 4);
1678
1679                                 $tempfile = tempnam(get_temppath(), "cache");
1680                                 file_put_contents($tempfile, $img_str);
1681                                 $mime = image_type_to_mime_type(exif_imagetype($tempfile));
1682                                 unlink($tempfile);
1683
1684                                 if (substr($mime, 0, 6) == "image/") {
1685                                         $type = "photo";
1686                                         $body = str_replace($search, "[img]" . $expanded_url . "[/img]", $body);
1687                                 } else {
1688                                         $type = $oembed_data->type;
1689                                         $footerurl = $expanded_url;
1690                                         $footerlink = "[url=" . $expanded_url . "]" . $expanded_url . "[/url]";
1691
1692                                         $body = str_replace($search, $footerlink, $body);
1693                                 }
1694                         }
1695                 }
1696
1697                 if ($footerurl != "") {
1698                         $footer = add_page_info($footerurl);
1699                 }
1700
1701                 if (($footerlink != "") && (trim($footer) != "")) {
1702                         $removedlink = trim(str_replace($footerlink, "", $body));
1703
1704                         if (($removedlink == "") || strstr($body, $removedlink)) {
1705                                 $body = $removedlink;
1706                         }
1707
1708                         $body .= $footer;
1709                 }
1710         }
1711
1712         if ($no_tags) {
1713                 return array("body" => $body, "tags" => "");
1714         }
1715
1716         $str_tags = '';
1717
1718         $cnt = preg_match_all("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $body, $matches, PREG_SET_ORDER);
1719         if ($cnt) {
1720                 foreach ($matches as $mtch) {
1721                         if (strlen($str_tags)) {
1722                                 $str_tags .= ',';
1723                         }
1724
1725                         if ($mtch[1] == "#") {
1726                                 // Replacing the hash tags that are directed to the GNU Social server with internal links
1727                                 $snhash = "#[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1728                                 $frdchash = '#[url=' . $a->get_baseurl() . '/search?tag=' . rawurlencode($mtch[3]) . ']' . $mtch[3] . '[/url]';
1729                                 $body = str_replace($snhash, $frdchash, $body);
1730
1731                                 $str_tags .= $frdchash;
1732                         } else {
1733                                 $str_tags .= "@[url=" . $mtch[2] . "]" . $mtch[3] . "[/url]";
1734                         }
1735                         // To-Do:
1736                         // There is a problem with links with to GNU Social groups, so these links are stored with "@" like friendica groups
1737                         //$str_tags .= $mtch[1]."[url=".$mtch[2]."]".$mtch[3]."[/url]";
1738                 }
1739         }
1740
1741         return array("body" => $body, "tags" => $str_tags);
1742 }
1743
1744 function statusnet_fetch_own_contact(App $a, $uid)
1745 {
1746         $ckey    = PConfig::get($uid, 'statusnet', 'consumerkey');
1747         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1748         $api     = PConfig::get($uid, 'statusnet', 'baseapi');
1749         $otoken  = PConfig::get($uid, 'statusnet', 'oauthtoken');
1750         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1751         $own_url = PConfig::get($uid, 'statusnet', 'own_url');
1752
1753         $contact_id = 0;
1754
1755         if ($own_url == "") {
1756                 require_once 'library/twitteroauth.php';
1757
1758                 $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1759
1760                 // Fetching user data
1761                 $user = $connection->get('account/verify_credentials');
1762
1763                 PConfig::set($uid, 'statusnet', 'own_url', normalise_link($user->statusnet_profile_url));
1764
1765                 $contact_id = statusnet_fetch_contact($uid, $user, true);
1766         } else {
1767                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
1768                         intval($uid), dbesc($own_url));
1769                 if (count($r)) {
1770                         $contact_id = $r[0]["id"];
1771                 } else {
1772                         PConfig::delete($uid, 'statusnet', 'own_url');
1773                 }
1774         }
1775         return $contact_id;
1776 }
1777
1778 function statusnet_is_retweet(App $a, $uid, $body)
1779 {
1780         $body = trim($body);
1781
1782         // Skip if it isn't a pure repeated messages
1783         // Does it start with a share?
1784         if (strpos($body, "[share") > 0) {
1785                 return false;
1786         }
1787
1788         // Does it end with a share?
1789         if (strlen($body) > (strrpos($body, "[/share]") + 8)) {
1790                 return false;
1791         }
1792
1793         $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism", "$1", $body);
1794         // Skip if there is no shared message in there
1795         if ($body == $attributes) {
1796                 return false;
1797         }
1798
1799         $link = "";
1800         preg_match("/link='(.*?)'/ism", $attributes, $matches);
1801         if ($matches[1] != "") {
1802                 $link = $matches[1];
1803         }
1804
1805         preg_match('/link="(.*?)"/ism', $attributes, $matches);
1806         if ($matches[1] != "") {
1807                 $link = $matches[1];
1808         }
1809
1810         $ckey    = PConfig::get($uid, 'statusnet', 'consumerkey');
1811         $csecret = PConfig::get($uid, 'statusnet', 'consumersecret');
1812         $api     = PConfig::get($uid, 'statusnet', 'baseapi');
1813         $otoken  = PConfig::get($uid, 'statusnet', 'oauthtoken');
1814         $osecret = PConfig::get($uid, 'statusnet', 'oauthsecret');
1815         $hostname = preg_replace("=https?://([\w\.]*)/.*=ism", "$1", $api);
1816
1817         $id = preg_replace("=https?://" . $hostname . "/notice/(.*)=ism", "$1", $link);
1818
1819         if ($id == $link) {
1820                 return false;
1821         }
1822
1823         logger('statusnet_is_retweet: Retweeting id ' . $id . ' for user ' . $uid, LOGGER_DEBUG);
1824
1825         $connection = new StatusNetOAuth($api, $ckey, $csecret, $otoken, $osecret);
1826
1827         $result = $connection->post('statuses/retweet/' . $id);
1828
1829         logger('statusnet_is_retweet: result ' . print_r($result, true), LOGGER_DEBUG);
1830
1831         return isset($result->id);
1832 }