]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/register.php
Better use of Nickname validation functions
[quix0rs-gnu-social.git] / actions / register.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Register a new user account
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  Login
23  * @package   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @copyright 2008-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 /**
35  * An action for registering a new user account
36  *
37  * @category Login
38  * @package  StatusNet
39  * @author   Evan Prodromou <evan@status.net>
40  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
41  * @link     http://status.net/
42  */
43 class RegisterAction extends Action
44 {
45     /**
46      * Has there been an error?
47      */
48     var $error = null;
49
50     /**
51      * Have we registered?
52      */
53     var $registered = false;
54
55     /**
56      * Are we processing an invite?
57      */
58     var $invite = null;
59
60     /**
61      * Prepare page to run
62      *
63      *
64      * @param $args
65      * @return string title
66      */
67     function prepare($args)
68     {
69         parent::prepare($args);
70         $this->code = $this->trimmed('code');
71
72         if (empty($this->code)) {
73             common_ensure_session();
74             if (array_key_exists('invitecode', $_SESSION)) {
75                 $this->code = $_SESSION['invitecode'];
76             }
77         }
78
79         if (common_config('site', 'inviteonly') && empty($this->code)) {
80             // TRANS: Client error displayed when trying to register to an invite-only site without an invitation.
81             $this->clientError(_('Sorry, only invited people can register.'));
82             return false;
83         }
84
85         if (!empty($this->code)) {
86             $this->invite = Invitation::getKV('code', $this->code);
87             if (empty($this->invite)) {
88             // TRANS: Client error displayed when trying to register to an invite-only site without a valid invitation.
89                 $this->clientError(_('Sorry, invalid invitation code.'));
90                 return false;
91             }
92             // Store this in case we need it
93             common_ensure_session();
94             $_SESSION['invitecode'] = $this->code;
95         }
96
97         return true;
98     }
99
100     /**
101      * Title of the page
102      *
103      * @return string title
104      */
105     function title()
106     {
107         if ($this->registered) {
108             // TRANS: Title for registration page after a succesful registration.
109             return _('Registration successful');
110         } else {
111             // TRANS: Title for registration page.
112             return _m('TITLE','Register');
113         }
114     }
115
116     /**
117      * Handle input, produce output
118      *
119      * Switches on request method; either shows the form or handles its input.
120      *
121      * Checks if registration is closed and shows an error if so.
122      *
123      * @param array $args $_REQUEST data
124      *
125      * @return void
126      */
127     function handle($args)
128     {
129         parent::handle($args);
130
131         if (common_config('site', 'closed')) {
132             // TRANS: Client error displayed when trying to register to a closed site.
133             $this->clientError(_('Registration not allowed.'));
134         } else if (common_logged_in()) {
135             // TRANS: Client error displayed when trying to register while already logged in.
136             $this->clientError(_('Already logged in.'));
137         } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
138             $this->tryRegister();
139         } else {
140             $this->showForm();
141         }
142     }
143
144     function showScripts()
145     {
146         parent::showScripts();
147         $this->autofocus('nickname');
148     }
149
150     /**
151      * Try to register a user
152      *
153      * Validates the input and tries to save a new user and profile
154      * record. On success, shows an instructions page.
155      *
156      * @return void
157      */
158     function tryRegister()
159     {
160         if (Event::handle('StartRegistrationTry', array($this))) {
161             $token = $this->trimmed('token');
162             if (!$token || $token != common_session_token()) {
163                 // TRANS: Client error displayed when the session token does not match or is not given.
164                 $this->showForm(_('There was a problem with your session token. '.
165                                   'Try again, please.'));
166                 return;
167             }
168
169             $nickname = $this->trimmed('nickname');
170             $email    = $this->trimmed('email');
171             $fullname = $this->trimmed('fullname');
172             $homepage = $this->trimmed('homepage');
173             $bio      = $this->trimmed('bio');
174             $location = $this->trimmed('location');
175
176             // We don't trim these... whitespace is OK in a password!
177             $password = $this->arg('password');
178             $confirm  = $this->arg('confirm');
179
180             // invitation code, if any
181             $code = $this->trimmed('code');
182
183             if ($code) {
184                 $invite = Invitation::getKV($code);
185             }
186
187             if (common_config('site', 'inviteonly') && !($code && $invite)) {
188                 // TRANS: Client error displayed when trying to register to an invite-only site without an invitation.
189                 $this->clientError(_('Sorry, only invited people can register.'));
190                 return;
191             }
192
193             // Input scrubbing
194             try {
195                 $nickname = Nickname::normalize($nickname, true);
196             } catch (NicknameException $e) {
197                 $this->showForm($e->getMessage());
198                 return;
199             }
200             $email    = common_canonical_email($email);
201
202             if (!$this->boolean('license')) {
203                 // TRANS: Form validation error displayed when trying to register without agreeing to the site license.
204                 $this->showForm(_('You cannot register if you do not '.
205                                   'agree to the license.'));
206             } else if ($email && !Validate::email($email, common_config('email', 'check_domain'))) {
207                 // TRANS: Form validation error displayed when trying to register without a valid e-mail address.
208                 $this->showForm(_('Not a valid email address.'));
209             } else if ($this->emailExists($email)) {
210                 // TRANS: Form validation error displayed when trying to register with an already registered e-mail address.
211                 $this->showForm(_('Email address already exists.'));
212             } else if (!is_null($homepage) && (strlen($homepage) > 0) &&
213                        !common_valid_http_url($homepage)) {
214                 // TRANS: Form validation error displayed when trying to register with an invalid homepage URL.
215                 $this->showForm(_('Homepage is not a valid URL.'));
216             } else if (!is_null($fullname) && mb_strlen($fullname) > 255) {
217                 // TRANS: Form validation error displayed when trying to register with a too long full name.
218                 $this->showForm(_('Full name is too long (maximum 255 characters).'));
219             } else if (Profile::bioTooLong($bio)) {
220                 // TRANS: Form validation error on registration page when providing too long a bio text.
221                 // TRANS: %d is the maximum number of characters for bio; used for plural.
222                 $this->showForm(sprintf(_m('Bio is too long (maximum %d character).',
223                                            'Bio is too long (maximum %d characters).',
224                                            Profile::maxBio()),
225                                         Profile::maxBio()));
226             } else if (!is_null($location) && mb_strlen($location) > 255) {
227                 // TRANS: Form validation error displayed when trying to register with a too long location.
228                 $this->showForm(_('Location is too long (maximum 255 characters).'));
229             } else if (strlen($password) < 6) {
230                 // TRANS: Form validation error displayed when trying to register with too short a password.
231                 $this->showForm(_('Password must be 6 or more characters.'));
232             } else if ($password != $confirm) {
233                 // TRANS: Form validation error displayed when trying to register with non-matching passwords.
234                 $this->showForm(_('Passwords do not match.'));
235             } else if ($user = User::register(array('nickname' => $nickname,
236                                                     'password' => $password,
237                                                     'email' => $email,
238                                                     'fullname' => $fullname,
239                                                     'homepage' => $homepage,
240                                                     'bio' => $bio,
241                                                     'location' => $location,
242                                                     'code' => $code))) {
243                 if (!($user instanceof User)) {
244                     // TRANS: Form validation error displayed when trying to register with an invalid username or password.
245                     $this->showForm(_('Invalid username or password.'));
246                     return;
247                 }
248                 // success!
249                 if (!common_set_user($user)) {
250                     // TRANS: Server error displayed when saving fails during user registration.
251                     $this->serverError(_('Error setting user.'));
252                 }
253                 // this is a real login
254                 common_real_login(true);
255                 if ($this->boolean('rememberme')) {
256                     common_debug('Adding rememberme cookie for ' . $nickname);
257                     common_rememberme($user);
258                 }
259
260                 // Re-init language env in case it changed (not yet, but soon)
261                 common_init_language();
262
263                 Event::handle('EndRegistrationTry', array($this));
264
265                 $this->showSuccess();
266             } else {
267                 // TRANS: Form validation error displayed when trying to register with an invalid username or password.
268                 $this->showForm(_('Invalid username or password.'));
269             }
270         }
271     }
272
273     /**
274      * Does the given email address already exist?
275      *
276      * Checks a canonical email address against the database.
277      *
278      * @param string $email email address to check
279      *
280      * @return boolean true if the address already exists
281      */
282     function emailExists($email)
283     {
284         $email = common_canonical_email($email);
285         if (!$email || strlen($email) == 0) {
286             return false;
287         }
288         $user = User::getKV('email', $email);
289         return is_object($user);
290     }
291
292     // overrrided to add entry-title class
293     function showPageTitle() {
294         if (Event::handle('StartShowPageTitle', array($this))) {
295             $this->element('h1', array('class' => 'entry-title'), $this->title());
296         }
297     }
298
299     // overrided to add hentry, and content-inner class
300     function showContentBlock()
301     {
302         $this->elementStart('div', array('id' => 'content', 'class' => 'hentry'));
303         $this->showPageTitle();
304         $this->showPageNoticeBlock();
305         $this->elementStart('div', array('id' => 'content_inner',
306                                          'class' => 'entry-content'));
307         // show the actual content (forms, lists, whatever)
308         $this->showContent();
309         $this->elementEnd('div');
310         $this->elementEnd('div');
311     }
312
313     /**
314      * Instructions or a notice for the page
315      *
316      * Shows the error, if any, or instructions for registration.
317      *
318      * @return void
319      */
320     function showPageNotice()
321     {
322         if ($this->registered) {
323             return;
324         } else if ($this->error) {
325             $this->element('p', 'error', $this->error);
326         } else {
327             $instr =
328               // TRANS: Page notice on registration page.
329               common_markup_to_html(_('With this form you can create '.
330                                       'a new account. ' .
331                                       'You can then post notices and '.
332                                       'link up to friends and colleagues.'));
333
334             $this->elementStart('div', 'instructions');
335             $this->raw($instr);
336             $this->elementEnd('div');
337         }
338     }
339
340     /**
341      * Wrapper for showing a page
342      *
343      * Stores an error and shows the page
344      *
345      * @param string $error Error, if any
346      *
347      * @return void
348      */
349     function showForm($error=null)
350     {
351         $this->error = $error;
352         $this->showPage();
353     }
354
355     /**
356      * Show the page content
357      *
358      * Either shows the registration form or, if registration was successful,
359      * instructions for using the site.
360      *
361      * @return void
362      */
363     function showContent()
364     {
365         if ($this->registered) {
366             $this->showSuccessContent();
367         } else {
368             $this->showFormContent();
369         }
370     }
371
372     /**
373      * Show the registration form
374      *
375      * @return void
376      */
377     function showFormContent()
378     {
379         $code = $this->trimmed('code');
380
381         $invite = null;
382
383         if ($code) {
384             $invite = Invitation::getKV($code);
385         }
386
387         if (common_config('site', 'inviteonly') && !($code && $invite)) {
388             // TRANS: Client error displayed when trying to register to an invite-only site without an invitation.
389             $this->clientError(_('Sorry, only invited people can register.'));
390             return;
391         }
392
393         $this->elementStart('form', array('method' => 'post',
394                                           'id' => 'form_register',
395                                           'class' => 'form_settings',
396                                           'action' => common_local_url('register')));
397         $this->elementStart('fieldset');
398         // TRANS: Fieldset legend on accout registration page.
399         $this->element('legend', null, 'Account settings');
400         $this->hidden('token', common_session_token());
401
402         if ($this->code) {
403             $this->hidden('code', $this->code);
404         }
405
406         $this->elementStart('ul', 'form_data');
407         if (Event::handle('StartRegistrationFormData', array($this))) {
408             $this->elementStart('li');
409             // TRANS: Field label on account registration page.
410             $this->input('nickname', _('Nickname'), $this->trimmed('nickname'),
411                          // TRANS: Field title on account registration page.
412                          _('1-64 lowercase letters or numbers, no punctuation or spaces.'));
413             $this->elementEnd('li');
414             $this->elementStart('li');
415             // TRANS: Field label on account registration page.
416             $this->password('password', _('Password'),
417                             // TRANS: Field title on account registration page.
418                             _('6 or more characters.'));
419             $this->elementEnd('li');
420             $this->elementStart('li');
421             // TRANS: Field label on account registration page. In this field the password has to be entered a second time.
422             $this->password('confirm', _m('PASSWORD','Confirm'),
423                          // TRANS: Field title on account registration page.
424                          _('Same as password above.'));
425             $this->elementEnd('li');
426             $this->elementStart('li');
427             if ($this->invite && $this->invite->address_type == 'email') {
428                 // TRANS: Field label on account registration page.
429                 $this->input('email', _m('LABEL','Email'), $this->invite->address,
430                              // TRANS: Field title on account registration page.
431                              _('Used only for updates, announcements, '.
432                                'and password recovery.'));
433             } else {
434                 // TRANS: Field label on account registration page.
435                 $this->input('email', _m('LABEL','Email'), $this->trimmed('email'),
436                              // TRANS: Field title on account registration page.
437                              _('Used only for updates, announcements, '.
438                                'and password recovery.'));
439             }
440             $this->elementEnd('li');
441             $this->elementStart('li');
442             // TRANS: Field label on account registration page.
443             $this->input('fullname', _('Full name'),
444                          $this->trimmed('fullname'),
445                      // TRANS: Field title on account registration page.
446                      _('Longer name, preferably your "real" name.'));
447             $this->elementEnd('li');
448             $this->elementStart('li');
449             // TRANS: Field label on account registration page.
450             $this->input('homepage', _('Homepage'),
451                          $this->trimmed('homepage'),
452                          // TRANS: Field title on account registration page.
453                          _('URL of your homepage, blog, '.
454                            'or profile on another site.'));
455             $this->elementEnd('li');
456             $this->elementStart('li');
457             $maxBio = Profile::maxBio();
458             if ($maxBio > 0) {
459                 // TRANS: Text area title in form for account registration. Plural
460                 // TRANS: is decided by the number of characters available for the
461                 // TRANS: biography (%d).
462                 $bioInstr = sprintf(_m('Describe yourself and your interests in %d character.',
463                                        'Describe yourself and your interests in %d characters.',
464                                        $maxBio),
465                                     $maxBio);
466             } else {
467                 // TRANS: Text area title on account registration page.
468                 $bioInstr = _('Describe yourself and your interests.');
469             }
470             // TRANS: Text area label on account registration page.
471             $this->textarea('bio', _('Bio'),
472                             $this->trimmed('bio'),
473                             $bioInstr);
474             $this->elementEnd('li');
475             $this->elementStart('li');
476             // TRANS: Field label on account registration page.
477             $this->input('location', _('Location'),
478                          $this->trimmed('location'),
479                          // TRANS: Field title on account registration page.
480                          _('Where you are, like "City, '.
481                            'State (or Region), Country".'));
482             $this->elementEnd('li');
483             Event::handle('EndRegistrationFormData', array($this));
484             $this->elementStart('li', array('id' => 'settings_rememberme'));
485             // TRANS: Checkbox label on account registration page.
486             $this->checkbox('rememberme', _('Remember me'),
487                             $this->boolean('rememberme'),
488                             // TRANS: Checkbox title on account registration page.
489                             _('Automatically login in the future; '.
490                               'not for shared computers!'));
491             $this->elementEnd('li');
492             $attrs = array('type' => 'checkbox',
493                            'id' => 'license',
494                            'class' => 'checkbox',
495                            'name' => 'license',
496                            'value' => 'true');
497             if ($this->boolean('license')) {
498                 $attrs['checked'] = 'checked';
499             }
500             $this->elementStart('li');
501             $this->element('input', $attrs);
502             $this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
503             $this->raw($this->licenseCheckbox());
504             $this->elementEnd('label');
505             $this->elementEnd('li');
506         }
507         $this->elementEnd('ul');
508         // TRANS: Button text to register a user on account registration page.
509         $this->submit('submit', _m('BUTTON','Register'));
510         $this->elementEnd('fieldset');
511         $this->elementEnd('form');
512     }
513
514     function licenseCheckbox()
515     {
516         $out = '';
517         switch (common_config('license', 'type')) {
518         case 'private':
519             $out .= htmlspecialchars(sprintf(
520                 // TRANS: Copyright checkbox label in registration dialog, for private sites.
521                 // TRANS: %1$s is the StatusNet sitename.
522                 _('I understand that content and data of %1$s are private and confidential.'),
523                 common_config('site', 'name')));
524             // fall through
525         case 'allrightsreserved':
526             if ($out != '') {
527                 $out .= ' ';
528             }
529             if (common_config('license', 'owner')) {
530                 $out .= htmlspecialchars(sprintf(
531                     // TRANS: Copyright checkbox label in registration dialog, for all rights reserved with a specified copyright owner.
532                     // TRANS: %1$s is the license owner.
533                     _('My text and files are copyright by %1$s.'),
534                     common_config('license', 'owner')));
535             } else {
536                 // TRANS: Copyright checkbox label in registration dialog, for all rights reserved with ownership left to contributors.
537                 $out .= htmlspecialchars(_('My text and files remain under my own copyright.'));
538             }
539             // TRANS: Copyright checkbox label in registration dialog, for all rights reserved.
540             $out .= ' ' . _('All rights reserved.');
541             break;
542         case 'cc': // fall through
543         default:
544             // TRANS: Copyright checkbox label in registration dialog, for Creative Commons-style licenses.
545             $message = _('My text and files are available under %s ' .
546                          'except this private data: password, ' .
547                          'email address, IM address, and phone number.');
548             $link = '<a href="' .
549                     htmlspecialchars(common_config('license', 'url')) .
550                     '">' .
551                     htmlspecialchars(common_config('license', 'title')) .
552                     '</a>';
553             $out .= sprintf(htmlspecialchars($message), $link);
554         }
555         return $out;
556     }
557
558     /**
559      * Show some information about registering for the site
560      *
561      * Save the registration flag, run showPage
562      *
563      * @return void
564      */
565     function showSuccess()
566     {
567         $this->registered = true;
568         $this->showPage();
569     }
570
571     /**
572      * Show some information about registering for the site
573      *
574      * Gives some information and options for new registrees.
575      *
576      * @return void
577      */
578     function showSuccessContent()
579     {
580         if (Event::handle('StartRegisterSuccess', array($this))) {
581             $nickname = $this->arg('nickname');
582
583             $profileurl = common_local_url('showstream',
584                                            array('nickname' => $nickname));
585
586             $this->elementStart('div', 'success');
587             // TRANS: Text displayed after successful account registration.
588             // TRANS: %1$s is the registered nickname, %2$s is the profile URL.
589             // TRANS: This message contains Markdown links in the form [link text](link)
590             // TRANS: and variables in the form %%%%variable%%%%. Please mind the syntax.
591             $instr = sprintf(_('Congratulations, %1$s! And welcome to %%%%site.name%%%%. '.
592                                'From here, you may want to...'. "\n\n" .
593                                '* Go to [your profile](%2$s) '.
594                                'and post your first message.' .  "\n" .
595                                '* Add a [Jabber/GTalk address]'.
596                                '(%%%%action.imsettings%%%%) '.
597                                'so you can send notices '.
598                                'through instant messages.' . "\n" .
599                                '* [Search for people](%%%%action.peoplesearch%%%%) '.
600                                'that you may know or '.
601                                'that share your interests. ' . "\n" .
602                                '* Update your [profile settings]'.
603                                '(%%%%action.profilesettings%%%%)'.
604                                ' to tell others more about you. ' . "\n" .
605                                '* Read over the [online docs](%%%%doc.help%%%%)'.
606                                ' for features you may have missed. ' . "\n\n" .
607                                'Thanks for signing up and we hope '.
608                                'you enjoy using this service.'),
609                              $nickname, $profileurl);
610
611             $this->raw(common_markup_to_html($instr));
612
613             $have_email = $this->trimmed('email');
614             if ($have_email) {
615                 // TRANS: Instruction text on how to deal with the e-mail address confirmation e-mail.
616                 $emailinstr = _('(You should receive a message by email '.
617                                 'momentarily, with ' .
618                                 'instructions on how to confirm '.
619                                 'your email address.)');
620                 $this->raw(common_markup_to_html($emailinstr));
621             }
622             $this->elementEnd('div');
623
624             Event::handle('EndRegisterSuccess', array($this));
625         }
626     }
627
628     /**
629      * Show the login group nav menu
630      *
631      * @return void
632      */
633     function showLocalNav()
634     {
635         if (common_logged_in()) {
636             parent::showLocalNav();
637         } else {
638             $nav = new LoginGroupNav($this);
639             $nav->show();
640         }
641     }
642
643     /**
644      * Show a bit of login context
645      *
646      * @return nothing
647      */
648     function showProfileBlock()
649     {
650         if (common_logged_in()) {
651             parent::showProfileBlock();
652         }
653     }
654 }