]> git.mxchange.org Git - quix0rs-gnu-social.git/blobdiff - plugins/TwitterBridge/twitterauthorization.php
Add email field to Twitter registration form; needed when RequireValidatedEmail plugi...
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitterauthorization.php
index 3f7316b7a40f2087e97cedf10fd65c312e665195..972fa527d41340fac906c14482bb2064237002d3 100644 (file)
  * You should have received a copy of the GNU Affero General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
- * @category  TwitterauthorizationAction
+ * @category  Plugin
  * @package   StatusNet
  * @author    Zach Copley <zach@status.net>
- * @copyright 2009 StatusNet, Inc.
+ * @author    Julien C <chaumond@gmail.com>
+ * @copyright 2009-2010 StatusNet, Inc.
  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  * @link      http://status.net/
  */
@@ -41,18 +42,21 @@ require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
  * (Foreign_link) between the StatusNet user and Twitter user and stores the
  * access token and secret in the link.
  *
- * @category Twitter
+ * @category Plugin
  * @package  StatusNet
  * @author   Zach Copley <zach@status.net>
+ * @author   Julien C <chaumond@gmail.com>
  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
- * @link     http://laconi.ca/
+ * @link     http://status.net/
  *
  */
 class TwitterauthorizationAction extends Action
 {
-    var $twuid = null;
-    var $tw_fields  = null;
+    var $twuid        = null;
+    var $tw_fields    = null;
     var $access_token = null;
+    var $signin       = null;
+    var $verifier     = null;
 
     /**
      * Initialize class members. Looks for 'oauth_token' parameter.
@@ -65,7 +69,9 @@ class TwitterauthorizationAction extends Action
     {
         parent::prepare($args);
 
+        $this->signin      = $this->boolean('signin');
         $this->oauth_token = $this->arg('oauth_token');
+        $this->verifier    = $this->arg('oauth_verifier');
 
         return true;
     }
@@ -85,11 +91,15 @@ class TwitterauthorizationAction extends Action
             $user  = common_current_user();
             $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE);
 
-            // If there's already a foreign link record, it means we already
-            // have an access token, and this is unecessary. So go back.
+            // If there's already a foreign link record and a foreign user
+            // it means the accounts are already linked, and this is unecessary.
+            // So go back.
 
             if (isset($flink)) {
-                common_redirect(common_local_url('twittersettings'));
+                $fuser = $flink->getForeignUser();
+                if (!empty($fuser)) {
+                    common_redirect(common_local_url('twittersettings'));
+                }
             }
         }
 
@@ -99,7 +109,7 @@ class TwitterauthorizationAction extends Action
 
             $this->twuid = $this->trimmed('twuid');
 
-            $this->tw_fields = array('name' => $this->trimmed('tw_fields_name'),
+            $this->tw_fields = array('screen_name' => $this->trimmed('tw_fields_screen_name'),
                                      'fullname' => $this->trimmed('tw_fields_fullname'));
 
             $this->access_token = new OAuthToken($this->trimmed('access_token_key'), $this->trimmed('access_token_secret'));
@@ -107,13 +117,13 @@ class TwitterauthorizationAction extends Action
             $token = $this->trimmed('token');
 
             if (!$token || $token != common_session_token()) {
-                $this->showForm(_('There was a problem with your session token. Try again, please.'));
+                $this->showForm(_m('There was a problem with your session token. Try again, please.'));
                 return;
             }
 
             if ($this->arg('create')) {
                 if (!$this->boolean('license')) {
-                    $this->showForm(_('You can\'t register if you don\'t agree to the license.'),
+                    $this->showForm(_m('You can\'t register if you don\'t agree to the license.'),
                                     $this->trimmed('newname'));
                     return;
                 }
@@ -121,9 +131,8 @@ class TwitterauthorizationAction extends Action
             } else if ($this->arg('connect')) {
                 $this->connectNewUser();
             } else {
-                common_debug('Twitter Connect Plugin - ' .
-                             print_r($this->args, true));
-                $this->showForm(_('Something weird happened.'),
+                common_debug('Twitter bridge - ' . print_r($this->args, true));
+                $this->showForm(_m('Something weird happened.'),
                                 $this->trimmed('newname'));
             }
         } else {
@@ -152,20 +161,25 @@ class TwitterauthorizationAction extends Action
             // Get a new request token and authorize it
 
             $client  = new TwitterOAuthClient();
-            $req_tok =
-              $client->getRequestToken(TwitterOAuthClient::$requestTokenURL);
+            $req_tok = $client->getRequestToken();
 
             // Sock the request token away in the session temporarily
 
             $_SESSION['twitter_request_token']        = $req_tok->key;
             $_SESSION['twitter_request_token_secret'] = $req_tok->secret;
 
-            $auth_link = $client->getAuthorizeLink($req_tok);
+            $auth_link = $client->getAuthorizeLink($req_tok, $this->signin);
 
         } catch (OAuthClientException $e) {
-            $msg = sprintf('OAuth client cURL error - code: %1s, msg: %2s',
-                           $e->getCode(), $e->getMessage());
-            $this->serverError(_m('Couldn\'t link your Twitter account.'));
+            $msg = sprintf(
+                'OAuth client error - code: %1s, msg: %2s',
+                $e->getCode(),
+                $e->getMessage()
+            );
+            common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
+            $this->serverError(
+                _m('Couldn\'t link your Twitter account.')
+            );
         }
 
         common_redirect($auth_link);
@@ -179,12 +193,13 @@ class TwitterauthorizationAction extends Action
      */
     function saveAccessToken()
     {
-
         // Check to make sure Twitter returned the same request
         // token we sent them
 
         if ($_SESSION['twitter_request_token'] != $this->oauth_token) {
-            $this->serverError(_m('Couldn\'t link your Twitter account.'));
+            $this->serverError(
+                _m('Couldn\'t link your Twitter account: oauth_token mismatch.')
+            );
         }
 
         $twitter_user = null;
@@ -196,7 +211,7 @@ class TwitterauthorizationAction extends Action
 
             // Exchange the request token for an access token
 
-            $atok = $client->getAccessToken(TwitterOAuthClient::$accessTokenURL);
+            $atok = $client->getAccessToken($this->verifier);
 
             // Test the access token and get the user's Twitter info
 
@@ -204,21 +219,29 @@ class TwitterauthorizationAction extends Action
             $twitter_user = $client->verifyCredentials();
 
         } catch (OAuthClientException $e) {
-            $msg = sprintf('OAuth client error - code: %1$s, msg: %2$s',
-                           $e->getCode(), $e->getMessage());
-            $this->serverError(_m('Couldn\'t link your Twitter account.'));
+            $msg = sprintf(
+                'OAuth client error - code: %1$s, msg: %2$s',
+                $e->getCode(),
+                $e->getMessage()
+            );
+            common_log(LOG_INFO, 'Twitter bridge - ' . $msg);
+            $this->serverError(
+                _m('Couldn\'t link your Twitter account.')
+            );
         }
 
         if (common_logged_in()) {
-
             // Save the access token and Twitter user info
 
-            $this->saveForeignLink($atok, $twitter_user);
+            $user = common_current_user();
+            $this->saveForeignLink($user->id, $twitter_user->id, $atok);
+            save_twitter_user($twitter_user->id, $twitter_user->screen_name);
 
         } else {
 
             $this->twuid = $twitter_user->id;
-            $this->tw_fields = array("name" => $twitter_user->screen_name, "fullname" => $twitter_user->name);
+            $this->tw_fields = array("screen_name" => $twitter_user->screen_name,
+                                     "fullname" => $twitter_user->name);
             $this->access_token = $atok;
             $this->tryLogin();
         }
@@ -237,49 +260,31 @@ class TwitterauthorizationAction extends Action
      * Saves a Foreign_link between Twitter user and local user,
      * which includes the access token and secret.
      *
-     * @param OAuthToken $access_token the access token to save
-     * @param mixed      $twitter_user twitter API user object
+     * @param int        $user_id StatusNet user ID
+     * @param int        $twuid   Twitter user ID
+     * @param OAuthToken $token   the access token to save
      *
      * @return nothing
      */
-    function saveForeignLink($access_token, $twitter_user)
+    function saveForeignLink($user_id, $twuid, $access_token)
     {
-        $user = common_current_user();
-
         $flink = new Foreign_link();
 
-        $flink->user_id     = $user->id;
-        $flink->foreign_id  = $twitter_user->id;
-        $flink->service     = TWITTER_SERVICE;
+        $flink->user_id = $user_id;
+        $flink->service = TWITTER_SERVICE;
 
-        $creds = TwitterOAuthClient::packToken($access_token);
-
-        $flink->credentials = $creds;
-        $flink->created     = common_sql_now();
-
-        // Defaults: noticesync on, everything else off
-
-        $flink->set_flags(true, false, false, false);
+        // delete stale flink, if any
+        $result = $flink->find(true);
 
-        $flink_id = $flink->insert();
-
-        if (empty($flink_id)) {
-            common_log_db_error($flink, 'INSERT', __FILE__);
-                $this->serverError(_m('Couldn\'t link your Twitter account.'));
+        if (!empty($result)) {
+            $flink->safeDelete();
         }
 
-        save_twitter_user($twitter_user->id, $twitter_user->screen_name);
-    }
-
-    function flinkUser($user_id, $twuid)
-    {
-        $flink = new Foreign_link();
-
         $flink->user_id     = $user_id;
         $flink->foreign_id  = $twuid;
         $flink->service     = TWITTER_SERVICE;
 
-        $creds = TwitterOAuthClient::packToken($this->access_token);
+        $creds = TwitterOAuthClient::packToken($access_token);
 
         $flink->credentials = $creds;
         $flink->created     = common_sql_now();
@@ -292,11 +297,9 @@ class TwitterauthorizationAction extends Action
 
         if (empty($flink_id)) {
             common_log_db_error($flink, 'INSERT', __FILE__);
-                $this->serverError(_('Couldn\'t link your Twitter account.'));
+            $this->serverError(_m('Couldn\'t link your Twitter account.'));
         }
 
-        save_twitter_user($twuid, $this->tw_fields['name']);
-
         return $flink_id;
     }
 
@@ -306,13 +309,13 @@ class TwitterauthorizationAction extends Action
             $this->element('div', array('class' => 'error'), $this->error);
         } else {
             $this->element('div', 'instructions',
-                           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')));
+                           sprintf(_m('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')));
         }
     }
 
     function title()
     {
-        return _('Twitter Account Setup');
+        return _m('Twitter Account Setup');
     }
 
     function showForm($error=null, $username=null)
