]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitterauthorization.php
3f7316b7a40f2087e97cedf10fd65c312e665195
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitterauthorization.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Class for doing OAuth authentication against Twitter
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  TwitterauthorizationAction
23  * @package   StatusNet
24  * @author    Zach Copley <zach@status.net>
25  * @copyright 2009 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET') && !defined('LACONICA')) {
31     exit(1);
32 }
33
34 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
35
36 /**
37  * Class for doing OAuth authentication against Twitter
38  *
39  * Peforms the OAuth "dance" between StatusNet and Twitter -- requests a token,
40  * authorizes it, and exchanges it for an access token.  It also creates a link
41  * (Foreign_link) between the StatusNet user and Twitter user and stores the
42  * access token and secret in the link.
43  *
44  * @category Twitter
45  * @package  StatusNet
46  * @author   Zach Copley <zach@status.net>
47  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
48  * @link     http://laconi.ca/
49  *
50  */
51 class TwitterauthorizationAction extends Action
52 {
53     var $twuid = null;
54     var $tw_fields  = null;
55     var $access_token = null;
56
57     /**
58      * Initialize class members. Looks for 'oauth_token' parameter.
59      *
60      * @param array $args misc. arguments
61      *
62      * @return boolean true
63      */
64     function prepare($args)
65     {
66         parent::prepare($args);
67
68         $this->oauth_token = $this->arg('oauth_token');
69
70         return true;
71     }
72
73     /**
74      * Handler method
75      *
76      * @param array $args is ignored since it's now passed in in prepare()
77      *
78      * @return nothing
79      */
80     function handle($args)
81     {
82         parent::handle($args);
83
84         if (common_logged_in()) {
85             $user  = common_current_user();
86             $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE);
87
88             // If there's already a foreign link record, it means we already
89             // have an access token, and this is unecessary. So go back.
90
91             if (isset($flink)) {
92                 common_redirect(common_local_url('twittersettings'));
93             }
94         }
95
96         if ($_SERVER['REQUEST_METHOD'] == 'POST') {
97
98             // User was not logged in to StatusNet before
99
100             $this->twuid = $this->trimmed('twuid');
101
102             $this->tw_fields = array('name' => $this->trimmed('tw_fields_name'),
103                                      'fullname' => $this->trimmed('tw_fields_fullname'));
104
105             $this->access_token = new OAuthToken($this->trimmed('access_token_key'), $this->trimmed('access_token_secret'));
106
107             $token = $this->trimmed('token');
108
109             if (!$token || $token != common_session_token()) {
110                 $this->showForm(_('There was a problem with your session token. Try again, please.'));
111                 return;
112             }
113
114             if ($this->arg('create')) {
115                 if (!$this->boolean('license')) {
116                     $this->showForm(_('You can\'t register if you don\'t agree to the license.'),
117                                     $this->trimmed('newname'));
118                     return;
119                 }
120                 $this->createNewUser();
121             } else if ($this->arg('connect')) {
122                 $this->connectNewUser();
123             } else {
124                 common_debug('Twitter Connect Plugin - ' .
125                              print_r($this->args, true));
126                 $this->showForm(_('Something weird happened.'),
127                                 $this->trimmed('newname'));
128             }
129         } else {
130             // $this->oauth_token is only populated once Twitter authorizes our
131             // request token. If it's empty we're at the beginning of the auth
132             // process
133
134             if (empty($this->oauth_token)) {
135                 $this->authorizeRequestToken();
136             } else {
137                 $this->saveAccessToken();
138             }
139         }
140     }
141
142     /**
143      * Asks Twitter for a request token, and then redirects to Twitter
144      * to authorize it.
145      *
146      * @return nothing
147      */
148     function authorizeRequestToken()
149     {
150         try {
151
152             // Get a new request token and authorize it
153
154             $client  = new TwitterOAuthClient();
155             $req_tok =
156               $client->getRequestToken(TwitterOAuthClient::$requestTokenURL);
157
158             // Sock the request token away in the session temporarily
159
160             $_SESSION['twitter_request_token']        = $req_tok->key;
161             $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
162
163             $auth_link = $client->getAuthorizeLink($req_tok);
164
165         } catch (OAuthClientException $e) {
166             $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s',
167                            $e->getCode(), $e->getMessage());
168             $this->serverError(_m('Couldn\'t link your Twitter account.'));
169         }
170
171         common_redirect($auth_link);
172     }
173
174     /**
175      * Called when Twitter returns an authorized request token. Exchanges
176      * it for an access token and stores it.
177      *
178      * @return nothing
179      */
180     function saveAccessToken()
181     {
182
183         // Check to make sure Twitter returned the same request
184         // token we sent them
185
186         if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
187             $this->serverError(_m('Couldn\'t link your Twitter account.'));
188         }
189
190         $twitter_user = null;
191
192         try {
193
194             $client = new TwitterOAuthClient($_SESSION['twitter_request_token'],
195                 $_SESSION['twitter_request_token_secret']);
196
197             // Exchange the request token for an access token
198
199             $atok = $client->getAccessToken(TwitterOAuthClient::$accessTokenURL);
200
201             // Test the access token and get the user's Twitter info
202
203             $client       = new TwitterOAuthClient($atok->key, $atok->secret);
204             $twitter_user = $client->verifyCredentials();
205
206         } catch (OAuthClientException $e) {
207             $msg = sprintf('OAuth client error - code: %1$s, msg: %2$s',
208                            $e->getCode(), $e->getMessage());
209             $this->serverError(_m('Couldn\'t link your Twitter account.'));
210         }
211
212         if (common_logged_in()) {
213
214             // Save the access token and Twitter user info
215
216             $this->saveForeignLink($atok, $twitter_user);
217
218         } else {
219
220             $this->twuid = $twitter_user->id;
221             $this->tw_fields = array("name" => $twitter_user->screen_name, "fullname" => $twitter_user->name);
222             $this->access_token = $atok;
223             $this->tryLogin();
224         }
225
226         // Clean up the the mess we made in the session
227
228         unset($_SESSION['twitter_request_token']);
229         unset($_SESSION['twitter_request_token_secret']);
230
231         if (common_logged_in()) {
232             common_redirect(common_local_url('twittersettings'));
233         }
234     }
235
236     /**
237      * Saves a Foreign_link between Twitter user and local user,
238      * which includes the access token and secret.
239      *
240      * @param OAuthToken $access_token the access token to save
241      * @param mixed      $twitter_user twitter API user object
242      *
243      * @return nothing
244      */
245     function saveForeignLink($access_token, $twitter_user)
246     {
247         $user = common_current_user();
248
249         $flink = new Foreign_link();
250
251         $flink->user_id     = $user->id;
252         $flink->foreign_id  = $twitter_user->id;
253         $flink->service     = TWITTER_SERVICE;
254
255         $creds = TwitterOAuthClient::packToken($access_token);
256
257         $flink->credentials = $creds;
258         $flink->created     = common_sql_now();
259
260         // Defaults: noticesync on, everything else off
261
262         $flink->set_flags(true, false, false, false);
263
264         $flink_id = $flink->insert();
265
266         if (empty($flink_id)) {
267             common_log_db_error($flink, 'INSERT', __FILE__);
268                 $this->serverError(_m('Couldn\'t link your Twitter account.'));
269         }
270
271         save_twitter_user($twitter_user->id, $twitter_user->screen_name);
272     }
273
274     function flinkUser($user_id, $twuid)
275     {
276         $flink = new Foreign_link();
277
278         $flink->user_id     = $user_id;
279         $flink->foreign_id  = $twuid;
280         $flink->service     = TWITTER_SERVICE;
281
282         $creds = TwitterOAuthClient::packToken($this->access_token);
283
284         $flink->credentials = $creds;
285         $flink->created     = common_sql_now();
286
287         // Defaults: noticesync on, everything else off
288
289         $flink->set_flags(true, false, false, false);
290
291         $flink_id = $flink->insert();
292
293         if (empty($flink_id)) {
294             common_log_db_error($flink, 'INSERT', __FILE__);
295                 $this->serverError(_('Couldn\'t link your Twitter account.'));
296         }
297
298         save_twitter_user($twuid, $this->tw_fields['name']);
299
300         return $flink_id;
301     }
302
303     function showPageNotice()
304     {
305         if ($this->error) {
306             $this->element('div', array('class' => 'error'), $this->error);
307         } else {
308             $this->element('div', 'instructions',
309                            sprintf(_('This is the first time you\'ve logged into %s so we must connect your Twitter account to a local account. You can either create a new account, or connect with your existing account, if you have one.'), common_config('site', 'name')));
310         }
311     }
312
313     function title()
314     {
315         return _('Twitter Account Setup');
316     }
317
318     function showForm($error=null, $username=null)
319     {
320         $this->error = $error;
321         $this->username = $username;
322
323         $this->showPage();
324     }
325
326     function showPage()
327     {
328         parent::showPage();
329     }
330
331     function showContent()
332     {
333         if (!empty($this->message_text)) {
334             $this->element('p', null, $this->message);
335             return;
336         }
337
338         $this->elementStart('form', array('method' => 'post',
339                                           'id' => 'form_settings_twitter_connect',
340                                           'class' => 'form_settings',
341                                           'action' => common_local_url('twitterauthorization')));
342         $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
343         $this->element('legend', null, _('Connection options'));
344         $this->elementStart('ul', 'form_data');
345         $this->elementStart('li');
346         $this->element('input', array('type' => 'checkbox',
347                                       'id' => 'license',
348                                       'class' => 'checkbox',
349                                       'name' => 'license',
350                                       'value' => 'true'));
351         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
352         $this->text(_('My text and files are available under '));
353         $this->element('a', array('href' => common_config('license', 'url')),
354                        common_config('license', 'title'));
355         $this->text(_(' except this private data: password, email address, IM address, phone number.'));
356         $this->elementEnd('label');
357         $this->elementEnd('li');
358         $this->elementEnd('ul');
359         $this->hidden('access_token_key', $this->access_token->key);
360         $this->hidden('access_token_secret', $this->access_token->secret);
361         $this->hidden('twuid', $this->twuid);
362         $this->hidden('tw_fields_name', $this->tw_fields['name']);
363         $this->hidden('tw_fields_fullname', $this->tw_fields['fullname']);
364
365         $this->elementStart('fieldset');
366         $this->hidden('token', common_session_token());
367         $this->element('legend', null,
368                        _('Create new account'));
369         $this->element('p', null,
370                        _('Create a new user with this nickname.'));
371         $this->elementStart('ul', 'form_data');
372         $this->elementStart('li');
373         $this->input('newname', _('New nickname'),
374                      ($this->username) ? $this->username : '',
375                      _('1-64 lowercase letters or numbers, no punctuation or spaces'));
376         $this->elementEnd('li');
377         $this->elementEnd('ul');
378         $this->submit('create', _('Create'));
379         $this->elementEnd('fieldset');
380
381         $this->elementStart('fieldset');
382         $this->element('legend', null,
383                        _('Connect existing account'));
384         $this->element('p', null,
385                        _('If you already have an account, login with your username and password to connect it to your Twitter account.'));
386         $this->elementStart('ul', 'form_data');
387         $this->elementStart('li');
388         $this->input('nickname', _('Existing nickname'));
389         $this->elementEnd('li');
390         $this->elementStart('li');
391         $this->password('password', _('Password'));
392         $this->elementEnd('li');
393         $this->elementEnd('ul');
394         $this->submit('connect', _('Connect'));
395         $this->elementEnd('fieldset');
396
397         $this->elementEnd('fieldset');
398         $this->elementEnd('form');
399     }
400
401     function message($msg)
402     {
403         $this->message_text = $msg;
404         $this->showPage();
405     }
406
407     function createNewUser()
408     {
409         if (common_config('site', 'closed')) {
410             $this->clientError(_('Registration not allowed.'));
411             return;
412         }
413
414         $invite = null;
415
416         if (common_config('site', 'inviteonly')) {
417             $code = $_SESSION['invitecode'];
418             if (empty($code)) {
419                 $this->clientError(_('Registration not allowed.'));
420                 return;
421             }
422
423             $invite = Invitation::staticGet($code);
424
425             if (empty($invite)) {
426                 $this->clientError(_('Not a valid invitation code.'));
427                 return;
428             }
429         }
430
431         $nickname = $this->trimmed('newname');
432
433         if (!Validate::string($nickname, array('min_length' => 1,
434                                                'max_length' => 64,
435                                                'format' => NICKNAME_FMT))) {
436             $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
437             return;
438         }
439
440         if (!User::allowed_nickname($nickname)) {
441             $this->showForm(_('Nickname not allowed.'));
442             return;
443         }
444
445         if (User::staticGet('nickname', $nickname)) {
446             $this->showForm(_('Nickname already in use. Try another one.'));
447             return;
448         }
449
450         $fullname = trim($this->tw_fields['fullname']);
451
452         $args = array('nickname' => $nickname, 'fullname' => $fullname);
453
454         if (!empty($invite)) {
455             $args['code'] = $invite->code;
456         }
457
458         $user = User::register($args);
459
460         $result = $this->flinkUser($user->id, $this->twuid);
461
462         if (!$result) {
463             $this->serverError(_('Error connecting user to Twitter.'));
464             return;
465         }
466
467         common_set_user($user);
468         common_real_login(true);
469
470         common_debug('TwitterBridge Plugin - ' .
471                      "Registered new user $user->id from Twitter user $this->fbuid");
472
473         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
474                         303);
475     }
476
477     function connectNewUser()
478     {
479         $nickname = $this->trimmed('nickname');
480         $password = $this->trimmed('password');
481
482         if (!common_check_user($nickname, $password)) {
483             $this->showForm(_('Invalid username or password.'));
484             return;
485         }
486
487         $user = User::staticGet('nickname', $nickname);
488
489         if (!empty($user)) {
490             common_debug('TwitterBridge Plugin - ' .
491                          "Legit user to connect to Twitter: $nickname");
492         }
493
494         $result = $this->flinkUser($user->id, $this->twuid);
495
496         if (!$result) {
497             $this->serverError(_('Error connecting user to Twitter.'));
498             return;
499         }
500
501         common_debug('TwitterBridge Plugin - ' .
502                      "Connected Twitter user $this->fbuid to local user $user->id");
503
504         common_set_user($user);
505         common_real_login(true);
506
507         $this->goHome($user->nickname);
508     }
509
510     function connectUser()
511     {
512         $user = common_current_user();
513
514         $result = $this->flinkUser($user->id, $this->twuid);
515
516         if (empty($result)) {
517             $this->serverError(_('Error connecting user to Twitter.'));
518             return;
519         }
520
521         common_debug('TwitterBridge Plugin - ' .
522                      "Connected Twitter user $this->fbuid to local user $user->id");
523
524         // Return to Twitter connection settings tab
525         common_redirect(common_local_url('twittersettings'), 303);
526     }
527
528     function tryLogin()
529     {
530         common_debug('TwitterBridge Plugin - ' .
531                      "Trying login for Twitter user $this->twuid.");
532
533         $flink = Foreign_link::getByForeignID($this->twuid, TWITTER_SERVICE);
534
535         if (!empty($flink)) {
536             $user = $flink->getUser();
537
538             if (!empty($user)) {
539
540                 common_debug('TwitterBridge Plugin - ' .
541                              "Logged in Twitter user $flink->foreign_id as user $user->id ($user->nickname)");
542
543                 common_set_user($user);
544                 common_real_login(true);
545                 $this->goHome($user->nickname);
546             }
547
548         } else {
549
550             common_debug('TwitterBridge Plugin - ' .
551                          "No flink found for twuid: $this->twuid - new user");
552
553             $this->showForm(null, $this->bestNewNickname());
554         }
555     }
556
557     function goHome($nickname)
558     {
559         $url = common_get_returnto();
560         if ($url) {
561             // We don't have to return to it again
562             common_set_returnto(null);
563         } else {
564             $url = common_local_url('all',
565                                     array('nickname' =>
566                                           $nickname));
567         }
568
569         common_redirect($url, 303);
570     }
571
572     function bestNewNickname()
573     {
574         if (!empty($this->tw_fields['name'])) {
575             $nickname = $this->nicknamize($this->tw_fields['name']);
576             if ($this->isNewNickname($nickname)) {
577                 return $nickname;
578             }
579         }
580
581         return null;
582     }
583
584      // Given a string, try to make it work as a nickname
585
586      function nicknamize($str)
587      {
588          $str = preg_replace('/\W/', '', $str);
589          $str = str_replace(array('-', '_'), '', $str);
590          return strtolower($str);
591      }
592
593     function isNewNickname($str)
594     {
595         if (!Validate::string($str, array('min_length' => 1,
596                                           'max_length' => 64,
597                                           'format' => NICKNAME_FMT))) {
598             return false;
599         }
600         if (!User::allowed_nickname($str)) {
601             return false;
602         }
603         if (User::staticGet('nickname', $str)) {
604             return false;
605         }
606         return true;
607     }
608
609 }
610