]> git.mxchange.org Git - friendica-addons.git/blob - statusnet/statusnet.php
typo
[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 StatusNet, 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         if (strpos($body, "[bookmark") !== false) {
452                 // splitting the text in two parts:
453                 // before and after the bookmark
454                 $pos = strpos($body, "[bookmark");
455                 $body1 = substr($body, 0, $pos);
456                 $body2 = substr($body, $pos);
457
458                 // Removing all quotes after the bookmark
459                 // they are mostly only the content after the bookmark.
460                 $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
461                 $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
462                 $body = $body1.$body2;
463         }
464
465         // Add some newlines so that the message could be cut better
466         $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
467                                 array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
468
469         // remove the recycle signs and the names since they aren't helpful on twitter
470         // recycle 1
471         $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
472         $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
473         // recycle 2 (Test)
474         $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
475         $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
476
477         // remove the share element
478         $body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
479
480         // At first convert the text to html
481         $html = bbcode($body, false, false);
482
483         // Then convert it to plain text
484         //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
485         $msg = trim(html2plain($html, 0, true));
486         $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
487
488         // Removing multiple newlines
489         while (strpos($msg, "\n\n\n") !== false)
490                 $msg = str_replace("\n\n\n", "\n\n", $msg);
491
492         // Removing multiple spaces
493         while (strpos($msg, "  ") !== false)
494                 $msg = str_replace("  ", " ", $msg);
495
496         // Removing URLs
497         $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
498
499         $msg = trim($msg);
500
501         $link = '';
502         // look for bookmark-bbcode and handle it with priority
503         if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
504                 $link = $matches[1];
505
506         $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
507
508         // If there is no bookmark element then take the first link
509         if ($link == '') {
510                 $links = collecturls($html);
511                 if (sizeof($links) > 0) {
512                         reset($links);
513                         $link = current($links);
514                 }
515                 $multiplelinks = (sizeof($links) > 1);
516         }
517
518         $msglink = "";
519         if ($multiplelinks)
520                 $msglink = $b["plink"];
521         else if ($link != "")
522                 $msglink = $link;
523         else if ($multipleimages)
524                 $msglink = $b["plink"];
525         else if ($image != "")
526                 $msglink = $image;
527
528         if (($msglink == "") and strlen($msg) > $max_char)
529                 $msglink = $b["plink"];
530
531         if (strlen($msglink) > 20)
532                 $msglink = short_link($msglink);
533
534         if (strlen(trim($msg." ".$msglink)) > $max_char) {
535                 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
536                 $lastchar = substr($msg, -1);
537                 $msg = substr($msg, 0, -1);
538                 $pos = strrpos($msg, "\n");
539                 if ($pos > 0)
540                         $msg = substr($msg, 0, $pos);
541                 else if ($lastchar != "\n")
542                         $msg = substr($msg, 0, -3)."...";
543         }
544         $msg = str_replace("\n", " ", $msg);
545
546         // Removing multiple spaces - again
547         while (strpos($msg, "  ") !== false)
548                 $msg = str_replace("  ", " ", $msg);
549
550         return(array("msg"=>trim($msg." ".$msglink), "image"=>$image));
551 }
552
553 function statusnet_post_hook(&$a,&$b) {
554
555         /**
556          * Post to statusnet
557          */
558
559         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
560                 return;
561
562         if(! strstr($b['postopts'],'statusnet'))
563                 return;
564
565         // if posts comes from statusnet don't send it back
566         if($b['app'] == "StatusNet")
567                 return;
568
569         logger('statusnet post invoked');
570
571         load_pconfig($b['uid'], 'statusnet');
572
573         $api     = get_pconfig($b['uid'], 'statusnet', 'baseapi');
574         $ckey    = get_pconfig($b['uid'], 'statusnet', 'consumerkey');
575         $csecret = get_pconfig($b['uid'], 'statusnet', 'consumersecret');
576         $otoken  = get_pconfig($b['uid'], 'statusnet', 'oauthtoken');
577         $osecret = get_pconfig($b['uid'], 'statusnet', 'oauthsecret');
578         $intelligent_shortening = get_pconfig($b['uid'], 'statusnet', 'intelligent_shortening');
579
580         // Global setting overrides this
581         if (get_config('statusnet','intelligent_shortening'))
582                 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
583
584         if($ckey && $csecret && $otoken && $osecret) {
585
586                 require_once('include/bbcode.php');
587                 $dent = new StatusNetOAuth($api,$ckey,$csecret,$otoken,$osecret);
588                 $max_char = $dent->get_maxlength(); // max. length for a dent
589                 // we will only work with up to two times the length of the dent
590                 // we can later send to StatusNet. This way we can "gain" some
591                 // information during shortening of potential links but do not
592                 // shorten all the links in a 200000 character long essay.
593
594                 $tempfile = "";
595                 $intelligent_shortening = get_config('statusnet','intelligent_shortening');
596                 if (!$intelligent_shortening) {
597                         if (! $b['title']=='') {
598                                 $tmp = $b['title'].": \n".$b['body'];
599         //                    $tmp = substr($tmp, 0, 4*$max_char);
600                         } else {
601                             $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
602                         }
603                         // if [url=bla][img]blub.png[/img][/url] get blub.png
604                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
605                         // preserve links to images, videos and audios
606                         $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
607                         $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
608                         $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
609                         $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
610                         $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
611                         $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
612                         $linksenabled = get_pconfig($b['uid'],'statusnet','post_taglinks');
613                         // if a #tag is linked, don't send the [url] over to SN
614                         // that is, don't send if the option is not set in the 
615                         // connector settings
616                         if ($linksenabled=='0') {
617                                 // #-tags
618                                 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
619                                 // @-mentions
620                                 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
621                                 // recycle 1
622                                 $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
623                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
624                                 // recycle 2 (test)
625                                 $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
626                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
627                         }
628                         // preserve links to webpages
629                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
630                         $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
631                         // find all http or https links in the body of the entry and 
632                         // apply the shortener if the link is longer then 20 characters 
633                         if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
634                             preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls  );
635                             foreach ($allurls as $url) {
636                                 foreach ($url as $u) {
637                                     if (strlen($u)>20) {
638                                         $sl = short_link($u);
639                                         $tmp = str_replace( $u, $sl, $tmp );
640                                     }
641                                 }
642                             }
643                         }
644                         // ok, all the links we want to send out are save, now strip 
645                         // away the remaining bbcode
646                         //$msg = strip_tags(bbcode($tmp, false, false));
647                         $msg = bbcode($tmp, false, false);
648                         $msg = str_replace(array('<br>','<br />'),"\n",$msg);
649                         $msg = strip_tags($msg);
650
651                         // quotes not working - let's try this
652                         $msg = html_entity_decode($msg);
653
654                         if (( strlen($msg) > $max_char) && $max_char > 0) {
655                                 $shortlink = short_link( $b['plink'] );
656                                 // the new message will be shortened such that "... $shortlink"
657                                 // will fit into the character limit
658                                 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
659                                 $msg = str_replace(array('<br>','<br />'),' ',$msg);
660                                 $e = explode(' ', $msg);
661                                 //  remove the last word from the cut down message to 
662                                 //  avoid sending cut words to the MicroBlog
663                                 array_pop($e);
664                                 $msg = implode(' ', $e);
665                                 $msg .= '... ' . $shortlink;
666                         }
667
668                         $msg = trim($msg);
669                         $postdata = array('status' => $msg);
670                 } else {
671                         $msgarr = statusnet_shortenmsg($b, $max_char);
672                         $msg = $msgarr["msg"];
673                         $image = $msgarr["image"];
674                         if ($image != "") {
675                                 $imagedata = file_get_contents($image);
676                                 $tempfile = tempnam(get_config("system","temppath"), "upload");
677                                 file_put_contents($tempfile, $imagedata);
678                                 $postdata = array("status"=>$msg, "media"=>"@".$tempfile);
679                         } else
680                                 $postdata = array("status"=>$msg);
681                 }
682
683                 // and now dent it :-)
684                 if(strlen($msg)) {
685                     //$result = $dent->post('statuses/update', array('status' => $msg));
686                     $result = $dent->post('statuses/update', $postdata);
687                     logger('statusnet_post send, result: ' . print_r($result, true).
688                            "\nmessage: ".$msg, LOGGER_DEBUG."\nOriginal post: ".print_r($b, true)."\nPost Data: ".print_r($postdata, true));
689                     if ($result->error) {
690                         logger('Send to StatusNet failed: "' . $result->error . '"');
691                     }
692                 }
693                 if ($tempfile != "")
694                         unlink($tempfile);
695         }
696 }
697
698 function statusnet_plugin_admin_post(&$a){
699         
700         $sites = array();
701         
702         foreach($_POST['sitename'] as $id=>$sitename){
703                 $sitename=trim($sitename);
704                 $apiurl=trim($_POST['apiurl'][$id]);
705                 $secret=trim($_POST['secret'][$id]);
706                 $key=trim($_POST['key'][$id]);
707                 $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'][$id])):'');
708                 if ($sitename!="" &&
709                         $apiurl!="" &&
710                         $secret!="" &&
711                         $key!="" &&
712                         !x($_POST['delete'][$id])){
713                                 
714                                 $sites[] = Array(
715                                         'sitename' => $sitename,
716                                         'apiurl' => $apiurl,
717                                         'consumersecret' => $secret,
718                                         'consumerkey' => $key,
719                                         'applicationname' => $applicationname
720                                 );
721                 }
722         }
723         
724         $sites = set_config('statusnet','sites', $sites);
725         
726 }
727
728 function statusnet_plugin_admin(&$a, &$o){
729
730         $sites = get_config('statusnet','sites');
731         $sitesform=array();
732         if (is_array($sites)){
733                 foreach($sites as $id=>$s){
734                         $sitesform[] = Array(
735                                 'sitename' => Array("sitename[$id]", "Site name", $s['sitename'], ""),
736                                 'apiurl' => Array("apiurl[$id]", "Api url", $s['apiurl'], ""),
737                                 'secret' => Array("secret[$id]", "Secret", $s['consumersecret'], ""),
738                                 'key' => Array("key[$id]", "Key", $s['consumerkey'], ""),
739                                 'applicationname' => Array("applicationname[$id]", "Application name", $s['applicationname'], ""),
740                                 'delete' => Array("delete[$id]", "Delete", False , "Check to delete this preset"),
741                         );
742                 }
743         }
744         /* empty form to add new site */
745         $id++;
746         $sitesform[] = Array(
747                 'sitename' => Array("sitename[$id]", t("Site name"), "", ""),
748                 'apiurl' => Array("apiurl[$id]", t("API URL"), "", ""),
749                 'secret' => Array("secret[$id]", t("Consumer Secret"), "", ""),
750                 'key' => Array("key[$id]", t("Consumer Key"), "", ""),
751                 'applicationname' => Array("applicationname[$id]", t("Application name"), "", ""),
752         );
753
754         $t = get_markup_template( "admin.tpl", "addon/statusnet/" );
755         $o = replace_macros($t, array(
756                 '$submit' => t('Submit'),
757                 '$sites' => $sitesform,
758         ));
759 }
760
761 function statusnet_cron($a,$b) {
762         $last = get_config('statusnet','last_poll');
763
764         $poll_interval = intval(get_config('statusnet','poll_interval'));
765         if(! $poll_interval)
766                 $poll_interval = STATUSNET_DEFAULT_POLL_INTERVAL;
767
768         if($last) {
769                 $next = $last + ($poll_interval * 60);
770                 if($next > time()) {
771                         logger('statusnet: poll intervall not reached');
772                         return;
773                 }
774         }
775         logger('statusnet: cron_start');
776
777         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'statusnet' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
778         if(count($r)) {
779                 foreach($r as $rr) {
780                         logger('statusnet: fetching for user '.$rr['uid']);
781                         statusnet_fetchtimeline($a, $rr['uid']);
782                 }
783         }
784
785         logger('statusnet: cron_end');
786
787         set_config('statusnet','last_poll', time());
788 }
789
790 function statusnet_fetchtimeline($a, $uid) {
791         $ckey    = get_pconfig($uid, 'statusnet', 'consumerkey');
792         $csecret = get_pconfig($uid, 'statusnet', 'consumersecret');
793         $api     = get_pconfig($uid, 'statusnet', 'baseapi');
794         $otoken  = get_pconfig($uid, 'statusnet', 'oauthtoken');
795         $osecret = get_pconfig($uid, 'statusnet', 'oauthsecret');
796         $lastid  = get_pconfig($uid, 'statusnet', 'lastid');
797
798         //  get the application name for the SN app
799         //  1st try personal config, then system config and fallback to the 
800         //  hostname of the node if neither one is set. 
801         $application_name  = get_pconfig( $uid, 'statusnet', 'application_name');
802         if ($application_name == "")
803                 $application_name  = get_config('statusnet', 'application_name');
804         if ($application_name == "")
805                 $application_name = $a->get_hostname();
806
807         $connection = new StatusNetOAuth($api, $ckey,$csecret,$otoken,$osecret);
808
809         $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
810
811         $first_time = ($lastid == "");
812
813         if ($lastid <> "")
814                 $parameters["since_id"] = $lastid;
815
816         $items = $connection->get('statuses/user_timeline', $parameters);
817         $posts = array_reverse($items);
818
819         if (count($posts)) {
820             foreach ($posts as $post) {
821                 if ($post->id > $lastid)
822                         $lastid = $post->id;
823
824                 if ($first_time)
825                         continue;
826
827                 if (is_object($post->retweeted_status))
828                         continue;
829
830                 if ($post->in_reply_to_status_id != "")
831                         continue;
832
833                 if (!strpos($post->source, $application_name)) {
834                         $_SESSION["authenticated"] = true;
835                         $_SESSION["uid"] = $uid;
836
837                         $_REQUEST["type"] = "wall";
838                         $_REQUEST["api_source"] = true;
839                         $_REQUEST["profile_uid"] = $uid;
840                         $_REQUEST["source"] = "StatusNet";
841
842                         //$_REQUEST["date"] = $post->created_at;
843
844                         $_REQUEST["body"] = $post->text;
845                         if (is_string($post->place->name))
846                                 $_REQUEST["location"] = $post->place->name;
847
848                         if (is_string($post->place->full_name))
849                                 $_REQUEST["location"] = $post->place->full_name;
850
851                         if (is_array($post->geo->coordinates))
852                                 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
853
854                         if (is_array($post->coordinates->coordinates))
855                                 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
856
857                         //print_r($_REQUEST);
858                         if ($_REQUEST["body"] != "") {
859                                 logger('statusnet: posting for user '.$uid);
860
861                                 require_once('mod/item.php');
862                                 item_post($a);
863                         }
864                 }
865             }
866         }
867         set_pconfig($uid, 'statusnet', 'lastid', $lastid);
868 }
869