Merge remote-tracking branch 'upstream/master' into social-master
[quix0rs-gnu-social.git] / actions / recoverpassword.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 // You have 24 hours to claim your password
23
24 define('MAX_RECOVERY_TIME', 24 * 60 * 60);
25
26 class RecoverpasswordAction extends Action
27 {
28     var $mode = null;
29     var $msg = null;
30     var $success = null;
31
32     function handle(array $args=array())
33     {
34         parent::handle($args);
35         if (common_logged_in()) {
36             // TRANS: Client error displayed trying to recover password while already logged in.
37             $this->clientError(_('You are already logged in!'));
38         } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
39             if ($this->arg('recover')) {
40                 $this->recoverPassword();
41             } else if ($this->arg('reset')) {
42                 $this->resetPassword();
43             } else {
44                 // TRANS: Client error displayed when unexpected data is posted in the password recovery form.
45                 $this->clientError(_('Unexpected form submission.'));
46             }
47         } else {
48             if ($this->trimmed('code')) {
49                 $this->checkCode();
50             } else {
51                 $this->showForm();
52             }
53         }
54     }
55
56     function checkCode()
57     {
58         $code = $this->trimmed('code');
59         $confirm = Confirm_address::getKV('code', $code);
60
61         if (!$confirm) {
62             // TRANS: Client error displayed when password recovery code is not correct.
63             $this->clientError(_('No such recovery code.'));
64         }
65         if ($confirm->address_type != 'recover') {
66             // TRANS: Client error displayed when no proper password recovery code was submitted.
67             $this->clientError(_('Not a recovery code.'));
68         }
69
70         $user = User::getKV($confirm->user_id);
71
72         if (!$user) {
73             // TRANS: Server error displayed trying to recover password without providing a user.
74             $this->serverError(_('Recovery code for unknown user.'));
75         }
76
77         $touched = strtotime($confirm->modified);
78         $email = $confirm->address;
79
80         // Burn this code
81
82         $result = $confirm->delete();
83
84         if (!$result) {
85             common_log_db_error($confirm, 'DELETE', __FILE__);
86             // TRANS: Server error displayed removing a password recovery code from the database.
87             $this->serverError(_('Error with confirmation code.'));
88         }
89
90         // These should be reaped, but for now we just check mod time
91         // Note: it's still deleted; let's avoid a second attempt!
92
93         if ((time() - $touched) > MAX_RECOVERY_TIME) {
94             common_log(LOG_WARNING,
95                        'Attempted redemption on recovery code ' .
96                        'that is ' . $touched . ' seconds old. ');
97             // TRANS: Client error displayed trying to recover password with too old a recovery code.
98             $this->clientError(_('This confirmation code is too old. ' .
99                                    'Please start again.'));
100         }
101
102         // If we used an outstanding confirmation to send the email,
103         // it's been confirmed at this point.
104
105         if (!$user->email) {
106             $orig = clone($user);
107             $user->email = $email;
108             // Throws exception on failure.
109             $user->updateWithKeys($orig);
110         }
111
112         // Success!
113
114         $this->setTempUser($user);
115         $this->showPasswordForm();
116     }
117
118     function setTempUser(&$user)
119     {
120         common_ensure_session();
121         $_SESSION['tempuser'] = $user->id;
122     }
123
124     function getTempUser()
125     {
126         common_ensure_session();
127         $user_id = $_SESSION['tempuser'];
128         if ($user_id) {
129             $user = User::getKV($user_id);
130         }
131         return $user;
132     }
133
134     function clearTempUser()
135     {
136         common_ensure_session();
137         unset($_SESSION['tempuser']);
138     }
139
140     function showPageNotice()
141     {
142         if ($this->msg) {
143             $this->element('div', ($this->success) ? 'success' : 'error', $this->msg);
144         } else {
145             $this->elementStart('div', 'instructions');
146             if ($this->mode == 'recover') {
147                 $this->element('p', null,
148                                // TRANS: Page notice for password recovery page.
149                                _('If you have forgotten or lost your' .
150                                  ' password, you can get a new one sent to' .
151                                  ' the email address you have stored' .
152                                  ' in your account.'));
153             } else if ($this->mode == 'reset') {
154                 $this->element('p', null,
155                                // TRANS: Page notice for password change page.
156                                _('You have been identified. Enter a' .
157                                  ' new password below.'));
158             }
159             $this->elementEnd('div');
160         }
161     }
162
163     function showForm($msg=null)
164     {
165         $this->msg = $msg;
166         $this->mode = 'recover';
167         $this->showPage();
168     }
169
170     function showContent()
171     {
172         if ($this->mode == 'recover') {
173             $this->showRecoverForm();
174         } else if ($this->mode == 'reset') {
175             $this->showResetForm();
176         }
177     }
178
179     function showRecoverForm()
180     {
181         $this->elementStart('form', array('method' => 'post',
182                                            'id' => 'form_password_recover',
183                                            'class' => 'form_settings',
184                                            'action' => common_local_url('recoverpassword')));
185         $this->elementStart('fieldset');
186         // TRANS: Fieldset legend for password recovery page.
187         $this->element('legend', null, _('Password recovery'));
188         $this->elementStart('ul', 'form_data');
189         $this->elementStart('li');
190         // TRANS: Field label on password recovery page.
191         $this->input('nicknameoremail', _('Nickname or email address'),
192                      $this->trimmed('nicknameoremail'),
193                      // TRANS: Title for field label on password recovery page.
194                      _('Your nickname on this server, ' .
195                         'or your registered email address.'));
196         $this->elementEnd('li');
197         $this->elementEnd('ul');
198         $this->element('input', array('name' => 'recover',
199                                       'type' => 'hidden',
200                                       // TRANS: Field label on password recovery page.
201                                       'value' => _('Recover')));
202         // TRANS: Button text on password recovery page.
203         $this->submit('recover', _m('BUTTON','Recover'));
204         $this->elementEnd('fieldset');
205         $this->elementEnd('form');
206     }
207
208     function title()
209     {
210         switch ($this->mode) {
211          // TRANS: Title for password recovery page in password reset mode.
212          case 'reset': return _('Reset password');
213          // TRANS: Title for password recovery page in password recover mode.
214          case 'recover': return _('Recover password');
215          // TRANS: Title for password recovery page in email sent mode.
216          case 'sent': return _('Password recovery requested');
217          // TRANS: Title for password recovery page in password saved mode.
218          case 'saved': return _('Password saved');
219          default:
220             // TRANS: Title for password recovery page when an unknown action has been specified.
221             return _('Unknown action');
222         }
223     }
224
225     function showPasswordForm($msg=null)
226     {
227         $this->msg = $msg;
228         $this->mode = 'reset';
229         $this->showPage();
230     }
231
232     function showResetForm()
233     {
234         $this->elementStart('form', array('method' => 'post',
235                                            'id' => 'form_password_change',
236                                            'class' => 'form_settings',
237                                            'action' => common_local_url('recoverpassword')));
238         $this->elementStart('fieldset');
239          // TRANS: Fieldset legend for password reset form.
240         $this->element('legend', null, _('Password change'));
241         $this->hidden('token', common_session_token());
242         $this->elementStart('ul', 'form_data');
243         $this->elementStart('li');
244          // TRANS: Field label for password reset form.
245         $this->password('newpassword', _('New password'),
246                         // TRANS: Title for field label for password reset form.
247                         _('6 or more characters, and do not forget it!'));
248         $this->elementEnd('li');
249         $this->elementStart('li');
250          // TRANS: Field label for password reset form where the password has to be typed again.
251         $this->password('confirm', _('Confirm'),
252                         // TRANS: Title for field label for password reset form where the password has to be typed again.
253                         _('Same as password above.'));
254         $this->elementEnd('li');
255         $this->elementEnd('ul');
256          // TRANS: Button text for password reset form.
257         $this->submit('reset', _m('BUTTON','Reset'));
258         $this->elementEnd('fieldset');
259         $this->elementEnd('form');
260     }
261
262     function recoverPassword()
263     {
264         $nore = $this->trimmed('nicknameoremail');
265
266         if (!$nore) {
267             // TRANS: Form instructions for password recovery form.
268             $this->showForm(_('Enter a nickname or email address.'));
269             return;
270         }
271
272         try {
273             User::recoverPassword($nore);
274             $this->mode = 'sent';
275             if (common_is_email($nore) && common_config('site', 'fakeaddressrecovery')) {
276                 // TRANS: User notification when recovering password by giving email address,
277                 //        regardless if the mail was sent or not (to hide registered email status).
278                 $this->msg = _('If the email address you provided was found in the database, a recovery mail with instructions has been sent there.');
279             } else {
280                 // TRANS: User notification after an e-mail with instructions was sent from the password recovery form.
281                 $this->msg = _('Instructions for recovering your password ' .
282                                'have been sent to the email address registered to your ' .
283                                'account.');
284             }
285             $this->success = true;
286         } catch (Exception $e) {
287             $this->success = false;
288             $this->msg = $e->getMessage();
289         }
290         $this->showPage();
291     }
292
293     function resetPassword()
294     {
295         // CSRF protection
296         $token = $this->trimmed('token');
297         if (!$token || $token != common_session_token()) {
298             // TRANS: Form validation error message.
299             $this->showForm(_('There was a problem with your session token. Try again, please.'));
300             return;
301         }
302
303         $user = $this->getTempUser();
304
305         if (!$user) {
306             // TRANS: Client error displayed when trying to reset as password without providing a user.
307             $this->clientError(_('Unexpected password reset.'));
308         }
309
310         $newpassword = $this->trimmed('newpassword');
311         $confirm = $this->trimmed('confirm');
312
313         if (!$newpassword || strlen($newpassword) < 6) {
314             // TRANS: Reset password form validation error message.
315             $this->showPasswordForm(_('Password must be 6 characters or more.'));
316             return;
317         }
318         if ($newpassword != $confirm) {
319             // TRANS: Reset password form validation error message.
320             $this->showPasswordForm(_('Password and confirmation do not match.'));
321             return;
322         }
323
324         // OK, we're ready to go
325         $user->setPassword($newpassword);
326
327         $this->clearTempUser();
328
329         if (!common_set_user($user->nickname)) {
330             // TRANS: Server error displayed when something does wrong with the user object during password reset.
331             $this->serverError(_('Error setting user.'));
332         }
333
334         common_real_login(true);
335
336         $this->mode = 'saved';
337         // TRANS: Success message for user after password reset.
338         $this->msg = _('New password successfully saved. ' .
339                        'You are now logged in.');
340         $this->success = true;
341         $this->showPage();
342     }
343
344     /**
345      * A local menu
346      *
347      * Shows different login/register actions.
348      *
349      * @return void
350      */
351
352     function showLocalNav()
353     {
354         $nav = new LoginGroupNav($this);
355         $nav->show();
356     }
357 }