@@ -328,6 +331,11 @@ class TwitterauthorizationAction extends Action
         parent::showPage();
     }
 
+    /**
+     * @fixme much of this duplicates core code, which is very fragile.
+     * Should probably be replaced with an extensible mini version of
+     * the core registration form.
+     */
     function showContent()
     {
         if (!empty($this->message_text)) {
@@ -340,7 +348,7 @@ class TwitterauthorizationAction extends Action
                                           'class' => 'form_settings',
                                           'action' => common_local_url('twitterauthorization')));
         $this->elementStart('fieldset', array('id' => 'settings_twitter_connect_options'));
-        $this->element('legend', null, _('Connection options'));
+        $this->element('legend', null, _m('Connection options'));
         $this->elementStart('ul', 'form_data');
         $this->elementStart('li');
         $this->element('input', array('type' => 'checkbox',
@@ -349,55 +357,99 @@ class TwitterauthorizationAction extends Action
                                       'name' => 'license',
                                       'value' => 'true'));
         $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
-        $this->text(_('My text and files are available under '));
-        $this->element('a', array('href' => common_config('license', 'url')),
-                       common_config('license', 'title'));
-        $this->text(_(' except this private data: password, email address, IM address, phone number.'));
+        $message = _m('My text and files are available under %s ' .
+                     'except this private data: password, ' .
+                     'email address, IM address, and phone number.');
+        $link = '<a href="' .
+                htmlspecialchars(common_config('license', 'url')) .
+                '">' .
+                htmlspecialchars(common_config('license', 'title')) .
+                '</a>';
+        $this->raw(sprintf(htmlspecialchars($message), $link));
         $this->elementEnd('label');
         $this->elementEnd('li');
         $this->elementEnd('ul');
         $this->hidden('access_token_key', $this->access_token->key);
         $this->hidden('access_token_secret', $this->access_token->secret);
         $this->hidden('twuid', $this->twuid);
