]> git.mxchange.org Git - friendica-addons.git/blob - statusnet/statusnet.php
fbpost: Beautifying the import to friendica
[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 <http://diekershoff.homeunix.net/friendika/profile/tobias>
7  */
8  
9 /*   StatusNet Plugin for Friendica
10  *
11  *   Author: Tobias Diekershoff
12  *           tobias.diekershoff@gmx.net
13  *
14  *   License:3-clause BSD license
15  *
16  *   Configuration:
17  *     To activate the plugin itself add it to the $a->config['system']['addon']
18  *     setting. After this, your user can configure their Twitter account settings
19  *     from "Settings -> Plugin Settings".
20  *
21  *     Requirements: PHP5, curl [Slinky library]
22  *
23  *     Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/StatusNet_Plugin
24  */
25
26 /***
27  * We have to alter the TwitterOAuth class a little bit to work with any StatusNet
28  * installation abroad. Basically it's only make the API path variable and be happy.
29  *
30  * Thank you guys for the Twitter compatible API!
31  */
32
33 define('STATUSNET_DEFAULT_POLL_INTERVAL', 5); // given in minutes
34
35 require_once('library/twitteroauth.php');
36
37 class StatusNetOAuth extends TwitterOAuth {
38     function get_maxlength() {
39         $config = $this->get($this->host . 'statusnet/config.json');
40         return $config->site->textlimit;
41     }
42     function accessTokenURL()  { return $this->host.'oauth/access_token'; }
43     function authenticateURL() { return $this->host.'oauth/authenticate'; } 
44     function authorizeURL() { return $this->host.'oauth/authorize'; }
45     function requestTokenURL() { return $this->host.'oauth/request_token'; }
46     function __construct($apipath, $consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
47         parent::__construct($consumer_key, $consumer_secret, $oauth_token, $oauth_token_secret);
48         $this->host = $apipath;
49     }
50   /**
51    * Make an HTTP request
52    *
53    * @return API results
54    *
55    * Copied here from the twitteroauth library and complemented by applying the proxy settings of friendica
56    */
57   function http($url, $method, $postfields = NULL) {
58     $this->http_info = array();
59     $ci = curl_init();
60     /* Curl settings */
61     $prx = get_config('system','proxy');
62     if(strlen($prx)) {
63         curl_setopt($ci, CURLOPT_HTTPPROXYTUNNEL, 1);
64         curl_setopt($ci, CURLOPT_PROXY, $prx);
65         $prxusr = get_config('system','proxyuser');
66         if(strlen($prxusr))
67             curl_setopt($ci, CURLOPT_PROXYUSERPWD, $prxusr);
68     }
69     curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
70     curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
71     curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
72     curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
73     curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
74     curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
75     curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
76     curl_setopt($ci, CURLOPT_HEADER, FALSE);
77
78     switch ($method) {
79       case 'POST':
80         curl_setopt($ci, CURLOPT_POST, TRUE);
81         if (!empty($postfields)) {
82           curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
83         }
84         break;
85       case 'DELETE':
86         curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
87         if (!empty($postfields)) {
88           $url = "{$url}?{$postfields}";
89         }
90     }
91
92     curl_setopt($ci, CURLOPT_URL, $url);
93     $response = curl_exec($ci);
94     $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
95     $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
96     $this->url = $url;
97     curl_close ($ci);
98     return $response;
99   }
100 }
101
102 function statusnet_install() {
103         //  we need some hooks, for the configuration and for sending tweets
104         register_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
105         register_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
106         register_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
107         register_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
108         register_hook('jot_networks',    'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
109         register_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
110         logger("installed statusnet");
111 }
112
113
114 function statusnet_uninstall() {
115         unregister_hook('connector_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
116         unregister_hook('connector_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
117         unregister_hook('notifier_normal', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
118         unregister_hook('post_local', 'addon/statusnet/statusnet.php', 'statusnet_post_local');
119         unregister_hook('jot_networks',    'addon/statusnet/statusnet.php', 'statusnet_jot_nets');
120         unregister_hook('cron', 'addon/statusnet/statusnet.php', 'statusnet_cron');
121
122         // old setting - remove only
123         unregister_hook('post_local_end', 'addon/statusnet/statusnet.php', 'statusnet_post_hook');
124         unregister_hook('plugin_settings', 'addon/statusnet/statusnet.php', 'statusnet_settings'); 
125         unregister_hook('plugin_settings_post', 'addon/statusnet/statusnet.php', 'statusnet_settings_post');
126
127 }
128
129 function statusnet_jot_nets(&$a,&$b) {
130         if(! local_user())
131                 return;
132
133         $statusnet_post = get_pconfig(local_user(),'statusnet','post');
134         if(intval($statusnet_post) == 1) {
135                 $statusnet_defpost = get_pconfig(local_user(),'statusnet','post_by_default');
136                 $selected = ((intval($statusnet_defpost) == 1) ? ' checked="checked" ' : '');
137                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="statusnet_enable"' . $selected . ' value="1" /> ' 
138                         . t('Post to StatusNet') . '</div>';
139         }
140 }
141
142 function statusnet_settings_post ($a,$post) {
143         if(! local_user())
144             return;
145         // don't check statusnet settings if statusnet submit button is not clicked
146         if (!x($_POST,'statusnet-submit')) return;
147         
148         if (isset($_POST['statusnet-disconnect'])) {
149             /***
150              * if the statusnet-disconnect checkbox is set, clear the statusnet configuration
151              */
152             del_pconfig(local_user(), 'statusnet', 'consumerkey');
153             del_pconfig(local_user(), 'statusnet', 'consumersecret');
154             del_pconfig(local_user(), 'statusnet', 'post');
155             del_pconfig(local_user(), 'statusnet', 'post_by_default');
156             del_pconfig(local_user(), 'statusnet', 'oauthtoken');
157             del_pconfig(local_user(), 'statusnet', 'oauthsecret');
158             del_pconfig(local_user(), 'statusnet', 'baseapi');
159             del_pconfig(local_user(), 'statusnet', 'post_taglinks');
160             del_pconfig(local_user(), 'statusnet', 'lastid');
161             del_pconfig(local_user(), 'statusnet', 'mirror_posts');
162             del_pconfig(local_user(), 'statusnet', 'intelligent_shortening');
163         } else {
164             if (isset($_POST['statusnet-preconf-apiurl'])) {
165                 /***
166                  * If the user used one of the preconfigured StatusNet server credentials
167                  * use them. All the data are available in the global config.
168                  * Check the API Url never the less and blame the admin if it's not working ^^
169                  */
170                 $globalsn = get_config('statusnet', 'sites');
171                 foreach ( $globalsn as $asn) {
172                     if ($asn['apiurl'] == $_POST['statusnet-preconf-apiurl'] ) {
173                         $apibase = $asn['apiurl'];
174                         $c = fetch_url( $apibase . 'statusnet/version.xml' );
175                         if (strlen($c) > 0) {
176                             set_pconfig(local_user(), 'statusnet', 'consumerkey', $asn['consumerkey'] );
177                             set_pconfig(local_user(), 'statusnet', 'consumersecret', $asn['consumersecret'] );
178                             set_pconfig(local_user(), 'statusnet', 'baseapi', $asn['apiurl'] );
179                         } else {
180                             notice( t('Please contact your site administrator.<br />The provided API URL is not valid.').EOL.$asn['apiurl'].EOL );
181                         }
182                     }
183                 }
184                 goaway($a->get_baseurl().'/settings/connectors');
185             } else {
186             if (isset($_POST['statusnet-consumersecret'])) {
187                 //  check if we can reach the API of the StatusNet server
188                 //  we'll check the API Version for that, if we don't get one we'll try to fix the path but will
189                 //  resign quickly after this one try to fix the path ;-)
190                 $apibase = $_POST['statusnet-baseapi'];
191                 $c = fetch_url( $apibase . 'statusnet/version.xml' );
192                 if (strlen($c) > 0) {
193                     //  ok the API path is correct, let's save the settings
194                     set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
195                     set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
196                     set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
197                 } else {
198                     //  the API path is not correct, maybe missing trailing / ?
199                     $apibase = $apibase . '/';
200                     $c = fetch_url( $apibase . 'statusnet/version.xml' );
201                     if (strlen($c) > 0) {
202                         //  ok the API path is now correct, let's save the settings
203                         set_pconfig(local_user(), 'statusnet', 'consumerkey', $_POST['statusnet-consumerkey']);
204                         set_pconfig(local_user(), 'statusnet', 'consumersecret', $_POST['statusnet-consumersecret']);
205                         set_pconfig(local_user(), 'statusnet', 'baseapi', $apibase );
206                     } else {
207                         //  still not the correct API base, let's do noting
208                         notice( t('We could not contact the StatusNet API with the Path you entered.').EOL );
209                     }
210                 }
211                 goaway($a->get_baseurl().'/settings/connectors');
212             } else {
213                 if (isset($_POST['statusnet-pin'])) {
214                         //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
215                     $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
216                                         $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey'  );
217                                         $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
218                                         //  the token and secret for which the PIN was generated were hidden in the settings
219                                         //  form as token and token2, we need a new connection to Twitter using these token
220                                         //  and secret to request a Access Token with the PIN
221                                         $connection = new StatusNetOAuth($api, $ckey, $csecret, $_POST['statusnet-token'], $_POST['statusnet-token2']);
222                                         $token   = $connection->getAccessToken( $_POST['statusnet-pin'] );
223                                         //  ok, now that we have the Access Token, save them in the user config
224                                         set_pconfig(local_user(),'statusnet', 'oauthtoken',  $token['oauth_token']);
225                                         set_pconfig(local_user(),'statusnet', 'oauthsecret', $token['oauth_token_secret']);
226                                         set_pconfig(local_user(),'statusnet', 'post', 1);
227                                         set_pconfig(local_user(),'statusnet', 'post_taglinks', 1);
228                     //  reload the Addon Settings page, if we don't do it see Bug #42
229                     goaway($a->get_baseurl().'/settings/connectors');
230                                 } else {
231                                         //  if no PIN is supplied in the POST variables, the user has changed the setting
232                                         //  to post a dent for every new __public__ posting to the wall
233                                         set_pconfig(local_user(),'statusnet','post',intval($_POST['statusnet-enable']));
234                                         set_pconfig(local_user(),'statusnet','post_by_default',intval($_POST['statusnet-default']));
235                                         set_pconfig(local_user(),'statusnet','post_taglinks',intval($_POST['statusnet-sendtaglinks']));
236                                         set_pconfig(local_user(), 'statusnet', 'mirror_posts', intval($_POST['statusnet-mirror']));
237                                         set_pconfig(local_user(), 'statusnet', 'intelligent_shortening', intval($_POST['statusnet-shortening']));
238                                         info( t('StatusNet settings updated.') . EOL);
239                 }}}}
240 }
241 function statusnet_settings(&$a,&$s) {
242         if(! local_user())
243                 return;
244         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/statusnet/statusnet.css' . '" media="all" />' . "\r\n";
245         /***
246          * 1) Check that we have a base api url and a consumer key & secret
247          * 2) If no OAuthtoken & stuff is present, generate button to get some
248          *    allow the user to cancel the connection process at this step
249          * 3) Checkbox for "Send public notices (respect size limitation)
250          */
251         $api     = get_pconfig(local_user(), 'statusnet', 'baseapi');
252         $ckey    = get_pconfig(local_user(), 'statusnet', 'consumerkey' );
253         $csecret = get_pconfig(local_user(), 'statusnet', 'consumersecret' );
254         $otoken  = get_pconfig(local_user(), 'statusnet', 'oauthtoken'  );
255         $osecret = get_pconfig(local_user(), 'statusnet', 'oauthsecret' );
256         $enabled = get_pconfig(local_user(), 'statusnet', 'post');
257         $checked = (($enabled) ? ' checked="checked" ' : '');
258         $defenabled = get_pconfig(local_user(),'statusnet','post_by_default');
259         $defchecked = (($defenabled) ? ' checked="checked" ' : '');
260         $linksenabled = get_pconfig(local_user(),'statusnet','post_taglinks');
261         $linkschecked = (($linksenabled) ? ' checked="checked" ' : '');
262
263         $mirrorenabled = get_pconfig(local_user(),'statusnet','mirror_posts');
264         $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
265         $shorteningenabled = get_pconfig(local_user(),'statusnet','intelligent_shortening');
266         $shorteningchecked = (($shorteningenabled) ? ' checked="checked" ' : '');
267
268         $s .= '<div class="settings-block">';
269         $s .= '<h3>'. t('StatusNet Posting Settings').'</h3>';
270
271         if ( (!$ckey) && (!$csecret) ) {
272                 /***
273                  * no consumer keys
274                  */
275             $globalsn = get_config('statusnet', 'sites');
276             /***
277              * lets check if we have one or more globally configured StatusNet
278              * server OAuth credentials in the configuration. If so offer them
279              * with a little explanation to the user as choice - otherwise
280              * ignore this option entirely.
281              */
282             if (! $globalsn == null) {
283                 $s .= '<h4>' . t('Globally Available StatusNet OAuthKeys') . '</h4>';
284                 $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>';
285                 $s .= '<div id="statusnet-preconf-wrapper">';
286                 foreach ($globalsn as $asn) {
287                     $s .= '<input type="radio" name="statusnet-preconf-apiurl" value="'. $asn['apiurl'] .'">'. $asn['sitename'] .'<br />';
288                 }
289                 $s .= '<p></p><div class="clear"></div></div>';
290                 $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
291             }
292             $s .= '<h4>' . t('Provide your own OAuth Credentials') . '</h4>';
293             $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>';
294             $s .= '<div id="statusnet-consumer-wrapper">';
295             $s .= '<label id="statusnet-consumerkey-label" for="statusnet-consumerkey">'. t('OAuth Consumer Key') .'</label>';
296             $s .= '<input id="statusnet-consumerkey" type="text" name="statusnet-consumerkey" size="35" /><br />';
297             $s .= '<div class="clear"></div>';
298             $s .= '<label id="statusnet-consumersecret-label" for="statusnet-consumersecret">'. t('OAuth Consumer Secret') .'</label>';
299             $s .= '<input id="statusnet-consumersecret" type="text" name="statusnet-consumersecret" size="35" /><br />';
300             $s .= '<div class="clear"></div>';
301             $s .= '<label id="statusnet-baseapi-label" for="statusnet-baseapi">'. t("Base API Path \x28remember the trailing /\x29") .'</label>';
302             $s .= '<input id="statusnet-baseapi" type="text" name="statusnet-baseapi" size="35" /><br />';
303             $s .= '<p></p><div class="clear"></div></div>';
304             $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
305         } else {
306                 /***
307                  * ok we have a consumer key pair now look into the OAuth stuff
308                  */
309                 if ( (!$otoken) && (!$osecret) ) {
310                         /***
311                          * the user has not yet connected the account to statusnet
312                          * get a temporary OAuth key/secret pair and display a button with
313                          * which the user can request a PIN to connect the account to a
314                          * account at statusnet
315                          */
316                         $connection = new StatusNetOAuth($api, $ckey, $csecret);
317                         $request_token = $connection->getRequestToken('oob');
318                         $token = $request_token['oauth_token'];
319                         /***
320                          *  make some nice form
321                          */
322                         $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>';
323                         $s .= '<a href="'.$connection->getAuthorizeURL($token,False).'" target="_statusnet"><img src="addon/statusnet/signinwithstatusnet.png" alt="'. t('Log in with StatusNet') .'"></a>';
324                         $s .= '<div id="statusnet-pin-wrapper">';
325                         $s .= '<label id="statusnet-pin-label" for="statusnet-pin">'. t('Copy the security code from StatusNet here') .'</label>';
326                         $s .= '<input id="statusnet-pin" type="text" name="statusnet-pin" />';
327                         $s .= '<input id="statusnet-token" type="hidden" name="statusnet-token" value="'.$token.'" />';
328                         $s .= '<input id="statusnet-token2" type="hidden" name="statusnet-token2" value="'.$request_token['oauth_token_secret'].'" />';
329                         $s .= '</div><div class="clear"></div>';
330                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
331                         $s .= '<h4>'.t('Cancel Connection Process').'</h4>';
332                         $s .= '<div id="statusnet-cancel-wrapper">';
333                         $s .= '<p>'.t('Current StatusNet API is').': '.$api.'</p>';
334                         $s .= '<label id="statusnet-cancel-label" for="statusnet-cancel">'. t('Cancel StatusNet Connection') . '</label>';
335                         $s .= '<input id="statusnet-cancel" type="checkbox" name="statusnet-disconnect" value="1" />';
336                         $s .= '</div><div class="clear"></div>';
337                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
338                 } else {
339                         /***
340                          *  we have an OAuth key / secret pair for the user
341                          *  so let's give a chance to disable the postings to statusnet
342                          */
343                         $connection = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
344                         $details = $connection->get('account/verify_credentials');
345                         $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>';
346                         $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>';
347                         if ($a->user['hidewall']) {
348                             $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>';
349                         }
350                         $s .= '<div id="statusnet-enable-wrapper">';
351                         $s .= '<label id="statusnet-enable-label" for="statusnet-checkbox">'. t('Allow posting to StatusNet') .'</label>';
352                         $s .= '<input id="statusnet-checkbox" type="checkbox" name="statusnet-enable" value="1" ' . $checked . '/>';
353                         $s .= '<div class="clear"></div>';
354                         $s .= '<label id="statusnet-default-label" for="statusnet-default">'. t('Send public postings to StatusNet by default') .'</label>';
355                         $s .= '<input id="statusnet-default" type="checkbox" name="statusnet-default" value="1" ' . $defchecked . '/>';
356                         $s .= '<div class="clear"></div>';
357
358                         $s .= '<label id="statusnet-mirror-label" for="statusnet-mirror">'.t('Mirror all posts from statusnet that are no replies or repeated messages').'</label>';
359                         $s .= '<input id="statusnet-mirror" type="checkbox" name="statusnet-mirror" value="1" '. $mirrorchecked . '/>';
360                         $s .= '<div class="clear"></div>';
361
362                         $s .= '<label id="statusnet-shortening-label" for="statusnet-shortening">'.t('Shortening method that optimizes the post').'</label>';
363                         $s .= '<input id="statusnet-shortening" type="checkbox" name="statusnet-shortening" value="1" '. $shorteningchecked . '/>';
364                         $s .= '<div class="clear"></div>';
365
366                         $s .= '<label id="statusnet-sendtaglinks-label" for="statusnet-sendtaglinks">'.t('Send linked #-tags and @-names to StatusNet').'</label>';
367                         $s .= '<input id="statusnet-sendtaglinks" type="checkbox" name="statusnet-sendtaglinks" value="1" '. $linkschecked . '/>';
368                         $s .= '</div><div class="clear"></div>';
369
370                         $s .= '<div id="statusnet-disconnect-wrapper">';
371                         $s .= '<label id="statusnet-disconnect-label" for="statusnet-disconnect">'. t('Clear OAuth configuration') .'</label>';
372                         $s .= '<input id="statusnet-disconnect" type="checkbox" name="statusnet-disconnect" value="1" />';
373                         $s .= '</div><div class="clear"></div>';
374                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="statusnet-submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
375                 }
376         }
377         $s .= '</div><div class="clear"></div></div>';
378 }
379
380
381 function statusnet_post_local(&$a,&$b) {
382         if($b['edit'])
383                 return;
384
385         if((local_user()) && (local_user() == $b['uid']) && (! $b['private'])) {
386
387                 $statusnet_post = get_pconfig(local_user(),'statusnet','post');
388                 $statusnet_enable = (($statusnet_post && x($_REQUEST,'statusnet_enable')) ? intval($_REQUEST['statusnet_enable']) : 0);
389
390                 // if API is used, default to the chosen settings
391                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'statusnet','post_by_default')))
392                         $statusnet_enable = 1;
393
394        if(! $statusnet_enable)
395             return;
396
397        if(strlen($b['postopts']))
398            $b['postopts'] .= ',';
399        $b['postopts'] .= 'statusnet';
400     }
401 }
402
403 if (! function_exists( 'short_link' )) {
404 function short_link($url) {
405     require_once('library/slinky.php');
406     $slinky = new Slinky( $url );
407     $yourls_url = get_config('yourls','url1');
408     if ($yourls_url) {
409             $yourls_username = get_config('yourls','username1');
410             $yourls_password = get_config('yourls', 'password1');
411             $yourls_ssl = get_config('yourls', 'ssl1');
412             $yourls = new Slinky_YourLS();
413             $yourls->set( 'username', $yourls_username );
414             $yourls->set( 'password', $yourls_password );
415             $yourls->set( 'ssl', $yourls_ssl );
416             $yourls->set( 'yourls-url', $yourls_url );
417             $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
418     }
419     else {
420             // setup a cascade of shortening services
421             // try to get a short link from these services
422             // in the order ur1.ca, trim, id.gd, tinyurl
423             $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
424     }
425     return $slinky->short();
426 } };
427
428 function statusnet_shortenmsg($b, $max_char) {
429         require_once("include/bbcode.php");
430         require_once("include/html2plain.php");
431
432         // Looking for the first image
433         $image = '';
434         if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
435                 $image = $matches[3];
436
437         if ($image == '')
438                 if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
439                         $image = $matches[1];
440
441         $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
442
443         // When saved into the database the content is sent through htmlspecialchars
444         // That means that we have to decode all image-urls
445         $image = htmlspecialchars_decode($image);
446
447         $body = $b["body"];
448         if ($b["title"] != "")
449                 $body = $b["title"]."\n\n".$body;
450
451         // Add some newlines so that the message could be cut better
452         $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
453                                 array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
454
455         // remove the recycle signs and the names since they aren't helpful on twitter
456         // recycle 1
457         $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
458         $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
459         // recycle 2 (Test)
460         $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
461         $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
462
463         // remove the share element
464         $body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
465
466         // At first convert the text to html
467         $html = bbcode($body, false, false);
468
469         // Then convert it to plain text
470         //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
471         $msg = trim(html2plain($html, 0, true));
472         $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
473
474         // Removing multiple newlines
475         while (strpos($msg, "\n\n\n") !== false)
476                 $msg = str_replace("\n\n\n", "\n\n", $msg);
477
478         // Removing multiple spaces
479         while (strpos($msg, "  ") !== false)
480                 $msg = str_replace("  ", " ", $msg);
481
482         // Removing URLs
483         $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
484
485         $msg = trim($msg);
486
487         $link = '';
488         // look for bookmark-bbcode and handle it with priority
489         if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
490                 $link = $matches[1];
491
492         $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
493
494         // If there is no bookmark element then take the first link
495         if ($link == '') {
496                 $links = collecturls($html);
497                 if (sizeof($links) > 0) {
498                         reset($links);
499                         $link = current($links);
500                 }
501                 $multiplelinks = (sizeof($links) > 1);
502         }
503
504         $msglink = "";
505         if ($multiplelinks)
506                 $msglink = $b["plink"];
507         else if ($link != "")
508                 $msglink = $link;
509         else if ($multipleimages)
510                 $msglink = $b["plink"];
511         else if ($image != "")
512                 $msglink = $image;
513
514         if (($msglink == "") and strlen($msg) > $max_char)
515                 $msglink = $b["plink"];
516
517         if (strlen($msglink) > 20)
518                 $msglink = short_link($msglink);
519
520         if (strlen(trim($msg." ".$msglink)) > $max_char) {
521                 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
522                 $lastchar = substr($msg, -1);
523                 $msg = substr($msg, 0, -1);
524                 $pos = strrpos($msg, "\n");
525                 if ($pos > 0)
526                         $msg = substr($msg, 0, $pos);
527                 else if ($lastchar != "\n")
528                         $msg = substr($msg, 0, -3)."...";
529         }
530         $msg = str_replace("\n", " ", $msg);
531
532         // Removing multiple spaces - again
533         while (strpos($msg, "  ") !== false)
534                 $msg = str_replace("  ", " ", $msg);
535
536         return(array("msg"=>trim($msg." ".$msglink), "image"=>$image));
537 }
538
539 function statusnet_post_hook(&$a,&$b) {
540
541         /**
542          * Post to statusnet
543          */
544
545         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
546                 return;
547
548         if(! strstr($b['postopts'],'statusnet'))
549                 return;
550
551         // if posts comes from statusnet don't send it back
552         if($b['app'] == "StatusNet")
553                 return;
554
555         logger('statusnet post invoked');
556
557         load_pconfig($b['uid'], 'statusnet');
558
559         $api     = get_pconfig($b['uid'], 'statusnet', 'baseapi');
560         $ckey    = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
561         $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
562         $otoken  = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
563         $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
564         $intelligent_shortening = get_pconfig($b['uid'], 'statusnet', 'intelligent_shortening');
565
566         // Global setting overrides this
567         if (get_config('statusnet','intelligent_shortening'))
568                 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
569
570         if($ckey && $csecret && $otoken && $osecret) {
571
572                 require_once('include/bbcode.php');
573                 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
574                 $max_char = $dent->get_maxlength(); // max. length for a dent
575                 // we will only work with up to two times the length of the dent
576                 // we can later send to StatusNet. This way we can "gain" some
577                 // information during shortening of potential links but do not
578                 // shorten all the links in a 200000 character long essay.
579
580                 $tempfile = "";
581                 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
582                 if (!$intelligent_shortening) {
583                         if (! $b['title']=='') {
584                                 $tmp = $b['title'].": \n".$b['body'];
585         //                    $tmp = substr($tmp, 0, 4*$max_char);
586                         } else {
587                             $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
588                         }
589                         // if [url=bla][img]blub.png[/img][/url] get blub.png
590                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
591                         // preserve links to images, videos and audios
592                         $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
593                         $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
594                         $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
595                         $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
596                         $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
597                         $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
598                         $linksenabled = get_pconfig($b['uid'],'statusnet','post_taglinks');
599                         // if a #tag is linked, don't send the [url] over to SN
600                         // that is, don't send if the option is not set in the 
601                         // connector settings
602                         if ($linksenabled=='0') {
603                                 // #-tags
604                                 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
605                                 // @-mentions
606                                 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
607                                 // recycle 1
608                                 $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
609                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
610                                 // recycle 2 (test)
611                                 $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
612                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
613                         }
614                         // preserve links to webpages
615                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
616                         $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
617                         // find all http or https links in the body of the entry and 
618                         // apply the shortener if the link is longer then 20 characters 
619                         if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
620                             preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls  );
621                             foreach ($allurls as $url) {
622                                 foreach ($url as $u) {
623                                     if (strlen($u)>20) {
624                                         $sl = short_link($u);
625                                         $tmp = str_replace( $u, $sl, $tmp );
626                                     }
627                                 }
628                             }
629                         }
630                         // ok, all the links we want to send out are save, now strip 
631                         // away the remaining bbcode
632                         //$msg = strip_tags(bbcode($tmp, false, false));
633                         $msg = bbcode($tmp, false, false);
634                         $msg = str_replace(array('<br>','<br />'),"\n",$msg);
635                         $msg = strip_tags($msg);
636
637                         // quotes not working - let's try this
638                         $msg = html_entity_decode($msg);
639
640                         if (( strlen($msg) > $max_char) && $max_char > 0) {
641                                 $shortlink = short_link( $b['plink'] );
642                                 // the new message will be shortened such that "... $shortlink"
643                                 // will fit into the character limit
644                                 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
645                                 $msg = str_replace(array('<br>','<br />'),' ',$msg);
646                                 $e = explode(' ', $msg);
647                                 //  remove the last word from the cut down message to 
648                                 //  avoid sending cut words to the MicroBlog
649                                 array_pop($e);
650                                 $msg = implode(' ', $e);
651                                 $msg .= '... ' . $shortlink;
652                         }
653
654                         $msg = trim($msg);
655                         $postdata = array('status' => $msg);
656                 } else {
657                         $msgarr = statusnet_shortenmsg($b, $max_char);
658                         $msg = $msgarr["msg"];
659                         $image = $msgarr["image"];
660                         if ($image != "") {
661                                 $imagedata = file_get_contents($image);
662                                 $tempfile = tempnam(get_config("system","temppath"), "upload");
663                                 file_put_contents($tempfile, $imagedata);
664                                 $postdata = array("status"=>$msg, "media"=>"@".$tempfile);
665                         } else
666                                 $postdata = array("status"=>$msg);
667                 }
668
669                 // and now dent it :-)
670                 if(strlen($msg)) {
671                     //$result = $dent->post('statuses/update', array('status' => $msg));
672                     $result = $dent->post('statuses/update', $postdata);
673                     logger('statusnet_post send, result: ' . print_r($result, true).
674                            "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
675                     if ($result->error) {
676                         logger('Send to StatusNet failed: "' . $result->error . '"');
677                     }
678                 }
679                 if ($tempfile != "")
680                         unlink($tempfile);
681         }
682 }
683
684 function statusnet_plugin_admin_post(&$a){
685         
686         $sites = array();
687         
688         foreach($_POST['sitename'] as $id=>$sitename){
689                 $sitename=trim($sitename);
690                 $apiurl=trim($_POST['apiurl'][$id]);
691                 $secret=trim($_POST['secret'][$id]);
692                 $key=trim($_POST['key'][$id]);
693                 if ($sitename!="" &&
694                         $apiurl!="" &&
695                         $secret!="" &&
696                         $key!="" &&
697                         !x($_POST['delete'][$id])){
698                                 
699                                 $sites[] = Array(
700                                         'sitename' => $sitename,
701                                         'apiurl' => $apiurl,
702                                         'consumersecret' => $secret,
703                                         'consumerkey' => $key
704                                 );
705                 }
706         }
707         
708         $sites = set_config('statusnet','sites', $sites);
709         
710 }
711
712 function statusnet_plugin_admin(&$a, &$o){
713
714         $sites = get_config('statusnet','sites');
715         $sitesform=array();
716         if (is_array($sites)){
717                 foreach($sites as $id=>$s){
718                         $sitesform[] = Array(
719                                 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
720                                 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
721                                 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
722                                 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
723                                 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
724                         );
725                 }
726         }
727         /* empty form to add new site */
728         $id++;
729         $sitesform[] = Array(
730                 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
731                 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
732                 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
733                 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
734         );
735
736         $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
737         $o = replace_macros($t, array(
738                 '$submit' => t('Submit'),
739                 '$sites' => $sitesform,
740         ));
741 }
742
743 function statusnet_cron($a,$b) {
744         $last = get_config('statusnet','last_poll');
745
746         $poll_interval = intval(get_config('statusnet','poll_interval'));
747         if(! $poll_interval)
748                 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
749
750         if($last) {
751                 $next = $last + ($poll_interval * 60);
752                 if($next > time()) {
753                         logger('statusnet: poll intervall not reached');
754                         return;
755                 }
756         }
757         logger('statusnet: cron_start');
758
759         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
760         if(count($r)) {
761                 foreach($r as $rr) {
762                         logger('statusnet: fetching for user '.$rr['uid']);
763                         statusnet_fetchtimeline($a, $rr['uid']);
764                 }
765         }
766
767         logger('statusnet: cron_end');
768
769         set_config('statusnet','last_poll', time());
770 }
771
772 function statusnet_fetchtimeline($a, $uid) {
773         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
774         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
775         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
776         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
777         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
778         $lastid  = get_pconfig($uid, 'statusnet', 'lastid');
779
780         $application_name  = get_config('statusnet', 'application_name');
781
782         if ($application_name == "")
783                 $application_name = $a->get_hostname();
784
785         $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
786
787         $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
788
789         if ($lastid <> "")
790                 $parameters["since_id"] = $lastid;
791
792         $items = $connection->get('statuses/user_timeline', $parameters);
793         $posts = array_reverse($items);
794
795         foreach ($posts as $post) {
796                 if ($post->id > $lastid)
797                         $lastid = $post->id;
798
799                 if (is_object($post->retweeted_status))
800                         continue;
801
802                 if ($post->in_reply_to_status_id != "")
803                         continue;
804
805                 if (!strpos($post->source, $application_name)) {
806                         $_SESSION["authenticated"] = true;
807                         $_SESSION["uid"] = $uid;
808
809                         $_REQUEST["type"] = "wall";
810                         $_REQUEST["api_source"] = true;
811                         $_REQUEST["profile_uid"] = $uid;
812                         $_REQUEST["source"] = "StatusNet";
813
814                         //$_REQUEST["date"] = $post->created_at;
815
816                         $_REQUEST["body"] = $post->text;
817                         if (is_string($post->place->name))
818                                 $_REQUEST["location"] = $post->place->name;
819
820                         if (is_string($post->place->full_name))
821                                 $_REQUEST["location"] = $post->place->full_name;
822
823                         if (is_array($post->geo->coordinates))
824                                 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
825
826                         if (is_array($post->coordinates->coordinates))
827                                 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
828
829                         //print_r($_REQUEST);
830                         if ($_REQUEST["body"] != "") {
831                                 logger('statusnet: posting for user '.$uid);
832
833                                 require_once('mod/item.php');
834                                 item_post($a);
835                         }
836                 }
837         }
838         set_pconfig($uid, 'statusnet', 'lastid', $lastid);
839 }
840