]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/recoverpassword.php
updateKeys -> updateWithKeys (w/ functionality)
[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($args)
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             $result = $user->updateWithKeys($orig);
109             if (!$result) {
110                 common_log_db_error($user, 'UPDATE', __FILE__);
111                 // TRANS: Server error displayed when updating a user's e-mail address in the database fails while recovering a password.
112                 $this->serverError(_('Could not update user with confirmed email address.'));
113             }
114         }
115
116         // Success!
117
118         $this->setTempUser($user);
119         $this->showPasswordForm();
120     }
121
122     function setTempUser(&$user)
123     {
124         common_ensure_session();
125         $_SESSION['tempuser'] = $user->id;
126     }
127
128     function getTempUser()
129     {
130         common_ensure_session();
131         $user_id = $_SESSION['tempuser'];
132         if ($user_id) {
133             $user = User::getKV($user_id);
134         }
135         return $user;
136     }
137
138     function clearTempUser()
139     {
140         common_ensure_session();
141         unset($_SESSION['tempuser']);
142     }
143
144     function showPageNotice()
145     {
146         if ($this->msg) {
147             $this->element('div', ($this->success) ? 'success' : 'error', $this->msg);
148         } else {
149             $this->elementStart('div', 'instructions');
150             if ($this->mode == 'recover') {
151                 $this->element('p', null,
152                                // TRANS: Page notice for password recovery page.
153                                _('If you have forgotten or lost your' .
154                                  ' password, you can get a new one sent to' .
155                                  ' the email address you have stored' .
156                                  ' in your account.'));
157             } else if ($this->mode == 'reset') {
158                 $this->element('p', null,
159                                // TRANS: Page notice for password change page.
160                                _('You have been identified. Enter a' .
161                                  ' new password below.'));
162             }
163             $this->elementEnd('div');
164         }
165     }
166
167     function showForm($msg=null)
168     {
169         $this->msg = $msg;
170         $this->mode = 'recover';
171         $this->showPage();
172     }
173
174     function showContent()
175     {
176         if ($this->mode == 'recover') {
177             $this->showRecoverForm();
178         } else if ($this->mode == 'reset') {
179             $this->showResetForm();
180         }
181     }
182
183     function showRecoverForm()
184     {
185         $this->elementStart('form', array('method' => 'post',
186                                            'id' => 'form_password_recover',
187                                            'class' => 'form_settings',
188                                            'action' => common_local_url('recoverpassword')));
189         $this->elementStart('fieldset');
190         // TRANS: Fieldset legend for password recovery page.
191         $this->element('legend', null, _('Password recovery'));
192         $this->elementStart('ul', 'form_data');
193         $this->elementStart('li');
194         // TRANS: Field label on password recovery page.
195         $this->input('nicknameoremail', _('Nickname or email address'),
196                      $this->trimmed('nicknameoremail'),
197                      // TRANS: Title for field label on password recovery page.
198                      _('Your nickname on this server, ' .
199                         'or your registered email address.'));
200         $this->elementEnd('li');
201         $this->elementEnd('ul');
202         $this->element('input', array('name' => 'recover',
203                                       'type' => 'hidden',
204                                       // TRANS: Field label on password recovery page.
205                                       'value' => _('Recover')));
206         // TRANS: Button text on password recovery page.
207         $this->submit('recover', _m('BUTTON','Recover'));
208         $this->elementEnd('fieldset');
209         $this->elementEnd('form');
210     }
211
212     function title()
213     {
214         switch ($this->mode) {
215          // TRANS: Title for password recovery page in password reset mode.
216          case 'reset': return _('Reset password');
217          // TRANS: Title for password recovery page in password recover mode.
218          case 'recover': return _('Recover password');
219          // TRANS: Title for password recovery page in email sent mode.
220          case 'sent': return _('Password recovery requested');
221          // TRANS: Title for password recovery page in password saved mode.
222          case 'saved': return _('Password saved');
223          default:
224             // TRANS: Title for password recovery page when an unknown action has been specified.
225             return _('Unknown action');
226         }
227     }
228
229     function showPasswordForm($msg=null)
230     {
231         $this->msg = $msg;
232         $this->mode = 'reset';
233         $this->showPage();
234     }
235
236     function showResetForm()
237     {
238         $this->elementStart('form', array('method' => 'post',
239                                            'id' => 'form_password_change',
240                                            'class' => 'form_settings',
241                                            'action' => common_local_url('recoverpassword')));
242         $this->elementStart('fieldset');
243          // TRANS: Fieldset legend for password reset form.
244         $this->element('legend', null, _('Password change'));
245         $this->hidden('token', common_session_token());
246         $this->elementStart('ul', 'form_data');
247         $this->elementStart('li');
248          // TRANS: Field label for password reset form.
249         $this->password('newpassword', _('New password'),
250                         // TRANS: Title for field label for password reset form.
251                         _('6 or more characters, and do not forget it!'));
252         $this->elementEnd('li');
253         $this->elementStart('li');
254          // TRANS: Field label for password reset form where the password has to be typed again.
255         $this->password('confirm', _('Confirm'),
256                         // TRANS: Title for field label for password reset form where the password has to be typed again.
257                         _('Same as password above.'));
258         $this->elementEnd('li');
259         $this->elementEnd('ul');
260          // TRANS: Button text for password reset form.
261         $this->submit('reset', _m('BUTTON','Reset'));
262         $this->elementEnd('fieldset');
263         $this->elementEnd('form');
264     }
265
266     function recoverPassword()
267     {
268         $nore = $this->trimmed('nicknameoremail');
269
270         if (!$nore) {
271             // TRANS: Form instructions for password recovery form.
272             $this->showForm(_('Enter a nickname or email address.'));
273             return;
274         }
275
276         try {
277             User::recoverPassword($nore);
278             $this->mode = 'sent';
279             // TRANS: User notification after an e-mail with instructions was sent from the password recovery form.
280             $this->msg = _('Instructions for recovering your password ' .
281                            'have been sent to the email address registered to your ' .
282                            'account.');
283             $this->success = true;
284         } catch (Exception $e) {
285             $this->success = false;
286             $this->msg = $e->getMessage();
287         }
288         $this->showPage();
289     }
290
291     function resetPassword()
292     {
293         // CSRF protection
294         $token = $this->trimmed('token');
295         if (!$token || $token != common_session_token()) {
296             // TRANS: Form validation error message.
297             $this->showForm(_('There was a problem with your session token. Try again, please.'));
298             return;
299         }
300
301         $user = $this->getTempUser();
302
303         if (!$user) {
304             // TRANS: Client error displayed when trying to reset as password without providing a user.
305             $this->clientError(_('Unexpected password reset.'));
306         }
307
308         $newpassword = $this->trimmed('newpassword');
309         $confirm = $this->trimmed('confirm');
310
311         if (!$newpassword || strlen($newpassword) < 6) {
312             // TRANS: Reset password form validation error message.
313             $this->showPasswordForm(_('Password must be 6 characters or more.'));
314             return;
315         }
316         if ($newpassword != $confirm) {
317             // TRANS: Reset password form validation error message.
318             $this->showPasswordForm(_('Password and confirmation do not match.'));
319             return;
320         }
321
322         // OK, we're ready to go
323
324         $original = clone($user);
325
326         $user->password = common_munge_password($newpassword, $user->id);
327
328         if (!$user->update($original)) {
329             common_log_db_error($user, 'UPDATE', __FILE__);
330             // TRANS: Reset password form validation error message.
331             $this->serverError(_('Cannot save new password.'));
332         }
333
334         $this->clearTempUser();
335
336         if (!common_set_user($user->nickname)) {
337             // TRANS: Server error displayed when something does wrong with the user object during password reset.
338             $this->serverError(_('Error setting user.'));
339         }
340
341         common_real_login(true);
342
343         $this->mode = 'saved';
344         // TRANS: Success message for user after password reset.
345         $this->msg = _('New password successfully saved. ' .
346                        'You are now logged in.');
347         $this->success = true;
348         $this->showPage();
349     }
350
351     /**
352      * A local menu
353      *
354      * Shows different login/register actions.
355      *
356      * @return void
357      */
358
359     function showLocalNav()
360     {
361         $nav = new LoginGroupNav($this);
362         $nav->show();
363     }
364 }