-        $this->hidden('tw_fields_name', $this->tw_fields['name']);
-        $this->hidden('tw_fields_fullname', $this->tw_fields['fullname']);
+        $this->hidden('tw_fields_screen_name', $this->tw_fields['screen_name']);
+        $this->hidden('tw_fields_name', $this->tw_fields['fullname']);
 
         $this->elementStart('fieldset');
         $this->hidden('token', common_session_token());
         $this->element('legend', null,
-                       _('Create new account'));
+                       _m('Create new account'));
         $this->element('p', null,
-                       _('Create a new user with this nickname.'));
+                       _m('Create a new user with this nickname.'));
         $this->elementStart('ul', 'form_data');
+
+        // Hook point for captcha etc
+        Event::handle('StartRegistrationFormData', array($this));
+
         $this->elementStart('li');
-        $this->input('newname', _('New nickname'),
+        $this->input('newname', _m('New nickname'),
                      ($this->username) ? $this->username : '',
-                     _('1-64 lowercase letters or numbers, no punctuation or spaces'));
+                     _m('1-64 lowercase letters or numbers, no punctuation or spaces'));
         $this->elementEnd('li');
+        $this->elementStart('li');
+        $this->input('email', _('Email'), $this->getEmail(),
+                     _('Used only for updates, announcements, '.
+                       'and password recovery'));
+        $this->elementEnd('li');
+
+        // Hook point for captcha etc
+        Event::handle('EndRegistrationFormData', array($this));
+
         $this->elementEnd('ul');
