]> git.mxchange.org Git - quix0rs-gnu-social.git/commitdiff
Merge branch '1.0.x' into emailregistration
authorEvan Prodromou <evan@status.net>
Sun, 17 Apr 2011 21:48:15 +0000 (17:48 -0400)
committerEvan Prodromou <evan@status.net>
Sun, 17 Apr 2011 21:48:15 +0000 (17:48 -0400)
classes/Confirm_address.php
plugins/EmailRegistration/EmailRegistrationPlugin.php [new file with mode: 0644]
plugins/EmailRegistration/Email_confirmation.php [new file with mode: 0644]
plugins/EmailRegistration/emailregister.php [new file with mode: 0644]

index ed3875d223c0ff5935979861a4adc5951e919040..4b9bec64c63c4bbf5e37162766f905fed0a9c5c2 100644 (file)
@@ -28,4 +28,36 @@ class Confirm_address extends Memcached_DataObject
 
     function sequenceKey()
     { return array(false, false); }
+
+    static function getAddress($address, $addressType)
+    {
+        $ca = new Confirm_address();
+
+        $ca->address      = $address;
+        $ca->address_type = $addressType;
+
+        if ($ca->find(true)) {
+            return $ca;
+        }
+
+        return null;
+    }
+
+    static function saveNew($user, $address, $addressType, $extra=null)
+    {
+        $ca = new Confirm_address();
+
+        if (!empty($user)) {
+            $ca->user_id = $user->id;
+        }
+
+        $ca->address       = $address;
+        $ca->address_type  = $addressType;
+        $ca->address_extra = $extra;
+        $ca->code          = common_confirmation_code(64);
+
+        $ca->insert();
+
+        return $ca;
+    }
 }
