]> git.mxchange.org Git - friendica-addons.git/blob - twitter/twitter.php
Move connectors addons settings under "connector settings" tab
[friendica-addons.git] / twitter / twitter.php
1 <?php
2 /**
3  * Name: Twitter Connector
4  * Version: 1.0.1
5  * Author: Tobias Diekershoff <https://diekershoff.homeunix.net/friendika/profile/tobias>
6  */
7
8
9 /*   Twitter Plugin for Friendika
10  *
11  *   Author: Tobias Diekershoff
12  *           tobias.diekershoff@gmx.net
13  *
14  *   License:3-clause BSD license
15  *
16  *   Configuration:
17  *     To use this plugin you need a OAuth Consumer key pair (key & secret)
18  *     you can get it from Twitter at https://twitter.com/apps
19  *
20  *     Register your Friendika site as "Client" application with "Read & Write" access
21  *     we do not need "Twitter as login". When you've registered the app you get the
22  *     OAuth Consumer key and secret pair for your application/site.
23  *
24  *     Add this key pair to your global .htconfig.php
25  *
26  *     $a->config['twitter']['consumerkey'] = 'your consumer_key here';
27  *     $a->config['twitter']['consumersecret'] = 'your consumer_secret here';
28  *
29  *     To activate the plugin itself add it to the $a->config['system']['addon']
30  *     setting. After this, your user can configure their Twitter account settings
31  *     from "Settings -> Plugin Settings".
32  *
33  *     Requirements: PHP5, curl [Slinky library]
34  *
35  *     Documentation: http://diekershoff.homeunix.net/redmine/wiki/friendikaplugin/Twitter_Plugin
36  */
37
38 /*   __TODO__
39  *
40  *   - what about multimedia content?
41  *     so far we just strip HTML tags from the message
42  */
43
44 function twitter_install() {
45         //  we need some hooks, for the configuration and for sending tweets
46         register_hook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
47         register_hook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
48         register_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
49         register_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
50         logger("installed twitter");
51 }
52
53
54 function twitter_uninstall() {
55         unregister_hook('connector_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
56         unregister_hook('connector_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
57         unregister_hook('plugin_settings', 'addon/twitter/twitter.php', 'twitter_settings'); 
58         unregister_hook('plugin_settings_post', 'addon/twitter/twitter.php', 'twitter_settings_post');
59         unregister_hook('post_local_end', 'addon/twitter/twitter.php', 'twitter_post_hook');
60         unregister_hook('jot_networks', 'addon/twitter/twitter.php', 'twitter_jot_nets');
61 }
62
63 function twitter_jot_nets(&$a,&$b) {
64         if(! local_user())
65                 return;
66
67         $tw_post = get_pconfig(local_user(),'twitter','post');
68         if(intval($tw_post) == 1) {
69                 $tw_defpost = get_pconfig(local_user(),'twitter','post_by_default');
70                 $selected = ((intval($tw_defpost) == 1) ? ' checked="checked" ' : '');
71                 $b .= '<div class="profile-jot-net"><input type="checkbox" name="twitter_enable"' . $selected . ' value="1" /> ' 
72                         . t('Post to Twitter') . '</div>';      
73         }
74
75
76 }
77
78 function twitter_settings_post ($a,$post) {
79         if(! local_user())
80                 return;
81         // don't check twitter settings if twitter submit button is not clicked 
82         if (!x($_POST,'twitter-submit')) return;
83         
84         if (isset($_POST['twitter-disconnect'])) {
85                 /***
86                  * if the twitter-disconnect checkbox is set, clear the OAuth key/secret pair
87                  * from the user configuration
88                  * TODO can we revoke the access tokens at Twitter and do we need to do so?
89                  */
90                 del_pconfig( local_user(), 'twitter', 'consumerkey'  );
91                 del_pconfig( local_user(), 'twitter', 'consumersecret' );
92                 del_pconfig( local_user(), 'twitter', 'post' );
93                 del_pconfig( local_user(), 'twitter', 'post_by_default' );
94         } else {
95         if (isset($_POST['twitter-pin'])) {
96                 //  if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
97                 logger('got a Twitter PIN');
98                 require_once('library/twitteroauth.php');
99                 $ckey    = get_config('twitter', 'consumerkey'  );
100                 $csecret = get_config('twitter', 'consumersecret' );
101                 //  the token and secret for which the PIN was generated were hidden in the settings
102                 //  form as token and token2, we need a new connection to Twitter using these token
103                 //  and secret to request a Access Token with the PIN
104                 $connection = new TwitterOAuth($ckey, $csecret, $_POST['twitter-token'], $_POST['twitter-token2']);
105                 $token   = $connection->getAccessToken( $_POST['twitter-pin'] );
106                 //  ok, now that we have the Access Token, save them in the user config
107                 set_pconfig(local_user(),'twitter', 'oauthtoken',  $token['oauth_token']);
108                 set_pconfig(local_user(),'twitter', 'oauthsecret', $token['oauth_token_secret']);
109                 set_pconfig(local_user(),'twitter', 'post', 1);
110                 //  reload the Addon Settings page, if we don't do it see Bug #42
111                 goaway($a->get_baseurl().'/settings/connectors');
112         } else {
113                 //  if no PIN is supplied in the POST variables, the user has changed the setting
114                 //  to post a tweet for every new __public__ posting to the wall
115                 set_pconfig(local_user(),'twitter','post',intval($_POST['twitter-enable']));
116                 set_pconfig(local_user(),'twitter','post_by_default',intval($_POST['twitter-default']));
117                 info( t('Twitter settings updated.') . EOL);
118         }}
119 }
120 function twitter_settings(&$a,&$s) {
121         if(! local_user())
122                 return;
123         $a->page['htmlhead'] .= '<link rel="stylesheet"  type="text/css" href="' . $a->get_baseurl() . '/addon/twitter/twitter.css' . '" media="all" />' . "\r\n";
124         /***
125          * 1) Check that we have global consumer key & secret
126          * 2) If no OAuthtoken & stuff is present, generate button to get some
127          * 3) Checkbox for "Send public notices (140 chars only)
128          */
129         $ckey    = get_config('twitter', 'consumerkey' );
130         $csecret = get_config('twitter', 'consumersecret' );
131         $otoken  = get_pconfig(local_user(), 'twitter', 'oauthtoken'  );
132         $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' );
133         $enabled = get_pconfig(local_user(), 'twitter', 'post');
134         $checked = (($enabled) ? ' checked="checked" ' : '');
135         $defenabled = get_pconfig(local_user(),'twitter','post_by_default');
136         $defchecked = (($defenabled) ? ' checked="checked" ' : '');
137
138         $s .= '<div class="settings-block">';
139         $s .= '<h3>'. t('Twitter Posting Settings') .'</h3>';
140
141         if ( (!$ckey) && (!$csecret) ) {
142                 /***
143                  * no global consumer keys
144                  * display warning and skip personal config
145                  */
146                 $s .= '<p>'. t('No consumer key pair for Twitter found. Please contact your site administrator.') .'</p>';
147         } else {
148                 /***
149                  * ok we have a consumer key pair now look into the OAuth stuff
150                  */
151                 if ( (!$otoken) && (!$osecret) ) {
152                         /***
153                          * the user has not yet connected the account to twitter...
154                          * get a temporary OAuth key/secret pair and display a button with
155                          * which the user can request a PIN to connect the account to a
156                          * account at Twitter.
157                          */
158                         require_once('library/twitteroauth.php');
159                         $connection = new TwitterOAuth($ckey, $csecret);
160                         $request_token = $connection->getRequestToken();
161                         $token = $request_token['oauth_token'];
162                         /***
163                          *  make some nice form
164                          */
165                         $s .= '<p>'. t('At this Friendika 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>';
166                         $s .= '<a href="'.$connection->getAuthorizeURL($token).'" target="_twitter"><img src="addon/twitter/lighter.png" alt="'.t('Log in with Twitter').'"></a>';
167                         $s .= '<div id="twitter-pin-wrapper">';
168                         $s .= '<label id="twitter-pin-label" for="twitter-pin">'. t('Copy the PIN from Twitter here') .'</label>';
169                         $s .= '<input id="twitter-pin" type="text" name="twitter-pin" />';
170                         $s .= '<input id="twitter-token" type="hidden" name="twitter-token" value="'.$token.'" />';
171                         $s .= '<input id="twitter-token2" type="hidden" name="twitter-token2" value="'.$request_token['oauth_token_secret'].'" />';
172             $s .= '</div><div class="clear"></div>';
173             $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Submit') . '" /></div>';
174                 } else {
175                         /***
176                          *  we have an OAuth key / secret pair for the user
177                          *  so let's give a chance to disable the postings to Twitter
178                          */
179                         require_once('library/twitteroauth.php');
180                         $connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
181                         $details = $connection->get('account/verify_credentials');
182                         $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>';
183                         $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>';
184                         $s .= '<div id="twitter-enable-wrapper">';
185                         $s .= '<label id="twitter-enable-label" for="twitter-checkbox">'. t('Allow posting to Twitter'). '</label>';
186                         $s .= '<input id="twitter-checkbox" type="checkbox" name="twitter-enable" value="1" ' . $checked . '/>';
187                         $s .= '<div class="clear"></div>';
188                         $s .= '<label id="twitter-default-label" for="twitter-default">'. t('Send public postings to Twitter by default') .'</label>';
189                         $s .= '<input id="twitter-default" type="checkbox" name="twitter-default" value="1" ' . $defchecked . '/>';
190                         $s .= '</div><div class="clear"></div>';
191
192                         $s .= '<div id="twitter-disconnect-wrapper">';
193                         $s .= '<label id="twitter-disconnect-label" for="twitter-disconnect">'. t('Clear OAuth configuration') .'</label>';
194                         $s .= '<input id="twitter-disconnect" type="checkbox" name="twitter-disconnect" value="1" />';
195                         $s .= '</div><div class="clear"></div>';
196                         $s .= '<div class="settings-submit-wrapper" ><input type="submit" name="twitter-submit" class="settings-submit" value="' . t('Submit') . '" /></div>'; 
197                 }
198         }
199         $s .= '</div><div class="clear"></div></div>';
200 }
201
202
203 function twitter_post_hook(&$a,&$b) {
204
205         /**
206          * Post to Twitter
207          */
208
209         logger('twitter post invoked');
210
211         if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (! $b['parent']) ) {
212
213                 // Twitter is not considered a private network
214                 if($b['prvnets'])
215                         return;
216
217
218                 load_pconfig(local_user(), 'twitter');
219
220                 $ckey    = get_config('twitter', 'consumerkey'  );
221                 $csecret = get_config('twitter', 'consumersecret' );
222                 $otoken  = get_pconfig(local_user(), 'twitter', 'oauthtoken'  );
223                 $osecret = get_pconfig(local_user(), 'twitter', 'oauthsecret' );
224
225                 if($ckey && $csecret && $otoken && $osecret) {
226
227                         $twitter_post = intval(get_pconfig(local_user(),'twitter','post'));
228                         $twitter_enable = (($twitter_post && x($_POST,'twitter_enable')) ? intval($_POST['twitter_enable']) : 0);
229
230                         // if API is used, default to the chosen settings
231                         if($_POST['api_source'] && intval(get_pconfig(local_user(),'twitter','post_by_default')))
232                                 $twitter_enable = 1;
233
234                         if($twitter_post && $twitter_enable) {
235                                 logger('Posting to Twitter', LOGGER_DEBUG);
236                                 require_once('library/twitteroauth.php');
237                                 require_once('include/bbcode.php');     
238                                 $tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
239                                 $max_char = 140; // max. length for a tweet
240                                 $msg = strip_tags(bbcode($b['body']));
241                                 if ( strlen($msg) > $max_char) {
242                                         $shortlink = "";
243                                         require_once('library/slinky.php');
244                                         // post url = base url + /display/ + owner + post id
245                                         // we construct this from the Owner link and replace
246                                         // profile by display - this will cause an error when
247                                         // /profile/ is in the owner url twice but I don't
248                                         // think this will be very common...
249                                         $posturl = str_replace('/profile/','/display/',$b['owner-link']).'/'.$b['id'];
250                                         $slinky = new Slinky( $posturl );
251                                         // setup a cascade of shortening services
252                                         // try to get a short link from these services
253                                         // in the order ur1.ca, trim, id.gd, tinyurl
254                                         $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
255                                         $shortlink = $slinky->short();
256                                         // the new message will be shortened such that "... $shortlink"
257                                         // will fit into the character limit
258                                         $msg = substr($msg, 0, $max_char-strlen($shortlink)-4);
259                                         $msg .= '... ' . $shortlink;
260                                 }
261                 // and now tweet it :-)
262                                 if(strlen($msg)) {
263                                         $result = $tweet->post('statuses/update', array('status' => $msg));
264                                         logger('twitter_post returns: ' . $result);
265                                 }
266
267                         }
268                 }
269         }
270 }
271
272 function twitter_plugin_admin_post(&$a){
273         $consumerkey    =       ((x($_POST,'consumerkey'))              ? notags(trim($_POST['consumerkey']))   : '');
274         $consumersecret =       ((x($_POST,'consumersecret'))   ? notags(trim($_POST['consumersecret'])): '');
275         set_config('twitter','consumerkey',$consumerkey);
276         set_config('twitter','consumersecret',$consumersecret);
277         info( t('Settings updated.'). EOL );
278 }
279 function twitter_plugin_admin(&$a, &$o){
280         $t = file_get_contents( dirname(__file__). "/admin.tpl" );
281         $o = replace_macros($t, array(
282                 '$submit' => t('Submit'),
283                                                                 // name, label, value, help, [extra values]
284                 '$consumerkey' => array('consumerkey', t('Consumer key'),  get_config('twitter', 'consumerkey' ), ''),
285                 '$consumersecret' => array('consumersecret', t('Consumer secret'),  get_config('twitter', 'consumersecret' ), '')
286         ));
287 }