-        $this->submit('create', _('Create'));
+        $this->submit('create', _m('Create'));
         $this->elementEnd('fieldset');
 
         $this->elementStart('fieldset');
         $this->element('legend', null,
-                       _('Connect existing account'));
+                       _m('Connect existing account'));
         $this->element('p', null,
-                       _('If you already have an account, login with your username and password to connect it to your Twitter account.'));
+                       _m('If you already have an account, login with your username and password to connect it to your Twitter account.'));
         $this->elementStart('ul', 'form_data');
         $this->elementStart('li');
-        $this->input('nickname', _('Existing nickname'));
+        $this->input('nickname', _m('Existing nickname'));
         $this->elementEnd('li');
         $this->elementStart('li');
-        $this->password('password', _('Password'));
+        $this->password('password', _m('Password'));
         $this->elementEnd('li');
         $this->elementEnd('ul');
-        $this->submit('connect', _('Connect'));
+        $this->submit('connect', _m('Connect'));
         $this->elementEnd('fieldset');
 
         $this->elementEnd('fieldset');
         $this->elementEnd('form');
     }
 
+    /**
+     * Get specified e-mail from the form, or the invite code.
+     *
+     * @return string
+     */
+    function getEmail()
+    {
+        $email = $this->trimmed('email');
+        if (!empty($email)) {
+            return $email;
+        }
+
+        // Terrible hack for invites...
+        if (common_config('site', 'inviteonly')) {
+            $code = $_SESSION['invitecode'];
+            if ($code) {
+                $invite = Invitation::staticGet($code);
+
+                if ($invite && $invite->address_type == 'email') {
+                    return $invite->address;
+                }
+            }
+        }
+        return '';
+    }
+
     function message($msg)
     {
         $this->message_text = $msg;
@@ -406,8 +458,12 @@ class TwitterauthorizationAction extends Action
 
     function createNewUser()
     {
+        if (!Event::handle('StartRegistrationTry', array($this))) {
+            return;
+        }
+
         if (common_config('site', 'closed')) {
-            $this->clientError(_('Registration not allowed.'));
+            $this->clientError(_m('Registration not allowed.'));
             return;
         }
 
@@ -416,34 +472,32 @@ class TwitterauthorizationAction extends Action
         if (common_config('site', 'inviteonly')) {
             $code = $_SESSION['invitecode'];
             if (empty($code)) {
-                $this->clientError(_('Registration not allowed.'));
+                $this->clientError(_m('Registration not allowed.'));
                 return;
             }
 
             $invite = Invitation::staticGet($code);
 
             if (empty($invite)) {
-                $this->clientError(_('Not a valid invitation code.'));
+                $this->clientError(_m('Not a valid invitation code.'));
                 return;
             }
         }
 
-        $nickname = $this->trimmed('newname');
-
-        if (!Validate::string($nickname, array('min_length' => 1,
-                                               'max_length' => 64,
-                                               'format' => NICKNAME_FMT))) {
-            $this->showForm(_('Nickname must have only lowercase letters and numbers and no spaces.'));
+        try {
+            $nickname = Nickname::normalize($this->trimmed('newname'));
+        } catch (NicknameException $e) {
+            $this->showForm($e->getMessage());
             return;
         }
 
         if (!User::allowed_nickname($nickname)) {
-            $this->showForm(_('Nickname not allowed.'));
+            $this->showForm(_m('Nickname not allowed.'));
             return;
         }
 
         if (User::staticGet('nickname', $nickname)) {
-            $this->showForm(_('Nickname already in use. Try another one.'));
+            $this->showForm(_m('Nickname already in use. Try another one.'));
             return;
         }
 
@@ -455,12 +509,26 @@ class TwitterauthorizationAction extends Action
             $args['code'] = $invite->code;
         }
 
+        $email = $this->getEmail();
+        if (!empty($email)) {
+            $args['email'] = $email;
+        }
+
         $user = User::register($args);
 
-        $result = $this->flinkUser($user->id, $this->twuid);
+        if (empty($user)) {
+            $this->serverError(_m('Error registering user.'));
+            return;
+        }
+
+        $result = $this->saveForeignLink($user->id,
+                                         $this->twuid,
+                                         $this->access_token);
+
+        save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
 
         if (!$result) {
-            $this->serverError(_('Error connecting user to Twitter.'));
+            $this->serverError(_m('Error connecting user to Twitter.'));
             return;
         }
 
@@ -468,7 +536,9 @@ class TwitterauthorizationAction extends Action
         common_real_login(true);
 
         common_debug('TwitterBridge Plugin - ' .
-                     "Registered new user $user->id from Twitter user $this->fbuid");
+                     "Registered new user $user->id from Twitter user $this->twuid");
+
+        Event::handle('EndRegistrationTry', array($this));
 
         common_redirect(common_local_url('showstream', array('nickname' => $user->nickname)),
                         303);
@@ -480,7 +550,7 @@ class TwitterauthorizationAction extends Action
         $password = $this->trimmed('password');
 
         if (!common_check_user($nickname, $password)) {
-            $this->showForm(_('Invalid username or password.'));
+            $this->showForm(_m('Invalid username or password.'));
             return;
         }
 
@@ -491,15 +561,19 @@ class TwitterauthorizationAction extends Action
                          "Legit user to connect to Twitter: $nickname");
         }
 