diff --git a/plugins/EmailRegistration/EmailRegistrationPlugin.php b/plugins/EmailRegistration/EmailRegistrationPlugin.php
new file mode 100644 (file)
index 0000000..37780f6
--- /dev/null
@@ -0,0 +1,98 @@
+<?php
+/**
+ * StatusNet - the distributed open-source microblogging tool
+ * Copyright (C) 2011, StatusNet, Inc.
+ *
+ * Email-based registration, as on the StatusNet OnDemand service
+ *
+ * PHP version 5
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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  Email registration
+ * @package   StatusNet
+ * @author    Evan Prodromou <evan@status.net>
+ * @copyright 2011 StatusNet, Inc.
+ * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
+ * @link      http://status.net/
+ */
+
+if (!defined('STATUSNET')) {
+    // This check helps protect against security problems;
+    // your code file can't be executed directly from the web.
+    exit(1);
+}
+
+/**
+ * Email based registration plugin
+ *
+ * @category  Email registration
+ * @package   StatusNet
+ * @author    Brion Vibber <brionv@status.net>
+ * @author    Evan Prodromou <evan@status.net>
+ * @copyright 2011 StatusNet, Inc.
+ * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
+ * @link      http://status.net/
+ */
+
+class EmailRegistrationPlugin extends Plugin
+{
+    function onAutoload($cls)
+    {
+        $dir = dirname(__FILE__);
+
+        switch ($cls)
+        {
+        case 'EmailregisterAction':
+            include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
+            return false;
+        default:
+            return true;
+        }
+    }
+
+    /**
+     * Hijack main/register
+     */
+
+    function onStartConnectPath(&$path, &$defaults, &$rules, &$result)
+    {
+        static $toblock = array('main/register', 'main/register/:code');
+
+        if (in_array($path, $toblock) && $defaults['action'] != 'emailregister') {
+            return false;
+        }
+
+        return true;
+    }
+
+    function onRouterInitialized($m)
+    {
+        $m->connect('main/register/:code', array('action' => 'emailregister'));
+        $m->connect('main/register', array('action' => 'emailregister'));
+
+        return true;
+    }
+
+    function onPluginVersion(&$versions)
+    {
+        $versions[] = array('name' => 'EmailRegistration',
+                            'version' => STATUSNET_VERSION,
+                            'author' => 'Evan Prodromou',
+                            'homepage' => 'http://status.net/wiki/Plugin:EmailRegistration',
+                            'rawdescription' =>
+                            _m('Use email only for registration'));
+        return true;
+    }
+}
diff --git a/plugins/EmailRegistration/Email_confirmation.php b/plugins/EmailRegistration/Email_confirmation.php
new file mode 100644 (file)
index 0000000..38d68c9
--- /dev/null
@@ -0,0 +1,184 @@
+<?php
+/**
+ * Data class for counting greetings
+ *
+ * PHP version 5
+ *
+ * @category Data
+ * @package  StatusNet
+ * @author   Evan Prodromou <evan@status.net>
+ * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
+ * @link     http://status.net/
+ *
+ * StatusNet - the distributed open-source microblogging tool
+ * Copyright (C) 2009, StatusNet, Inc.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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/>.
+ */
+
+if (!defined('STATUSNET')) {
+    exit(1);
+}
+
+require_once INSTALLDIR . '/classes/Memcached_DataObject.php';
+
+/**
+ * Data class for counting greetings
+ *
+ * We use the DB_DataObject framework for data classes in StatusNet. Each
+ * table maps to a particular data class, making it easier to manipulate
+ * data.
+ *
+ * Data classes should extend Memcached_DataObject, the (slightly misnamed)
+ * extension of DB_DataObject that provides caching, internationalization,
+ * and other bits of good functionality to StatusNet-specific data classes.
+ *
+ * @category Action
+ * @package  StatusNet
+ * @author   Evan Prodromou <evan@status.net>
+ * @license  http://www.fsf.org/licensing/licenses/agpl.html AGPLv3
+ * @link     http://status.net/
+ *
+ * @see      DB_DataObject
+ */
+
+class User_greeting_count extends Memcached_DataObject
+{
+    public $__table = 'user_greeting_count'; // table name
+    public $user_id;                         // int(4)  primary_key not_null
+    public $greeting_count;                  // int(4)
+
+    /**
+     * Get an instance by key
+     *
+     * This is a utility method to get a single instance with a given key value.
+     *
+     * @param string $k Key to use to lookup (usually 'user_id' for this class)
+     * @param mixed  $v Value to lookup
+     *
+     * @return User_greeting_count object found, or null for no hits
+     *
+     */
+    function staticGet($k, $v=null)
+    {
+        return Memcached_DataObject::staticGet('User_greeting_count', $k, $v);
+    }
+
+    /**
+     * return table definition for DB_DataObject
+     *
+     * DB_DataObject needs to know something about the table to manipulate
+     * instances. This method provides all the DB_DataObject needs to know.
+     *
+     * @return array array of column definitions
+     */
+    function table()
+    {
+        return array('user_id' => DB_DATAOBJECT_INT + DB_DATAOBJECT_NOTNULL,
+                     'greeting_count' => DB_DATAOBJECT_INT);
+    }
+
+    /**
+     * return key definitions for DB_DataObject
+     *
+     * DB_DataObject needs to know about keys that the table has, since it
+     * won't appear in StatusNet's own keys list. In most cases, this will
+     * simply reference your keyTypes() function.
+     *
+     * @return array list of key field names
+     */
+    function keys()
+    {
+        return array_keys($this->keyTypes());
+    }
+
+    /**
+     * return key definitions for Memcached_DataObject
+     *
+     * Our caching system uses the same key definitions, but uses a different
+     * method to get them. This key information is used to store and clear
+     * cached data, so be sure to list any key that will be used for static
+     * lookups.
+     *
+     * @return array associative array of key definitions, field name to type:
+     *         'K' for primary key: for compound keys, add an entry for each component;
+     *         'U' for unique keys: compound keys are not well supported here.
+     */
+    function keyTypes()
+    {
+        return array('user_id' => 'K');
+    }
+
+    /**
+     * Magic formula for non-autoincrementing integer primary keys
+     *
+     * If a table has a single integer column as its primary key, DB_DataObject
+     * assumes that the column is auto-incrementing and makes a sequence table
+     * to do this incrementation. Since we don't need this for our class, we
+     * overload this method and return the magic formula that DB_DataObject needs.
+     *
+     * @return array magic three-false array that stops auto-incrementing.
+     */
+    function sequenceKey()
+    {
+        return array(false, false, false);
+    }
+
+    /**
+     * Increment a user's greeting count and return instance
+     *
+     * This method handles the ins and outs of creating a new greeting_count for a
+     * user or fetching the existing greeting count and incrementing its value.
+     *
+     * @param integer $user_id ID of the user to get a count for
+     *
+     * @return User_greeting_count instance for this user, with count already incremented.
+     */
+    static function inc($user_id)
+    {
+        $gc = User_greeting_count::staticGet('user_id', $user_id);
+
+        if (empty($gc)) {
+
+            $gc = new User_greeting_count();
+
+            $gc->user_id        = $user_id;
+            $gc->greeting_count = 1;
+
+            $result = $gc->insert();
+
+            if (!$result) {
+                // TRANS: Exception thrown when the user greeting count could not be saved in the database.
+                // TRANS: %d is a user ID (number).
+                throw Exception(sprintf(_m("Could not save new greeting count for %d."),
+                                        $user_id));
+            }
+        } else {
+            $orig = clone($gc);
+
+            $gc->greeting_count++;
+
+            $result = $gc->update($orig);
+
+            if (!$result) {
+                // TRANS: Exception thrown when the user greeting count could not be saved in the database.
+                // TRANS: %d is a user ID (number).
+                throw Exception(sprintf(_m("Could not increment greeting count for %d."),
+                                        $user_id));
+            }
+        }
+
+        return $gc;
+    }
+}
diff --git a/plugins/EmailRegistration/emailregister.php b/plugins/EmailRegistration/emailregister.php
new file mode 100644 (file)
index 0000000..28f69ea
--- /dev/null
@@ -0,0 +1,432 @@
+<?php
+/**
+ * StatusNet - the distributed open-source microblogging tool
+ * Copyright (C) 2011, StatusNet, Inc.
+ *
+ * Register a user by their email address
+ * 
+ * PHP version 5
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as published by
+ * the Free Software Foundation, either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU Affero General Public License for more details.
+ *
+ * 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  Email registration
+ * @package   StatusNet
+ * @author    Evan Prodromou <evan@status.net>
+ * @copyright 2011 StatusNet, Inc.
+ * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
+ * @link      http://status.net/
+ */
+
+if (!defined('STATUSNET')) {
+    // This check helps protect against security problems;
+    // your code file can't be executed directly from the web.
+    exit(1);
+}
+
+/**
+ * Email registration
+ *
+ * There are four cases where we're called:
+ *
+ * 1. GET, no arguments. Initial registration; ask for an email address.  
+ * 2. POST, email address argument. Initial registration; send an email to confirm.
+ * 3. GET, code argument. Confirming an invitation or a registration; look them up,
+ *    create the relevant user if possible, login as that user, and 
+ *    show a password-entry form.
+ * 4. POST, password argument. After confirmation, set the password for the new
+ *    user, and redirect to a registration complete action with some instructions.
+ *
+ * @category  Action
+ * @package   StatusNet
+ * @author    Evan Prodromou <evan@status.net>
+ * @copyright 2011 StatusNet, Inc.
+ * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
+ * @link      http://status.net/
+ */
+
+class EmailregisterAction extends Action
+{
+    const NEWEMAIL = 1;
+    const SETPASSWORD = 2;
+    const NEWREGISTER = 3;
+    const CONFIRMINVITE = 4;
+    const CONFIRMREGISTER = 5;
+
+    const CONFIRMTYPE = 'register';
+
+    protected $user;
+    protected $email;
+    protected $code;
+    protected $invitation;
+    protected $confirmation;
+    protected $password1;
+    protected $password2;
+    protected $state;
+    protected $error;
+
+    function prepare($argarray)
+    {
+        parent::prepare($argarray);
+
+        if ($this->isPost()) {
+
+            $this->checkSessionToken();
+
+            $this->email = $this->trimmed('email');
+
+            if (!empty($this->email)) {
+                $this->email = common_canonical_email($this->email);
+                $this->state = self::NEWEMAIL;
+            } else {
+                $this->state = self::SETPASSWORD;
+
+                $this->code = $this->trimmed('code');
+
+                if (empty($this->code)) {
+                    throw new ClientException(_('No confirmation code.'));
+                }
+
+                $this->invitation = Invitation::staticGet('code', $this->code);
+
+                if (!empty($this->invitation)) {
+                    $this->state = self::CONFIRMINVITE;
+                } else {
+                    $this->state = self::CONFIRMREGISTER;
+                    $this->confirmation = Confirm_address::staticGet('code', $this->code);
+
+                    if (empty($this->confirmation)) {
+                        throw new ClientException(_('No such confirmation code.'), 405);
+                    }
+                }
+
+                $this->password1 = $this->trimmed('password1');
+                $this->password2 = $this->trimmed('password2');
+                
+                $this->tos = $this->boolean('tos');
+            }
+        } else { // GET
+            $this->code = $this->trimmed('code');
+
+            if (empty($this->code)) {
+                $this->state = self::NEWREGISTER;
+            } else {
+                $this->invitation = Invitation::staticGet('code', $this->code);
+                if (!empty($this->invitation)) {
+                    $this->state = self::CONFIRMINVITE;
+                } else {
+                    $this->state = self::CONFIRMREGISTER;
+                    $this->confirmation = Confirm_address::staticGet('code', $this->code);
+
+                    if (empty($this->confirmation)) {
+                        throw new ClientException(_('No such confirmation code.'), 405);
+                    }
+                }
+            }
+        }
+
+        return true;
+    }
+
+    function title()
+    {
+        switch ($this->state) {
+        case self::NEWREGISTER:
+        case self::NEWEMAIL:
+            // TRANS: Title for registration page.
+            return _m('TITLE','Register');
+            break;
+        case self::SETPASSWORD:
+        case self::CONFIRMINVITE:
+        case self::CONFIRMREGISTER:
+            // TRANS: Title for page where to change password.
+            return _m('TITLE','Set password');
+            break;
+        }
+    }
+
+    /**
+     * Handler method
+     *
+     * @param array $argarray is ignored since it's now passed in in prepare()
+     *
+     * @return void
+     */
+
+    function handle($argarray=null)
+    {
+        switch ($this->state) {
+        case self::NEWREGISTER:
+            $this->showRegistrationForm();
+            break;
+        case self::NEWEMAIL:
+            $this->registerUser();
+            break;
+        case self::CONFIRMINVITE:
+            $this->confirmInvite();
+            break;
+        case self::CONFIRMREGISTER:
+            $this->confirmRegister();
+            break;
+        case self::SETPASSWORD:
+            $this->setPassword();
+            break;
+        }
+        return;
+    }
+
+    function showRegistrationForm()
+    {
+        $this->form = new EmailRegistrationForm($this, $this->email);
+        $this->showPage();
+    }
+
+    function registerUser()
+    {
+        $old = User::staticGet('email', $this->email);
+
+        if (!empty($old)) {
+            $this->error = sprintf(_('A user with that email address already exists. You can use the '.
+                                     '<a href="%s">password recovery</a> tool to recover a missing password.'),
+                                   common_local_url('recoverpassword'));
+            $this->showRegistrationForm();
+            break;
+        }
+
+        $valid = false;
+
+        if (Event::handle('StartValidateUserEmail', array(null, $this->email, &$valid))) {
+            $valid = Validate::email($this->email, common_config('email', 'check_domain'));
+            Event::handle('EndValidateUserEmail', array(null, $this->email, &$valid));
+        }
+
+        if (!$valid) {
+            $this->error = _('Not a valid email address.');
+            $this->showRegistrationForm();
+        }
+
+        $confirm = Confirm_address::getAddress($this->email, self::CONFIRMTYPE);
+
+        if (empty($confirm)) {
+            $confirm = Confirm_address::saveNew(null, $this->email, 'register');
+            $prompt = sprintf(_('An email was sent to %s to confirm that address. Check your email inbox for instructions.'),
+                              $this->email);
+        } else {
+            $prompt = sprintf(_('The address %s was already registered but not confirmed. The confirmation code was resent.'),
+                              $this->email);
+        }
+
+        $this->sendConfirmEmail($confirm);
+
+        $this->complete = $prompt;
+        
+        $this->showPage();
+    }
+
+    function confirmInvite()
+    {
+        $this->form = new ConfirmRegisterForm($this, $this->invitation->code);
+        $this->showPage();
+    }
+
+    function confirmRegister()
+    {
+        $this->form = new ConfirmRegisterForm($this, $this->confirmation->code);
+        $this->showPage();
+    }
+
+    function setPassword()
+    {
+        if (!$this->tos) {
+            $this->error = _('You must accept the terms of service and privacy policy to register.');
+            $this->form = new ConfirmRegisterForm($this, $this->code);
+            $this->showPage();
+            return;
+        }
+
+        if (!empty($this->invitation)) {
+            $email = $this->invitation->address;
+        } else if (!empty($this->confirmation)) {
+            $email = $this->confirmation->address;
+        } else {
+            throw new Exception('No confirmation thing.');
+        }
+
+        $nickname = $this->nicknameFromEmail($email);
+
+        $this->user = User::registerNew(array('nickname' => $nickname,
+                                              'email' => $email,
+                                              'email_confirmed' => true));
+
+        if (empty($this->user)) {
+            throw new Exception("Failed to register user.");
+        }
+
+        if (!empty($this->invitation)) {
+            $inviter = User::staticGet('id', $this->invitation->user_id);
+            if (!empty($inviter)) {
+                Subscription::start($inviter->getProfile(),
+                                    $user->getProfile());
+            }
+
+            $this->invitation->delete();
+        } else if (!empty($this->confirmation)) {
+            $this->confirmation->delete();
+        } else {
+            throw new Exception('No confirmation thing.');
+        }
+
+        common_redirect(common_local_url('doc', array('file' => 'registered')),
+                        303);
+    }
+
+    function sendConfirmEmail($confirm, $new)
+    {
+        $sitename = common_config('site', 'name');
+
+        $recipients = array($confirm->address);
+
+        $headers['From'] = mail_notify_from();
+        $headers['To'] = trim($confirm->address);
+        $headers['Subject'] = sprintf(_('Confirm your registration on %1$s'), $sitename);
+
+        $body = sprintf(_('Someone (probably you) has requested an account on %1$s using this email address.'.
+                          "\n".
+                          'To confirm the address, click the following URL or copy it into the address bar of your browser.'.
+                          "\n".
+                          '%2$s'.
+                          "\n".
+                          'If it was not you, you can safely ignore this message.'),
+                        $sitename,
+                        common_local_url('register', array('code' => $confirm->code)));
+
+        mail_send($recipients, $headers, $body);
+    }
+
+    function showContent()
+    {
+        if ($this->complete) {
+            $this->elementStart('p', 'success');
+            $this->raw($this->complete);
+            $this->elementEnd('p');
+        } else {
+            if ($this->error) {
+                $this->elementStart('p', 'error');
+                $this->raw($this->error);
+                $this->elementEnd('p');
+            }
+
+            if (!empty($this->form)) {
+                $this->form->show();
+            }
+        }
+    }
+
+    /**
+     * Return true if read only.
+     *
+     * MAY override
+     *
+     * @param array $args other arguments
+     *
+     * @return boolean is read only action?
+     */
+
+    function isReadOnly($args)
+    {
+        return false;
+    }
+}
+
+class EmailRegistrationForm extends Form
+{
+    protected $email;
+
+    function __construct($out, $email)
+    {
+        parent::__construct($out);
+        $this->email = $email;
+    }
+
+    function formData()
+    {
+        $this->out->element('p', 'instructions',
+                            _('Enter your email address to register for an account.'));
+                            
+        $this->out->elementStart('fieldset', array('id' => 'new_bookmark_data'));
+        $this->out->elementStart('ul', 'form_data');
+
+        $this->li();
+        $this->out->input('email',
+                          // TRANS: Field label on form for adding a new bookmark.
+                          _m('LABEL','E-mail address'),
+                          $this->email);
+        $this->unli();
+
+        $this->out->elementEnd('ul');
+        $this->out->elementEnd('fieldset');
+    }
+
+     function method()
+     {
+         return 'post';
+     }
+
+    /**
+     * Buttons for form actions
+     *
+     * Submit and cancel buttons (or whatever)
+     * Sub-classes should overload this to show their own buttons.
+     *
+     * @return void
+     */
+
+    function formActions()
+    {
+        // TRANS: Button text for action to save a new bookmark.
+        $this->out->submit('submit', _m('BUTTON', 'Register'));
+    }
+
+    /**
+     * ID of the form
+     *
+     * Should be unique on the page. Sub-classes should overload this
+     * to show their own IDs.
+     *
+     * @return int ID of the form
+     */
+
+    function id()
+    {
+        return 'form_email_registration';
+    }
+
+    /**
+     * Action of the form.
+     *
+     * URL to post to. Should be overloaded by subclasses to give
+     * somewhere to post to.
+     *
+     * @return string URL to post to
+     */
+
+    function action()
+    {
+        return common_local_url('register');
+    }
+
+    function formClass()
+    {
+        return 'form_email_registration';
+    }
+}