]> git.mxchange.org Git - friendica-addons.git/blob - twitter/twitter.php
Statusnet/Twitter: When a message is less than 140 digits the post isn't modified...
[friendica-addons.git] / twitter / twitter.php
1 <?php
2 /**
3  * Name: Twitter Connector
4  * Description: Relay public postings to a connected Twitter account
5  * Version: 1.0.4
6  * Author: Tobias Diekershoff <http://diekershoff.homeunix.net/friendika/profile/tobias>
7  */
8
9
10 /*   Twitter Plugin for Friendica
11  *
12  *   Author: Tobias Diekershoff
13  *           tobias.diekershoff@gmx.net
14  *
15  *   License:3-clause BSD license
16  *
17  *   Configuration:
18  *     To use this plugin you need a OAuth Consumer key pair (key & secret)
19  *     you can get it from Twitter at https://twitter.com/apps
20  *
21  *     Register your Friendica site as "Client" application with "Read & Write" access
22  *     we do not need "Twitter as login". When you've registered the app you get the
23  *     OAuth Consumer key and secret pair for your application/site.
24  *
25  *     Add this key pair to your global .htconfig.php or use the admin panel.
26  *
27  *     $a->config['twitter']['consumerkey'] = 'your consumer_key here';
28  *     $a->config['twitter']['consumersecret'] = 'your consumer_secret here';
29  *
30  *     To activate the plugin itself add it to the $a->config['system']['addon']
31  *     setting. After this, your user can configure their Twitter account settings
32  *     from "Settings -> Plugin Settings".
33  *
34  *     Requirements: PHP5, curl [Slinky library]
35  *
36  *     Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/Twitter_Plugin
37  */
38
39 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
40
41 function twitter_install() {
42         //  we need some hooks, for the configuration and for sending tweets
43         register_hook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
44         register_hook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
45         register_hook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
46         register_hook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
47         register_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
48         register_hook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
49         logger("installed twitter");
50 }
51
52
53 function twitter_uninstall() {
54         unregister_hook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
55         unregister_hook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
56         unregister_hook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
57         unregister_hook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
58         unregister_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
59         unregister_hook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
60
61         // old setting - remove only
62         unregister_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
63         unregister_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
64         unregister_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
65
66 }
67
68 function twitter_jot_nets(&$a,&$b) {
69         if(! local_user())
70                 return;
71
72         $tw_post = get_pconfig(local_user(),'twitter','post');
73         if(intval($tw_post) == 1) {
74                 $tw_defpost = get_pconfig(local_user(),'twitter','post_by_default');
75                 $selected = ((intval($tw_defpost) == 1) ? ' checked="checked" ' : '');
76                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="twitter_enable"' . $selected . ' value="1" /> ' 
77                         . t('Post to Twitter') . '</div>';
78         }
79 }
80
81 function twitter_settings_post ($a,$post) {
82         if(! local_user())
83                 return;
84         // don't check twitter settings if twitter submit button is not clicked 
85         if (!x($_POST,'twitter-submit')) return;
86         
87         if (isset($_POST['twitter-disconnect'])) {
88                 /***
89                  * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
90                  * from the user configuration
91                  */
92                 del_pconfig(local_user(), 'twitter', 'consumerkey');
93                 del_pconfig(local_user(), 'twitter', 'consumersecret');
94                 del_pconfig(local_user(), 'twitter', 'oauthtoken');
95                 del_pconfig(local_user(), 'twitter', 'oauthsecret');
96                 del_pconfig(local_user(), 'twitter', 'post');
97                 del_pconfig(local_user(), 'twitter', 'post_by_default');
98                 del_pconfig(local_user(), 'twitter', 'post_taglinks');
99                 del_pconfig(local_user(), 'twitter', 'lastid');
100                 del_pconfig(local_user(), 'twitter', 'mirror_posts');
101                 del_pconfig(local_user(), 'twitter', 'intelligent_shortening');
102         } else {
103         if (isset($_POST['twitter-pin'])) {
104                 //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
105                 logger('got a Twitter PIN');
106                 require_once('library/twitteroauth.php');
107                 $ckey    = get_config('twitter', 'consumerkey');
108                 $csecret = get_config('twitter', 'consumersecret');
109                 //  the token and secret for which the PIN was generated were hidden in the settings
110                 //  form as token and token2, we need a new connection to Twitter using these token
111                 //  and secret to request a Access Token with the PIN
112                 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
113                 $token   = $connection->getAccessToken( $_POST['twitter-pin'] );
114                 //  ok, now that we have the Access Token, save them in the user config
115                 set_pconfig(local_user(),'twitter', 'oauthtoken',  $token['oauth_token']);
116                 set_pconfig(local_user(),'twitter', 'oauthsecret', $token['oauth_token_secret']);
117                 set_pconfig(local_user(),'twitter', 'post', 1);
118                 set_pconfig(local_user(),'twitter', 'post_taglinks', 1);
119                 //  reload the Addon Settings page, if we don't do it see Bug #42
120                 goaway($a->get_baseurl().'/settings/connectors');
121         } else {
122                 //  if no PIN is supplied in the POST variables, the user has changed the setting
123                 //  to post a tweet for every new __public__ posting to the wall
124                 set_pconfig(local_user(),'twitter','post',intval($_POST['twitter-enable']));
125                 set_pconfig(local_user(),'twitter','post_by_default',intval($_POST['twitter-default']));
126                 set_pconfig(local_user(),'twitter','post_taglinks',intval($_POST['twitter-sendtaglinks']));
127                 set_pconfig(local_user(), 'twitter', 'mirror_posts', intval($_POST['twitter-mirror']));
128                 set_pconfig(local_user(), 'twitter', 'intelligent_shortening', intval($_POST['twitter-shortening']));
129                 info( t('Twitter settings updated.') . EOL);
130         }}
131 }
132 function twitter_settings(&$a,&$s) {
133         if(! local_user())
134                 return;
135         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
136         /***
137          * 1) Check that we have global consumer key & secret
138          * 2) If no OAuthtoken & stuff is present, generate button to get some
139          * 3) Checkbox for "Send public notices (140 chars only)
140          */
141         $ckey    = get_config('twitter', 'consumerkey' );
142         $csecret = get_config('twitter', 'consumersecret' );
143         $otoken  = get_pconfig(local_user(), 'twitter', 'oauthtoken'  );
144         $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' );
145         $enabled = get_pconfig(local_user(), 'twitter', 'post');
146         $checked = (($enabled) ? ' checked="checked" ' : '');
147         $defenabled = get_pconfig(local_user(),'twitter','post_by_default');
148         $defchecked = (($defenabled) ? ' checked="checked" ' : '');
149         $linksenabled = get_pconfig(local_user(),'twitter','post_taglinks');
150         $linkschecked = (($linksenabled) ? ' checked="checked" ' : '');
151         $mirrorenabled = get_pconfig(local_user(),'twitter','mirror_posts');
152         $mirrorchecked = (($mirrorenabled) ? ' checked="checked" ' : '');
153         $shorteningenabled = get_pconfig(local_user(),'twitter','intelligent_shortening');
154         $shorteningchecked = (($shorteningenabled) ? ' checked="checked" ' : '');
155
156         $s .= '<div class="settings-block">';
157         $s .= '<h3>'. t('Twitter Posting Settings') .'</h3>';
158
159         if ( (!$ckey) && (!$csecret) ) {
160                 /***
161                  * no global consumer keys
162                  * display warning and skip personal config
163                  */
164                 $s .= '<p>'. t('No consumer key pair for Twitter found. Please contact your site administrator.') .'</p>';
165         } else {
166                 /***
167                  * ok we have a consumer key pair now look into the OAuth stuff
168                  */
169                 if ( (!$otoken) && (!$osecret) ) {
170                         /***
171                          * the user has not yet connected the account to twitter...
172                          * get a temporary OAuth key/secret pair and display a button with
173                          * which the user can request a PIN to connect the account to a
174                          * account at Twitter.
175                          */
176                         require_once('library/twitteroauth.php');
177                         $connection = new TwitterOAuth($ckey, $csecret);
178                         $request_token = $connection->getRequestToken();
179                         $token = $request_token['oauth_token'];
180                         /***
181                          *  make some nice form
182                          */
183                         $s .= '<p>'. t('At this Friendica instance the Twitter plugin was enabled but you have not yet connected your account to your Twitter account. To do so click the button below to get a PIN from Twitter which you have to copy into the input box below and submit the form. Only your <strong>public</strong> posts will be posted to Twitter.') .'</p>';
184                         $s .= '<a href="'.$connection->getAuthorizeURL($token).'" target="_twitter"><img src="addon/twitter/lighter.png" alt="'.t('Log in with Twitter').'"></a>';
185                         $s .= '<div id="twitter-pin-wrapper">';
186                         $s .= '<label id="twitter-pin-label" for="twitter-pin">'. t('Copy the PIN from Twitter here') .'</label>';
187                         $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
188                         $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="'.$token.'" />';
189                         $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="'.$request_token['oauth_token_secret'].'" />';
190             $s .= '</div><div class="clear"></div>';
191             $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
192                 } else {
193                         /***
194                          *  we have an OAuth key / secret pair for the user
195                          *  so let's give a chance to disable the postings to Twitter
196                          */
197                         require_once('library/twitteroauth.php');
198                         $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
199                         $details = $connection->get('account/verify_credentials');
200                         $s .= '<div id="twitter-info" ><img id="twitter-avatar" src="'.$details->profile_image_url.'" /><p id="twitter-info-block">'. t('Currently connected to: ') .'<a href="https://twitter.com/'.$details->screen_name.'" target="_twitter">'.$details->screen_name.'</a><br /><em>'.$details->description.'</em></p></div>';
201                         $s .= '<p>'. t('If enabled all your <strong>public</strong> postings can be posted to the associated Twitter account. You can choose to do so by default (here) or for every posting separately in the posting options when writing the entry.') .'</p>';
202                         if ($a->user['hidewall']) {
203                             $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 Twitter will lead the visitor to a blank page informing the visitor that the access to your profile has been restricted.') .'</p>';
204                         }
205                         $s .= '<div id="twitter-enable-wrapper">';
206                         $s .= '<label id="twitter-enable-label" for="twitter-checkbox">'. t('Allow posting to Twitter'). '</label>';
207                         $s .= '<input id="twitter-checkbox" type="checkbox" name="twitter-enable" value="1" ' . $checked . '/>';
208                         $s .= '<div class="clear"></div>';
209                         $s .= '<label id="twitter-default-label" for="twitter-default">'. t('Send public postings to Twitter by default') .'</label>';
210                         $s .= '<input id="twitter-default" type="checkbox" name="twitter-default" value="1" ' . $defchecked . '/>';
211                         $s .= '<div class="clear"></div>';
212
213                         $s .= '<label id="twitter-mirror-label" for="twitter-mirror">'.t('Mirror all posts from twitter that are no replies or retweets').'</label>';
214                         $s .= '<input id="twitter-mirror" type="checkbox" name="twitter-mirror" value="1" '. $mirrorchecked . '/>';
215                         $s .= '<div class="clear"></div>';
216
217                         $s .= '<label id="twitter-shortening-label" for="twitter-shortening">'.t('Shortening method that optimizes the tweet').'</label>';
218                         $s .= '<input id="twitter-shortening" type="checkbox" name="twitter-shortening" value="1" '. $shorteningchecked . '/>';
219                         $s .= '<div class="clear"></div>';
220
221                         $s .= '<label id="twitter-sendtaglinks-label" for="twitter-sendtaglinks">'.t('Send linked #-tags and @-names to Twitter').'</label>';
222                         $s .= '<input id="twitter-sendtaglinks" type="checkbox" name="twitter-sendtaglinks" value="1" '. $linkschecked . '/>';
223                         $s .= '</div><div class="clear"></div>';
224
225                         $s .= '<div id="twitter-disconnect-wrapper">';
226                         $s .= '<label id="twitter-disconnect-label" for="twitter-disconnect">'. t('Clear OAuth configuration') .'</label>';
227                         $s .= '<input id="twitter-disconnect" type="checkbox" name="twitter-disconnect" value="1" />';
228                         $s .= '</div><div class="clear"></div>';
229                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
230                 }
231         }
232         $s .= '</div><div class="clear"></div>';
233 }
234
235
236 function twitter_post_local(&$a,&$b) {
237
238         if($b['edit'])
239                 return;
240
241         if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (! $b['parent']) ) {
242
243                 $twitter_post = intval(get_pconfig(local_user(),'twitter','post'));
244                 $twitter_enable = (($twitter_post && x($_REQUEST,'twitter_enable')) ? intval($_REQUEST['twitter_enable']) : 0);
245
246                 // if API is used, default to the chosen settings
247                 if($_REQUEST['api_source'] && intval(get_pconfig(local_user(),'twitter','post_by_default')))
248                         $twitter_enable = 1;
249
250         if(! $twitter_enable)
251             return;
252
253         if(strlen($b['postopts']))
254             $b['postopts'] .= ',';
255         $b['postopts'] .= 'twitter';
256         }
257 }
258
259 if (! function_exists('short_link')) {
260 function short_link ($url) {
261     require_once('library/slinky.php');
262     $slinky = new Slinky( $url );
263     $yourls_url = get_config('yourls','url1');
264     if ($yourls_url) {
265             $yourls_username = get_config('yourls','username1');
266             $yourls_password = get_config('yourls', 'password1');
267             $yourls_ssl = get_config('yourls', 'ssl1');
268             $yourls = new Slinky_YourLS();
269             $yourls->set( 'username', $yourls_username );
270             $yourls->set( 'password', $yourls_password );
271             $yourls->set( 'ssl', $yourls_ssl );
272             $yourls->set( 'yourls-url', $yourls_url );
273             $slinky->set_cascade( array( $yourls, new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
274     }
275     else {
276             // setup a cascade of shortening services
277             // try to get a short link from these services
278             // in the order ur1.ca, trim, id.gd, tinyurl
279             $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
280     }
281     return $slinky->short();
282 } };
283
284 function twitter_shortenmsg($b) {
285         require_once("include/bbcode.php");
286         require_once("include/html2plain.php");
287
288         $max_char = 140;
289
290         // Looking for the first image
291         $image = '';
292         if(preg_match("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/is",$b['body'],$matches))
293                 $image = $matches[3];
294
295         if ($image == '')
296                 if(preg_match("/\[img\](.*?)\[\/img\]/is",$b['body'],$matches))
297                         $image = $matches[1];
298
299         $multipleimages = (strpos($b['body'], "[img") != strrpos($b['body'], "[img"));
300
301         // When saved into the database the content is sent through htmlspecialchars
302         // That means that we have to decode all image-urls
303         $image = htmlspecialchars_decode($image);
304
305         $body = $b["body"];
306         if ($b["title"] != "")
307                 $body = $b["title"]."\n\n".$body;
308
309         if (strpos($body, "[bookmark") !== false) {
310                 // splitting the text in two parts:
311                 // before and after the bookmark
312                 $pos = strpos($body, "[bookmark");
313                 $body1 = substr($body, 0, $pos);
314                 $body2 = substr($body, $pos);
315
316                 // Removing all quotes after the bookmark
317                 // they are mostly only the content after the bookmark.
318                 $body2 = preg_replace("/\[quote\=([^\]]*)\](.*?)\[\/quote\]/ism",'',$body2);
319                 $body2 = preg_replace("/\[quote\](.*?)\[\/quote\]/ism",'',$body2);
320                 $body = $body1.$body2;
321         }
322
323         // Add some newlines so that the message could be cut better
324         $body = str_replace(array("[quote", "[bookmark", "[/bookmark]", "[/quote]"),
325                         array("\n[quote", "\n[bookmark", "[/bookmark]\n", "[/quote]\n"), $body);
326
327         // remove the recycle signs and the names since they aren't helpful on twitter
328         // recycle 1
329         $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
330         $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
331         // recycle 2 (Test)
332         $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
333         $body = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', "\n", $body);
334
335         // remove the share element
336         $body = preg_replace("/\[share(.*?)\](.*?)\[\/share\]/ism","\n\n$2\n\n",$body);
337
338         // At first convert the text to html
339         $html = bbcode($body, false, false);
340
341         // Then convert it to plain text
342         //$msg = trim($b['title']." \n\n".html2plain($html, 0, true));
343         $msg = trim(html2plain($html, 0, true));
344         $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
345
346         // Removing multiple newlines
347         while (strpos($msg, "\n\n\n") !== false)
348                 $msg = str_replace("\n\n\n", "\n\n", $msg);
349
350         // Removing multiple spaces
351         while (strpos($msg, "  ") !== false)
352                 $msg = str_replace("  ", " ", $msg);
353
354         $origmsg = $msg;
355
356         // Removing URLs
357         $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
358
359         $msg = trim($msg);
360
361         $link = '';
362         // look for bookmark-bbcode and handle it with priority
363         if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
364                 $link = $matches[1];
365
366         $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
367
368         // If there is no bookmark element then take the first link
369         if ($link == '') {
370                 $links = collecturls($html);
371                 if (sizeof($links) > 0) {
372                         reset($links);
373                         $link = current($links);
374                 }
375                 $multiplelinks = (sizeof($links) > 1);
376         }
377
378         $msglink = "";
379         if ($multiplelinks)
380                 $msglink = $b["plink"];
381         else if ($link != "")
382                 $msglink = $link;
383         else if ($multipleimages)
384                 $msglink = $b["plink"];
385         else if ($image != "")
386                 $msglink = $image;
387
388         if (($msglink == "") and strlen($msg) > $max_char)
389                 $msglink = $b["plink"];
390
391         // If the message is short enough then don't modify it. (if the link exists in the original message)
392         if ((strlen(trim($origmsg)) <= $max_char) AND (strpos($origmsg, $msglink) OR ($msglink == "")))
393                 return(trim($origmsg));
394
395         if (strlen($msglink) > 20)
396                 $msglink = short_link($msglink);
397
398         if (strlen(trim($msg." ".$msglink)) > $max_char) {
399                 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
400                 $lastchar = substr($msg, -1);
401                 $msg = substr($msg, 0, -1);
402                 $pos = strrpos($msg, "\n");
403                 if ($pos > 0)
404                         $msg = substr($msg, 0, $pos);
405                 else if ($lastchar != "\n")
406                         $msg = substr($msg, 0, -3)."...";
407         }
408         $msg = str_replace("\n", " ", $msg);
409
410         // Removing multiple spaces - again
411         while (strpos($msg, "  ") !== false)
412                 $msg = str_replace("  ", " ", $msg);
413
414         return(trim($msg." ".$msglink));
415 }
416
417 function twitter_post_hook(&$a,&$b) {
418
419         /**
420          * Post to Twitter
421          */
422
423         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
424         return;
425
426         if(! strstr($b['postopts'],'twitter'))
427                 return;
428
429         if($b['parent'] != $b['id'])
430                 return;
431
432         // if post comes from twitter don't send it back
433         if($b['app'] == "Twitter")
434                 return;
435
436         logger('twitter post invoked');
437
438
439         load_pconfig($b['uid'], 'twitter');
440
441         $ckey    = get_config('twitter', 'consumerkey');
442         $csecret = get_config('twitter', 'consumersecret');
443         $otoken  = get_pconfig($b['uid'], 'twitter', 'oauthtoken');
444         $osecret = get_pconfig($b['uid'], 'twitter', 'oauthsecret');
445         $intelligent_shortening = get_pconfig($b['uid'], 'twitter', 'intelligent_shortening');
446
447         // Global setting overrides this
448         if (get_config('twitter','intelligent_shortening'))
449                 $intelligent_shortening = get_config('twitter','intelligent_shortening');
450
451         if($ckey && $csecret && $otoken && $osecret) {
452                 logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
453
454                 require_once('library/twitteroauth.php');
455                 require_once('include/bbcode.php');
456                 $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
457                 // in theory max char is 140 but T. uses t.co to make links 
458                 // longer so we give them 10 characters extra
459                 if (!$intelligent_shortening) {
460                         $max_char = 130; // max. length for a tweet
461                         // we will only work with up to two times the length of the dent 
462                         // we can later send to Twitter. This way we can "gain" some 
463                         // information during shortening of potential links but do not 
464                         // shorten all the links in a 200000 character long essay.
465                         if (! $b['title']=='') {
466                             $tmp = $b['title'] . ' : '. $b['body'];
467         //                    $tmp = substr($tmp, 0, 4*$max_char);
468                         } else {
469                             $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
470                         }
471                         // if [url=bla][img]blub.png[/img][/url] get blub.png
472                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
473                         // preserve links to images, videos and audios
474                         $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
475                         $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
476                         $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
477                         $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
478                         $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
479                         $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
480                         $linksenabled = get_pconfig($b['uid'],'twitter','post_taglinks');
481                         // if a #tag is linked, don't send the [url] over to SN
482                         // that is, don't send if the option is not set in the
483                         // connector settings
484                         if ($linksenabled=='0') {
485                                 // #-tags
486                                 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
487                                 // @-mentions
488                                 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
489                                 // recycle 1
490                                 $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
491                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
492                                 // recycle 2 (Test)
493                                 $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
494                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
495                         }
496                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
497                         $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
498                         // find all http or https links in the body of the entry and
499                         // apply the shortener if the link is longer then 20 characters
500                         if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
501                             preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls  );
502                             foreach ($allurls as $url) {
503                                 foreach ($url as $u) {
504                                     if (strlen($u)>20) {
505                                         $sl = short_link($u);
506                                         $tmp = str_replace( $u, $sl, $tmp );
507                                     }
508                                 }
509                             }
510                         }
511                         // ok, all the links we want to send out are save, now strip 
512                         // away the remaining bbcode
513                         //$msg = strip_tags(bbcode($tmp, false, false));
514                         $msg = bbcode($tmp, false, false);
515                         $msg = str_replace(array('<br>','<br />'),"\n",$msg);
516                         $msg = strip_tags($msg);
517
518                         // quotes not working - let's try this
519                         $msg = html_entity_decode($msg);
520                         if (( strlen($msg) > $max_char) && $max_char > 0) {
521                                 $shortlink = short_link( $b['plink'] );
522                                 // the new message will be shortened such that "... $shortlink"
523                                 // will fit into the character limit
524                                 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
525                                 $msg = str_replace(array('<br>','<br />'),' ',$msg);
526                                 $e = explode(' ', $msg);
527                                 //  remove the last word from the cut down message to 
528                                 //  avoid sending cut words to the MicroBlog
529                                 array_pop($e);
530                                 $msg = implode(' ', $e);
531                                 $msg .= '... ' . $shortlink;
532                         }
533
534                         $msg = trim($msg);
535                 } else
536                         $msg = twitter_shortenmsg($b);
537
538                 // and now tweet it :-)
539                 if(strlen($msg)) {
540                         $result = $tweet->post('statuses/update', array('status' => $msg));
541                         logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG);
542                         if ($result->error) {
543                                 logger('Send to Twitter failed: "' . $result->error . '"');
544                         }
545                 }
546         }
547 }
548
549 function twitter_plugin_admin_post(&$a){
550         $consumerkey    =       ((x($_POST,'consumerkey'))              ? notags(trim($_POST['consumerkey']))   : '');
551         $consumersecret =       ((x($_POST,'consumersecret'))   ? notags(trim($_POST['consumersecret'])): '');
552         $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'])):'');
553         set_config('twitter','consumerkey',$consumerkey);
554         set_config('twitter','consumersecret',$consumersecret);
555         set_config('twitter','application_name',$applicationname);
556         info( t('Settings updated.'). EOL );
557 }
558 function twitter_plugin_admin(&$a, &$o){
559         $t = get_markup_template( "admin.tpl", "addon/twitter/" );
560
561         $o = replace_macros($t, array(
562                 '$submit' => t('Submit'),
563                                                                 // name, label, value, help, [extra values]
564                 '$consumerkey' => array('consumerkey', t('Consumer key'),  get_config('twitter', 'consumerkey' ), ''),
565                 '$consumersecret' => array('consumersecret', t('Consumer secret'),  get_config('twitter', 'consumersecret' ), ''),
566                 '$applicationname' => array('applicationname', t('Name of the Twitter Application'), get_config('twitter','application_name'),t('set this to avoid mirroring postings from ~friendica back to ~friendica'))
567         ));
568 }
569
570 function twitter_cron($a,$b) {
571         $last = get_config('twitter','last_poll');
572
573         $poll_interval = intval(get_config('twitter','poll_interval'));
574         if(! $poll_interval)
575                 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
576
577         if($last) {
578                 $next = $last + ($poll_interval * 60);
579                 if($next > time()) {
580                         logger('twitter: poll intervall not reached');
581                         return;
582                 }
583         }
584         logger('twitter: cron_start');
585
586         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
587         if(count($r)) {
588                 foreach($r as $rr) {
589                         logger('twitter: fetching for user '.$rr['uid']);
590                         twitter_fetchtimeline($a, $rr['uid']);
591                 }
592         }
593
594         logger('twitter: cron_end');
595
596         set_config('twitter','last_poll', time());
597 }
598
599 function twitter_fetchtimeline($a, $uid) {
600         $ckey    = get_config('twitter', 'consumerkey');
601         $csecret = get_config('twitter', 'consumersecret');
602         $otoken  = get_pconfig($uid, 'twitter', 'oauthtoken');
603         $osecret = get_pconfig($uid, 'twitter', 'oauthsecret');
604         $lastid  = get_pconfig($uid, 'twitter', 'lastid');
605
606         $application_name  = get_config('twitter', 'application_name');
607
608         if ($application_name == "")
609                 $application_name = $a->get_hostname();
610
611         require_once('library/twitteroauth.php');
612         $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
613
614         $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
615
616         $first_time = ($lastid == "");
617
618         if ($lastid <> "")
619                 $parameters["since_id"] = $lastid;
620
621         $items = $connection->get('statuses/user_timeline', $parameters);
622
623         if (!is_array($items))
624                 return;
625
626         $posts = array_reverse($items);
627
628         if (count($posts)) {
629             foreach ($posts as $post) {
630                 if ($post->id_str > $lastid)
631                         $lastid = $post->id_str;
632
633                 if ($first_time)
634                         continue;
635
636                 if (!strpos($post->source, $application_name)) {
637                         $_SESSION["authenticated"] = true;
638                         $_SESSION["uid"] = $uid;
639
640                         $_REQUEST["type"] = "wall";
641                         $_REQUEST["api_source"] = true;
642                         $_REQUEST["profile_uid"] = $uid;
643                         $_REQUEST["source"] = "Twitter";
644
645                         //$_REQUEST["date"] = $post->created_at;
646
647                         $_REQUEST["body"] = $post->text;
648                         if (is_string($post->place->name))
649                                 $_REQUEST["location"] = $post->place->name;
650
651                         if (is_string($post->place->full_name))
652                                 $_REQUEST["location"] = $post->place->full_name;
653
654                         if (is_array($post->geo->coordinates))
655                                 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
656
657                         if (is_array($post->coordinates->coordinates))
658                                 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
659
660                         //print_r($_REQUEST);
661                         logger('twitter: posting for user '.$uid);
662
663                         require_once('mod/item.php');
664                         item_post($a);
665
666                 }
667             }
668         }
669         set_pconfig($uid, 'twitter', 'lastid', $lastid);
670 }