-        $result = $this->flinkUser($user->id, $this->twuid);
+        $result = $this->saveForeignLink($user->id,
+                                         $this->twuid,
+                                         $this->access_token);
+
+        save_twitter_user($this->twuid, $this->tw_fields['screen_name']);
 
         if (!$result) {
-            $this->serverError(_('Error connecting user to Twitter.'));
+            $this->serverError(_m('Error connecting user to Twitter.'));
             return;
         }
 
         common_debug('TwitterBridge Plugin - ' .
-                     "Connected Twitter user $this->fbuid to local user $user->id");
+                     "Connected Twitter user $this->twuid to local user $user->id");
 
         common_set_user($user);
         common_real_login(true);
@@ -514,12 +588,12 @@ class TwitterauthorizationAction extends Action
         $result = $this->flinkUser($user->id, $this->twuid);
 
         if (empty($result)) {
-            $this->serverError(_('Error connecting user to Twitter.'));
+            $this->serverError(_m('Error connecting user to Twitter.'));
             return;
         }
 
         common_debug('TwitterBridge Plugin - ' .
-                     "Connected Twitter user $this->fbuid to local user $user->id");
+                     "Connected Twitter user $this->twuid to local user $user->id");
 
         // Return to Twitter connection settings tab
         common_redirect(common_local_url('twittersettings'), 303);
@@ -530,7 +604,8 @@ class TwitterauthorizationAction extends Action
         common_debug('TwitterBridge Plugin - ' .
                      "Trying login for Twitter user $this->twuid.");
 
-        $flink = Foreign_link::getByForeignID($this->twuid, TWITTER_SERVICE);
+        $flink = Foreign_link::getByForeignID($this->twuid,
+                                              TWITTER_SERVICE);
 
         if (!empty($flink)) {
             $user = $flink->getUser();
@@ -571,8 +646,8 @@ class TwitterauthorizationAction extends Action
 
     function bestNewNickname()
     {
-        if (!empty($this->tw_fields['name'])) {
-            $nickname = $this->nicknamize($this->tw_fields['name']);
+        if (!empty($this->tw_fields['fullname'])) {
+            $nickname = $this->nicknamize($this->tw_fields['fullname']);
             if ($this->isNewNickname($nickname)) {
                 return $nickname;
             }
@@ -592,9 +667,7 @@ class TwitterauthorizationAction extends Action
 
     function isNewNickname($str)
     {
-        if (!Validate::string($str, array('min_length' => 1,
-                                          'max_length' => 64,
-                                          'format' => NICKNAME_FMT))) {
+        if (!Nickname::isValid($str)) {
             return false;
         }
         if (!User::allowed_nickname($str)) {