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