]> git.mxchange.org Git - friendica-addons.git/blob - twitter/twitter.php
Merge pull request #148 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 <https://f.diekershoff.de/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
63 define('TWITTER_DEFAULT_POLL_INTERVAL', 5); // given in minutes
64
65 function twitter_install() {
66         //  we need some hooks, for the configuration and for sending tweets
67         register_hook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
68         register_hook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
69         register_hook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
70         register_hook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
71         register_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
72         register_hook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
73         register_hook('queue_predeliver', 'addon/twitter/twitter.php', 'twitter_queue_hook');
74         logger("installed twitter");
75 }
76
77
78 function twitter_uninstall() {
79         unregister_hook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
80         unregister_hook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
81         unregister_hook('post_local', 'addon/twitter/twitter.php', 'twitter_post_local');
82         unregister_hook('notifier_normal', 'addon/twitter/twitter.php', 'twitter_post_hook');
83         unregister_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
84         unregister_hook('cron', 'addon/twitter/twitter.php', 'twitter_cron');
85         unregister_hook('queue_predeliver', 'addon/twitter/twitter.php', 'twitter_queue_hook');
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, $shortlink = false) {
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, 2);
366
367         // Then convert it to plain text
368         $msg = trim(html2plain($html, 0, true));
369         $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
370
371         // Removing multiple newlines
372         while (strpos($msg, "\n\n\n") !== false)
373                 $msg = str_replace("\n\n\n", "\n\n", $msg);
374
375         // Removing multiple spaces
376         while (strpos($msg, "  ") !== false)
377                 $msg = str_replace("  ", " ", $msg);
378
379         $origmsg = trim($msg);
380
381         // Removing URLs
382         $msg = preg_replace('/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', "", $msg);
383
384         $msg = trim($msg);
385
386         $link = '';
387         // look for bookmark-bbcode and handle it with priority
388         if(preg_match("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/is",$b['body'],$matches))
389                 $link = $matches[1];
390
391         $multiplelinks = (strpos($b['body'], "[bookmark") != strrpos($b['body'], "[bookmark"));
392
393         // If there is no bookmark element then take the first link
394         if ($link == '') {
395                 $links = collecturls($html);
396
397                 foreach($links AS $singlelink) {
398                         $img_str = fetch_url($singlelink);
399
400                         $tempfile = tempnam(get_config("system","temppath"), "cache");
401                         file_put_contents($tempfile, $img_str);
402                         $mime = image_type_to_mime_type(exif_imagetype($tempfile));
403                         unlink($tempfile);
404
405                         if (substr($mime, 0, 6) == "image/") {
406                                 $image = $singlelink;
407                                 unset($links[$singlelink]);
408                         }
409                 }
410
411                 if (sizeof($links) > 0) {
412                         reset($links);
413                         $link = current($links);
414                 }
415                 $multiplelinks = (sizeof($links) > 1);
416         }
417
418         $msglink = "";
419         if ($multiplelinks)
420                 $msglink = $b["plink"];
421         else if ($link != "")
422                 $msglink = $link;
423         else if ($multipleimages)
424                 $msglink = $b["plink"];
425         else if ($image != "")
426                 $msglink = $image;
427
428         if (($msglink == "") and strlen($msg) > $max_char)
429                 $msglink = $b["plink"];
430
431         // If the message is short enough then don't modify it.
432         if ((strlen($origmsg) <= $max_char) AND ($msglink == ""))
433                 return(array("msg"=>$origmsg, "image"=>""));
434
435         // If the message is short enough and contains a picture then post the picture as well
436         if ((strlen($origmsg) <= ($max_char - 23)) AND strpos($origmsg, $msglink))
437                 return(array("msg"=>$origmsg, "image"=>$image));
438
439         // If the message is short enough and the link exists in the original message don't modify it as well
440         // -3 because of the bad shortener of twitter
441         if ((strlen($origmsg) <= ($max_char - 3)) AND strpos($origmsg, $msglink))
442                 return(array("msg"=>$origmsg, "image"=>""));
443
444         // Preserve the unshortened link
445         $orig_link = $msglink;
446
447         // Just replace the message link with a 22 character long string
448         // Twitter calculates with this length
449         if (trim($msglink) <> '')
450                 $msglink = "1234567890123456789012";
451
452         if (strlen(trim($msg." ".$msglink)) > ($max_char)) {
453                 $msg = substr($msg, 0, ($max_char) - (strlen($msglink)));
454                 $lastchar = substr($msg, -1);
455                 $msg = substr($msg, 0, -1);
456                 $pos = strrpos($msg, "\n");
457                 if ($pos > 0)
458                         $msg = substr($msg, 0, $pos);
459                 else if ($lastchar != "\n")
460                         $msg = substr($msg, 0, -3)."...";
461
462                 // if the post contains a picture and a link then the system tries to cut the post earlier.
463                 // So the link and the picture can be posted.
464                 if (($image != "") AND ($orig_link != $image)) {
465                         $msg2 = substr($msg, 0, ($max_char - 20) - (strlen($msglink)));
466                         $lastchar = substr($msg2, -1);
467                         $msg2 = substr($msg2, 0, -1);
468                         $pos = strrpos($msg2, "\n");
469                         if ($pos > 0)
470                                 $msg = substr($msg2, 0, $pos);
471                         else if ($lastchar == "\n")
472                                 $msg = trim($msg2);
473                 }
474
475         }
476         // Removing multiple spaces - again
477         while (strpos($msg, "  ") !== false)
478                 $msg = str_replace("  ", " ", $msg);
479
480         $msg = trim($msg);
481
482         // Removing multiple newlines
483         //while (strpos($msg, "\n\n") !== false)
484         //      $msg = str_replace("\n\n", "\n", $msg);
485
486         // Looking if the link points to an image
487         $img_str = fetch_url($orig_link);
488
489         $tempfile = tempnam(get_config("system","temppath"), "cache");
490         file_put_contents($tempfile, $img_str);
491         $mime = image_type_to_mime_type(exif_imagetype($tempfile));
492         unlink($tempfile);
493
494         if (($image == $orig_link) OR (substr($mime, 0, 6) == "image/"))
495                 return(array("msg"=>$msg, "image"=>$orig_link));
496         else if (($image != $orig_link) AND ($image != "") AND (strlen($msg." ".$msglink) <= ($max_char - 23))) {
497                 if ($shortlink)
498                         $orig_link = short_link($orig_link);
499
500                 return(array("msg"=>$msg." ".$orig_link, "image"=>$image));
501         } else {
502                 if ($shortlink)
503                         $orig_link = short_link($orig_link);
504
505                 return(array("msg"=>$msg." ".$orig_link, "image"=>""));
506         }
507 }
508
509 function twitter_post_hook(&$a,&$b) {
510
511         /**
512          * Post to Twitter
513          */
514
515         if($b['deleted'] || $b['private'] || ($b['created'] !== $b['edited']))
516         return;
517
518         if(! strstr($b['postopts'],'twitter'))
519                 return;
520
521         if($b['parent'] != $b['id'])
522                 return;
523
524         // if post comes from twitter don't send it back
525         if($b['app'] == "Twitter")
526                 return;
527
528         logger('twitter post invoked');
529
530
531         load_pconfig($b['uid'], 'twitter');
532
533         $ckey    = get_config('twitter', 'consumerkey');
534         $csecret = get_config('twitter', 'consumersecret');
535         $otoken  = get_pconfig($b['uid'], 'twitter', 'oauthtoken');
536         $osecret = get_pconfig($b['uid'], 'twitter', 'oauthsecret');
537         $intelligent_shortening = get_pconfig($b['uid'], 'twitter', 'intelligent_shortening');
538
539         // Global setting overrides this
540         if (get_config('twitter','intelligent_shortening'))
541                 $intelligent_shortening = get_config('twitter','intelligent_shortening');
542
543         if($ckey && $csecret && $otoken && $osecret) {
544                 logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
545
546                 require_once('library/twitteroauth.php');
547                 require_once('include/bbcode.php');
548                 $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
549                 // in theory max char is 140 but T. uses t.co to make links 
550                 // longer so we give them 10 characters extra
551                 if (!$intelligent_shortening) {
552                         $max_char = 130; // max. length for a tweet
553                         // we will only work with up to two times the length of the dent 
554                         // we can later send to Twitter. This way we can "gain" some 
555                         // information during shortening of potential links but do not 
556                         // shorten all the links in a 200000 character long essay.
557                         if (! $b['title']=='') {
558                             $tmp = $b['title'] . ' : '. $b['body'];
559         //                    $tmp = substr($tmp, 0, 4*$max_char);
560                         } else {
561                             $tmp = $b['body']; // substr($b['body'], 0, 3*$max_char);
562                         }
563                         // if [url=bla][img]blub.png[/img][/url] get blub.png
564                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\]\[img\](\\w+.*?)\\[\\/img\]\\[\\/url\]/i', '$2', $tmp);
565                         // preserve links to images, videos and audios
566                         $tmp = preg_replace( '/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism', '$3', $tmp);
567                         $tmp = preg_replace( '/\[\\/?img(\\s+.*?\]|\])/i', '', $tmp);
568                         $tmp = preg_replace( '/\[\\/?video(\\s+.*?\]|\])/i', '', $tmp);
569                         $tmp = preg_replace( '/\[\\/?youtube(\\s+.*?\]|\])/i', '', $tmp);
570                         $tmp = preg_replace( '/\[\\/?vimeo(\\s+.*?\]|\])/i', '', $tmp);
571                         $tmp = preg_replace( '/\[\\/?audio(\\s+.*?\]|\])/i', '', $tmp);
572                         $linksenabled = get_pconfig($b['uid'],'twitter','post_taglinks');
573                         // if a #tag is linked, don't send the [url] over to SN
574                         // that is, don't send if the option is not set in the
575                         // connector settings
576                         if ($linksenabled=='0') {
577                                 // #-tags
578                                 $tmp = preg_replace( '/#\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '#$2', $tmp);
579                                 // @-mentions
580                                 $tmp = preg_replace( '/@\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', '@$2', $tmp);
581                                 // recycle 1
582                                 $recycle = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8');
583                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
584                                 // recycle 2 (Test)
585                                 $recycle = html_entity_decode("&#x25CC; ", ENT_QUOTES, 'UTF-8');
586                                 $tmp = preg_replace( '/'.$recycle.'\[url\=(\w+.*?)\](\w+.*?)\[\/url\]/i', $recycle.'$2', $tmp);
587                         }
588                         $tmp = preg_replace( '/\[url\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/url\]/i', '$2 $1', $tmp);
589                         $tmp = preg_replace( '/\[bookmark\=(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)\](\w+.*?)\[\/bookmark\]/i', '$2 $1', $tmp);
590                         // find all http or https links in the body of the entry and
591                         // apply the shortener if the link is longer then 20 characters
592                         if (( strlen($tmp)>$max_char ) && ( $max_char > 0 )) {
593                             preg_match_all ( '/(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/i', $tmp, $allurls  );
594                             foreach ($allurls as $url) {
595                                 foreach ($url as $u) {
596                                     if (strlen($u)>20) {
597                                         $sl = short_link($u);
598                                         $tmp = str_replace( $u, $sl, $tmp );
599                                     }
600                                 }
601                             }
602                         }
603                         // ok, all the links we want to send out are save, now strip 
604                         // away the remaining bbcode
605                         //$msg = strip_tags(bbcode($tmp, false, false));
606                         $msg = bbcode($tmp, false, false, true);
607                         $msg = str_replace(array('<br>','<br />'),"\n",$msg);
608                         $msg = strip_tags($msg);
609
610                         // quotes not working - let's try this
611                         $msg = html_entity_decode($msg);
612                         if (( strlen($msg) > $max_char) && $max_char > 0) {
613                                 $shortlink = short_link( $b['plink'] );
614                                 // the new message will be shortened such that "... $shortlink"
615                                 // will fit into the character limit
616                                 $msg = nl2br(substr($msg, 0, $max_char-strlen($shortlink)-4));
617                                 $msg = str_replace(array('<br>','<br />'),' ',$msg);
618                                 $e = explode(' ', $msg);
619                                 //  remove the last word from the cut down message to 
620                                 //  avoid sending cut words to the MicroBlog
621                                 array_pop($e);
622                                 $msg = implode(' ', $e);
623                                 $msg .= '... ' . $shortlink;
624                         }
625
626                         $msg = trim($msg);
627                         $image = "";
628                 } else {
629                         $msgarr = twitter_shortenmsg($b);
630                         $msg = $msgarr["msg"];
631                         $image = $msgarr["image"];
632                 }
633                 // and now tweet it :-)
634                 if(strlen($msg) and ($image != "")) {
635                         $img_str = fetch_url($image);
636
637                         $tempfile = tempnam(get_config("system","temppath"), "cache");
638                         file_put_contents($tempfile, $img_str);
639
640                         // Twitter had changed something so that the old library doesn't work anymore
641                         // so we are using a new library for twitter
642                         // To-Do:
643                         // Switching completely to this library with all functions
644                         require_once("addon/twitter/codebird.php");
645
646                         $cb = \Codebird\Codebird::getInstance();
647                         $cb->setConsumerKey($ckey, $csecret);
648                         $cb->setToken($otoken, $osecret);
649                         $result = $cb->statuses_updateWithMedia(array('status' => $msg, 'media[]' => $tempfile));
650                         unlink($tempfile);
651
652                         /*
653                         // Old Code
654                         $mime = image_type_to_mime_type(exif_imagetype($tempfile));
655                         unlink($tempfile);
656
657                         $filename = "upload";
658
659                         $result = $tweet->post('statuses/update_with_media', array('media[]' => "{$img_str};type=".$mime.";filename={$filename}" , 'status' => $msg));
660                         */
661
662                         logger('twitter_post_with_media send, result: ' . print_r($result, true), LOGGER_DEBUG);
663                         if ($result->errors OR $result->error) {
664                                 logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
665
666                                 // Workaround: Remove the picture link so that the post can be reposted without it
667                                 $msg .= " ".$image;
668                                 $image = "";
669                         }
670                 }
671
672                 if(strlen($msg) and ($image == "")) {
673                         $url = 'statuses/update';
674                         $post = array('status' => $msg);
675                         $result = $tweet->post($url, $post);
676                         logger('twitter_post send, result: ' . print_r($result, true), LOGGER_DEBUG);
677                         if ($result->errors) {
678                                 logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
679
680                                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", $b['uid']);
681                                 if (count($r))
682                                         $a->contact = $r[0]["id"];
683
684                                 $s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $post));
685                                 require_once('include/queue_fn.php');
686                                 add_to_queue($a->contact,NETWORK_TWITTER,$s);
687                                 notice(t('Twitter post failed. Queued for retry.').EOL);
688                         }
689                 }
690         }
691 }
692
693 function twitter_plugin_admin_post(&$a){
694         $consumerkey    =       ((x($_POST,'consumerkey'))              ? notags(trim($_POST['consumerkey']))   : '');
695         $consumersecret =       ((x($_POST,'consumersecret'))   ? notags(trim($_POST['consumersecret'])): '');
696         $applicationname = ((x($_POST, 'applicationname')) ? notags(trim($_POST['applicationname'])):'');
697         set_config('twitter','consumerkey',$consumerkey);
698         set_config('twitter','consumersecret',$consumersecret);
699         set_config('twitter','application_name',$applicationname);
700         info( t('Settings updated.'). EOL );
701 }
702 function twitter_plugin_admin(&$a, &$o){
703         $t = get_markup_template( "admin.tpl", "addon/twitter/" );
704
705         $o = replace_macros($t, array(
706                 '$submit' => t('Submit'),
707                                                                 // name, label, value, help, [extra values]
708                 '$consumerkey' => array('consumerkey', t('Consumer key'),  get_config('twitter', 'consumerkey' ), ''),
709                 '$consumersecret' => array('consumersecret', t('Consumer secret'),  get_config('twitter', 'consumersecret' ), ''),
710                 '$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'))
711         ));
712 }
713
714 function twitter_cron($a,$b) {
715         $last = get_config('twitter','last_poll');
716
717         $poll_interval = intval(get_config('twitter','poll_interval'));
718         if(! $poll_interval)
719                 $poll_interval = TWITTER_DEFAULT_POLL_INTERVAL;
720
721         if($last) {
722                 $next = $last + ($poll_interval * 60);
723                 if($next > time()) {
724                         logger('twitter: poll intervall not reached');
725                         return;
726                 }
727         }
728         logger('twitter: cron_start');
729
730         $r = q("SELECT * FROM `pconfig` WHERE `cat` = 'twitter' AND `k` = 'mirror_posts' AND `v` = '1' ORDER BY RAND() ");
731         if(count($r)) {
732                 foreach($r as $rr) {
733                         logger('twitter: fetching for user '.$rr['uid']);
734                         twitter_fetchtimeline($a, $rr['uid']);
735                 }
736         }
737
738         logger('twitter: cron_end');
739
740         set_config('twitter','last_poll', time());
741 }
742
743 function twitter_fetchtimeline($a, $uid) {
744         $ckey    = get_config('twitter', 'consumerkey');
745         $csecret = get_config('twitter', 'consumersecret');
746         $otoken  = get_pconfig($uid, 'twitter', 'oauthtoken');
747         $osecret = get_pconfig($uid, 'twitter', 'oauthsecret');
748         $lastid  = get_pconfig($uid, 'twitter', 'lastid');
749
750         $application_name  = get_config('twitter', 'application_name');
751
752         if ($application_name == "")
753                 $application_name = $a->get_hostname();
754
755         require_once('library/twitteroauth.php');
756         $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
757
758         $parameters = array("exclude_replies" => true, "trim_user" => true, "contributor_details" => false, "include_rts" => false);
759
760         $first_time = ($lastid == "");
761
762         if ($lastid <> "")
763                 $parameters["since_id"] = $lastid;
764
765         $items = $connection->get('statuses/user_timeline', $parameters);
766
767         if (!is_array($items))
768                 return;
769
770         $posts = array_reverse($items);
771
772         if (count($posts)) {
773             foreach ($posts as $post) {
774                 if ($post->id_str > $lastid)
775                         $lastid = $post->id_str;
776
777                 if ($first_time)
778                         continue;
779
780                 if (!strpos($post->source, $application_name)) {
781                         $_SESSION["authenticated"] = true;
782                         $_SESSION["uid"] = $uid;
783
784                         unset($_REQUEST);
785                         $_REQUEST["type"] = "wall";
786                         $_REQUEST["api_source"] = true;
787                         $_REQUEST["profile_uid"] = $uid;
788                         $_REQUEST["source"] = "Twitter";
789
790                         //$_REQUEST["date"] = $post->created_at;
791
792                         $_REQUEST["title"] = "";
793
794                         $_REQUEST["body"] = $post->text;
795                         if (is_string($post->place->name))
796                                 $_REQUEST["location"] = $post->place->name;
797
798                         if (is_string($post->place->full_name))
799                                 $_REQUEST["location"] = $post->place->full_name;
800
801                         if (is_array($post->geo->coordinates))
802                                 $_REQUEST["coord"] = $post->geo->coordinates[0]." ".$post->geo->coordinates[1];
803
804                         if (is_array($post->coordinates->coordinates))
805                                 $_REQUEST["coord"] = $post->coordinates->coordinates[1]." ".$post->coordinates->coordinates[0];
806
807                         //print_r($_REQUEST);
808                         logger('twitter: posting for user '.$uid);
809
810                         require_once('mod/item.php');
811                         item_post($a);
812
813                 }
814             }
815         }
816         set_pconfig($uid, 'twitter', 'lastid', $lastid);
817 }
818
819 function twitter_queue_hook(&$a,&$b) {
820
821         $qi = q("SELECT * FROM `queue` WHERE `network` = '%s'",
822                 dbesc(NETWORK_TWITTER)
823                 );
824         if(! count($qi))
825                 return;
826
827         require_once('include/queue_fn.php');
828
829         foreach($qi as $x) {
830                 if($x['network'] !== NETWORK_TWITTER)
831                         continue;
832
833                 logger('twitter_queue: run');
834
835                 $r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid` 
836                         WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
837                         intval($x['cid'])
838                 );
839                 if(! count($r))
840                         continue;
841
842                 $user = $r[0];
843
844                 $ckey    = get_config('twitter', 'consumerkey');
845                 $csecret = get_config('twitter', 'consumersecret');
846                 $otoken  = get_pconfig($user['uid'], 'twitter', 'oauthtoken');
847                 $osecret = get_pconfig($user['uid'], 'twitter', 'oauthsecret');
848
849                 $success = false;
850
851                 if ($ckey AND $csecret AND $otoken AND $osecret) {
852
853                         logger('twitter_queue: able to post');
854
855                         $z = unserialize($x['content']);
856
857                         require_once("addon/twitter/codebird.php");
858
859                         $cb = \Codebird\Codebird::getInstance();
860                         $cb->setConsumerKey($ckey, $csecret);
861                         $cb->setToken($otoken, $osecret);
862
863                         if ($z['url'] == "statuses/update")
864                                 $result = $cb->statuses_update($z['post']);
865
866                         logger('twitter_queue: post result: ' . print_r($result, true), LOGGER_DEBUG);
867
868                         if ($result->errors)
869                                 logger('twitter_queue: Send to Twitter failed: "' . print_r($result->errors, true) . '"');
870                         else {
871                                 $success = true;
872                                 remove_queue_item($x['id']);
873                         }
874                 } else
875                         logger("twitter_queue: Error getting tokens for user ".$user['uid']);
876
877                 if (!$success) {
878                         logger('twitter_queue: delayed');
879                         update_queue_time($x['id']);
880                 }
881         }
882 }