]> git.mxchange.org Git - friendica-addons.git/blob - twitter/twitter.php
clarification
[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 = 130;
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. (if the link exists in the original message)
418         if ((strlen(trim($origmsg)) <= $max_char) AND (strpos($origmsg, $msglink) OR ($msglink == "")))
419                 return(trim($origmsg));
420
421         if (strlen($msglink) > 20)
422                 $msglink = short_link($msglink);
423
424         if (strlen(trim($msg." ".$msglink)) > $max_char) {
425                 $msg = substr($msg, 0, $max_char - (strlen($msglink)));
426                 $lastchar = substr($msg, -1);
427                 $msg = substr($msg, 0, -1);
428                 $pos = strrpos($msg, "\n");
429                 if ($pos > 0)
430                         $msg = substr($msg, 0, $pos);
431                 else if ($lastchar != "\n")
432                         $msg = substr($msg, 0, -3)."...";
433         }
434         $msg = str_replace("\n", " ", $msg);
435
436         // Removing multiple spaces - again
437         while (strpos($msg, "  ") !== false)
438                 $msg = str_replace("  ", " ", $msg);
439
440         return(trim($msg." ".$msglink));
441 }
442
443 function twitter_post_hook(&$a,&$b) {
444
445         /**
446          * Post to Twitter
447          */
448
449         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
450         return;
451
452         if(! strstr($b['postopts'],'twitter'))
453                 return;
454
455         if($b['parent'] != $b['id'])
456                 return;
457
458         // if post comes from twitter don't send it back
459         if($b['app'] == "Twitter")
460                 return;
461
462         logger('twitter post invoked');
463
464
465         load_pconfig($b['uid'], 'twitter');
466
467         $ckey    = get_config('twitter', 'consumerkey');
468         $csecret = get_config('twitter', 'consumersecret');
469         $otoken  = get_pconfig($b['uid'], 'twitter', 'oauthtoken');
470         $osecret = get_pconfig($b['uid'], 'twitter', 'oauthsecret');
471         $intelligent_shortening = get_pconfig($b['uid'], 'twitter', 'intelligent_shortening');
472
473         // Global setting overrides this
474         if (get_config('twitter','intelligent_shortening'))
475                 $intelligent_shortening = get_config('twitter','intelligent_shortening');
476
477         if($ckey && $csecret && $otoken && $osecret) {
478                 logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
479
480                 require_once('library/twitteroauth.php');
481                 require_once('include/bbcode.php');
482                 $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
483                 // in theory max char is 140 but T. uses t.co to make links 
484                 // longer so we give them 10 characters extra
485                 if (!$intelligent_shortening) {
486                         $max_char = 130; // max. length for a tweet
487                         // we will only work with up to two times the length of the dent 
488                         // we can later send to Twitter. This way we can "gain" some 
489                         // information during shortening of potential links but do not 
490                         // shorten all the links in a 200000 character long essay.
491                         if (! $b['title']=='') {
492                             $tmp = $b['title'] . ' : '. $b['body'];
493         //                    $tmp = substr($tmp, 0, 4*$max_char);
494                         } else {
495                             $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
496                         }
497                         // if [url=bla][img]blub.png[/img][/url] get blub.png
498                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
499                         // preserve links to images, videos and audios
500                         $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
501                         $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
502                         $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
503                         $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
504                         $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
505                         $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
506                         $linksenabled = get_pconfig($b['uid'],'twitter','post_taglinks');
507                         // if a #tag is linked, don't send the [url] over to SN
508                         // that is, don't send if the option is not set in the
509                         // connector settings
510                         if ($linksenabled=='0') {
511                                 // #-tags
512                                 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
513                                 // @-mentions
514                                 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
515                                 // recycle 1
516                                 $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
517                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
518                                 // recycle 2 (Test)
519                                 $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
520                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
521                         }
522                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
523                         $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
524                         // find all http or https links in the body of the entry and
525                         // apply the shortener if the link is longer then 20 characters
526                         if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
527                             preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls  );
528                             foreach ($allurls as $url) {
529                                 foreach ($url as $u) {
530                                     if (strlen($u)>20) {
531                                         $sl = short_link($u);
532                                         $tmp = str_replace( $u, $sl, $tmp );
533                                     }
534                                 }
535                             }
536                         }
537                         // ok, all the links we want to send out are save, now strip 
538                         // away the remaining bbcode
539                         //$msg = strip_tags(bbcode($tmp, false, false));
540                         $msg = bbcode($tmp, false, false, true);
541                         $msg = str_replace(array('<br>','<br />'),"\n",$msg);
542                         $msg = strip_tags($msg);
543
544                         // quotes not working - let's try this
545                         $msg = html_entity_decode($msg);
546                         if (( strlen($msg) > $max_char) && $max_char > 0) {
547                                 $shortlink = short_link( $b['plink'] );
548                                 // the new message will be shortened such that "... $shortlink"
549                                 // will fit into the character limit
550                                 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
551                                 $msg = str_replace(array('<br>','<br />'),' ',$msg);
552                                 $e = explode(' ', $msg);
553                                 //  remove the last word from the cut down message to 
554                                 //  avoid sending cut words to the MicroBlog
555                                 array_pop($e);
556                                 $msg = implode(' ', $e);
557                                 $msg .= '... ' . $shortlink;
558                         }
559
560                         $msg = trim($msg);
561                 } else
562                         $msg = twitter_shortenmsg($b);
563
564                 // and now tweet it :-)
565                 if(strlen($msg)) {
566                         $result = $tweet->post('statuses/update', array('status' => $msg));
567                         logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG);
568                         if ($result->error) {
569                                 logger('Send to Twitter failed: "' . $result->error . '"');
570                         }
571                 }
572         }
573 }
574
575 function twitter_plugin_admin_post(&$a){
576         $consumerkey    =       ((x($_POST,'consumerkey'))              ? notags(trim($_POST['consumerkey']))   : '');
577         $consumersecret =       ((x($_POST,'consumersecret'))   ? notags(trim($_POST['consumersecret'])): '');
578         $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'])):'');
579         set_config('twitter','consumerkey',$consumerkey);
580         set_config('twitter','consumersecret',$consumersecret);
581         set_config('twitter','application_name',$applicationname);
582         info( t('Settings updated.'). EOL );
583 }
584 function twitter_plugin_admin(&$a, &$o){
585         $t = get_markup_template( "admin.tpl", "addon/twitter/" );
586
587         $o = replace_macros($t, array(
588                 '$submit' => t('Submit'),
589                                                                 // name, label, value, help, [extra values]
590                 '$consumerkey' => array('consumerkey', t('Consumer key'),  get_config('twitter', 'consumerkey' ), ''),
591                 '$consumersecret' => array('consumersecret', t('Consumer secret'),  get_config('twitter', 'consumersecret' ), ''),
592                 '$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'))
593         ));
594 }
595
596 function twitter_cron($a,$b) {
597         $last = get_config('twitter','last_poll');
598
599         $poll_interval = intval(get_config('twitter','poll_interval'));
600         if(! $poll_interval)
601                 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
602
603         if($last) {
604                 $next = $last + ($poll_interval * 60);
605                 if($next > time()) {
606                         logger('twitter: poll intervall not reached');
607                         return;
608                 }
609         }
610         logger('twitter: cron_start');
611
612         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
613         if(count($r)) {
614                 foreach($r as $rr) {
615                         logger('twitter: fetching for user '.$rr['uid']);
616                         twitter_fetchtimeline($a, $rr['uid']);
617                 }
618         }
619
620         logger('twitter: cron_end');
621
622         set_config('twitter','last_poll', time());
623 }
624
625 function twitter_fetchtimeline($a, $uid) {
626         $ckey    = get_config('twitter', 'consumerkey');
627         $csecret = get_config('twitter', 'consumersecret');
628         $otoken  = get_pconfig($uid, 'twitter', 'oauthtoken');
629         $osecret = get_pconfig($uid, 'twitter', 'oauthsecret');
630         $lastid  = get_pconfig($uid, 'twitter', 'lastid');
631
632         $application_name  = get_config('twitter', 'application_name');
633
634         if ($application_name == "")
635                 $application_name = $a->get_hostname();
636
637         require_once('library/twitteroauth.php');
638         $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
639
640         $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
641
642         $first_time = ($lastid == "");
643
644         if ($lastid <> "")
645                 $parameters["since_id"] = $lastid;
646
647         $items = $connection->get('statuses/user_timeline', $parameters);
648
649         if (!is_array($items))
650                 return;
651
652         $posts = array_reverse($items);
653
654         if (count($posts)) {
655             foreach ($posts as $post) {
656                 if ($post->id_str > $lastid)
657                         $lastid = $post->id_str;
658
659                 if ($first_time)
660                         continue;
661
662                 if (!strpos($post->source, $application_name)) {
663                         $_SESSION["authenticated"] = true;
664                         $_SESSION["uid"] = $uid;
665
666                         $_REQUEST["type"] = "wall";
667                         $_REQUEST["api_source"] = true;
668                         $_REQUEST["profile_uid"] = $uid;
669                         $_REQUEST["source"] = "Twitter";
670
671                         //$_REQUEST["date"] = $post->created_at;
672
673                         $_REQUEST["body"] = $post->text;
674                         if (is_string($post->place->name))
675                                 $_REQUEST["location"] = $post->place->name;
676
677                         if (is_string($post->place->full_name))
678                                 $_REQUEST["location"] = $post->place->full_name;
679
680                         if (is_array($post->geo->coordinates))
681                                 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
682
683                         if (is_array($post->coordinates->coordinates))
684                                 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
685
686                         //print_r($_REQUEST);
687                         logger('twitter: posting for user '.$uid);
688
689                         require_once('mod/item.php');
690                         item_post($a);
691
692                 }
693             }
694         }
695         set_pconfig($uid, 'twitter', 'lastid', $lastid);
696 }