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