]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/recoverpassword.php
Merge branch '1.0.x' of git://gitorious.org/statusnet/mainline
[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             return;
39         } else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
40             if ($this->arg('recover')) {
41                 $this->recoverPassword();
42             } else if ($this->arg('reset')) {
43                 $this->resetPassword();
44             } else {
45                 // TRANS: Client error displayed when unexpected data is posted in the password recovery form.
46                 $this->clientError(_('Unexpected form submission.'));
47             }
48         } else {
49             if ($this->trimmed('code')) {
50                 $this->checkCode();
51             } else {
52                 $this->showForm();
53             }
54         }
55     }
56
57     function checkCode()
58     {
59         $code = $this->trimmed('code');
60         $confirm = Confirm_address::staticGet('code', $code);
61
62         if (!$confirm) {
63             // TRANS: Client error displayed when password recovery code is not correct.
64             $this->clientError(_('No such recovery code.'));
65             return;
66         }
67         if ($confirm->address_type != 'recover') {
68             // TRANS: Client error displayed when no proper password recovery code was submitted.
69             $this->clientError(_('Not a recovery code.'));
70             return;
71         }
72
73         $user = User::staticGet($confirm->user_id);
74
75         if (!$user) {
76             // TRANS: Server error displayed trying to recover password without providing a user.
77             $this->serverError(_('Recovery code for unknown user.'));
78             return;
79         }
80
81         $touched = strtotime($confirm->modified);
82         $email = $confirm->address;
83
84         // Burn this code
85
86         $result = $confirm->delete();
87
88         if (!$result) {
89             common_log_db_error($confirm, 'DELETE', __FILE__);
90             // TRANS: Server error displayed removing a password recovery code from the database.
91             $this->serverError(_('Error with confirmation code.'));
92             return;
93         }
94
95         // These should be reaped, but for now we just check mod time
96         // Note: it's still deleted; let's avoid a second attempt!
97
98         if ((time() - $touched) > MAX_RECOVERY_TIME) {
99             common_log(LOG_WARNING,
100                        'Attempted redemption on recovery code ' .
101                        'that is ' . $touched . ' seconds old. ');
102             // TRANS: Client error displayed trying to recover password with too old a recovery code.
103             $this->clientError(_('This confirmation code is too old. ' .
104                                    'Please start again.'));
105             return;
106         }
107
108         // If we used an outstanding confirmation to send the email,
109         // it's been confirmed at this point.
110
111         if (!$user->email) {
112             $orig = clone($user);
113             $user->email = $email;
114             $result = $user->updateKeys($orig);
115             if (!$result) {
116                 common_log_db_error($user, 'UPDATE', __FILE__);
117                 // TRANS: Server error displayed when updating a user's e-mail address in the database fails while recovering a password.
118                 $this->serverError(_('Could not update user with confirmed email address.'));
119                 return;
120             }
121         }
122
123         // Success!
124
125         $this->setTempUser($user);
126         $this->showPasswordForm();
127     }
128
129     function setTempUser(&$user)
130     {
131         common_ensure_session();
132         $_SESSION['tempuser'] = $user->id;
133     }
134
135     function getTempUser()
136     {
137         common_ensure_session();
138         $user_id = $_SESSION['tempuser'];
139         if ($user_id) {
140             $user = User::staticGet($user_id);
141         }
142         return $user;
143     }
144
145     function clearTempUser()
146     {
147         common_ensure_session();
148         unset($_SESSION['tempuser']);
149     }
150
151     function showPageNotice()
152     {
153         if ($this->msg) {
154             $this->element('div', ($this->success) ? 'success' : 'error', $this->msg);
155         } else {
156             $this->elementStart('div', 'instructions');
157             if ($this->mode == 'recover') {
158                 $this->element('p', null,
159                                // TRANS: Page notice for password recovery page.
160                                _('If you have forgotten or lost your' .
161                                  ' password, you can get a new one sent to' .
162                                  ' the email address you have stored' .
163                                  ' in your account.'));
164             } else if ($this->mode == 'reset') {
165                 $this->element('p', null,
166                                // TRANS: Page notice for password change page.
167                                _('You have been identified. Enter a' .
168                                  ' new password below.'));
169             }
170             $this->elementEnd('div');
171         }
172     }
173
174     function showForm($msg=null)
175     {
176         $this->msg = $msg;
177         $this->mode = 'recover';
178         $this->showPage();
179     }
180
181     function showContent()
182     {
183         if ($this->mode == 'recover') {
184             $this->showRecoverForm();
185         } else if ($this->mode == 'reset') {
186             $this->showResetForm();
187         }
188     }
189
190     function showRecoverForm()
191     {
192         $this->elementStart('form', array('method' => 'post',
193                                            'id' => 'form_password_recover',
194                                            'class' => 'form_settings',
195                                            'action' => common_local_url('recoverpassword')));
196         $this->elementStart('fieldset');
197         // TRANS: Fieldset legend for password recovery page.
198         $this->element('legend', null, _('Password recovery'));
199         $this->elementStart('ul', 'form_data');
200         $this->elementStart('li');
201         // TRANS: Field label on password recovery page.
202         $this->input('nicknameoremail', _('Nickname or email address'),
203                      $this->trimmed('nicknameoremail'),
204                      // TRANS: Title for field label on password recovery page.
205                      _('Your nickname on this server, ' .
206                         'or your registered email address.'));
207         $this->elementEnd('li');
208         $this->elementEnd('ul');
209         $this->element('input', array('name' => 'recover',
210                                       'type' => 'hidden',
211                                       // TRANS: Field label on password recovery page.
212                                       'value' => _('Recover')));
213         // TRANS: Button text on password recovery page.
214         $this->submit('recover', _m('BUTTON','Recover'));
215         $this->elementEnd('fieldset');
216         $this->elementEnd('form');
217     }
218
219     function title()
220     {
221         switch ($this->mode) {
222          // TRANS: Title for password recovery page in password reset mode.
223          case 'reset': return _('Reset password');
224          // TRANS: Title for password recovery page in password recover mode.
225          case 'recover': return _('Recover password');
226          // TRANS: Title for password recovery page in email sent mode.
227          case 'sent': return _('Password recovery requested');
228          // TRANS: Title for password recovery page in password saved mode.
229          case 'saved': return _('Password saved');
230          default:
231             // TRANS: Title for password recovery page when an unknown action has been specified.
232             return _('Unknown action');
233         }
234     }
235
236     function showPasswordForm($msg=null)
237     {
238         $this->msg = $msg;
239         $this->mode = 'reset';
240         $this->showPage();
241     }
242
243     function showResetForm()
244     {
245         $this->elementStart('form', array('method' => 'post',
246                                            'id' => 'form_password_change',
247                                            'class' => 'form_settings',
248                                            'action' => common_local_url('recoverpassword')));
249         $this->elementStart('fieldset');
250          // TRANS: Fieldset legend for password reset form.
251         $this->element('legend', null, _('Password change'));
252         $this->hidden('token', common_session_token());
253         $this->elementStart('ul', 'form_data');
254         $this->elementStart('li');
255          // TRANS: Field label for password reset form.
256         $this->password('newpassword', _('New password'),
257                         // TRANS: Title for field label for password reset form.
258                         _('6 or more characters, and do not forget it!'));
259         $this->elementEnd('li');
260         $this->elementStart('li');
261          // TRANS: Field label for password reset form where the password has to be typed again.
262         $this->password('confirm', _('Confirm'),
263                         // TRANS: Ttile for field label for password reset form where the password has to be typed again.
264                         _('Same as password above.'));
265         $this->elementEnd('li');
266         $this->elementEnd('ul');
267          // TRANS: Button text for password reset form.
268         $this->submit('reset', _m('BUTTON','Reset'));
269         $this->elementEnd('fieldset');
270         $this->elementEnd('form');
271     }
272
273     function recoverPassword()
274     {
275         $nore = $this->trimmed('nicknameoremail');
276         if (!$nore) {
277             // TRANS: Form instructions for password recovery form.
278             $this->showForm(_('Enter a nickname or email address.'));
279             return;
280         }
281
282         $user = User::staticGet('email', common_canonical_email($nore));
283
284         if (!$user) {
285             try {
286                 $user = User::staticGet('nickname', common_canonical_nickname($nore));
287             } catch (NicknameException $e) {
288                 // invalid
289             }
290         }
291
292         // See if it's an unconfirmed email address
293
294         if (!$user) {
295             // Warning: it may actually be legit to have multiple folks
296             // who have claimed, but not yet confirmed, the same address.
297             // We'll only send to the first one that comes up.
298             $confirm_email = new Confirm_address();
299             $confirm_email->address = common_canonical_email($nore);
300             $confirm_email->address_type = 'email';
301             $confirm_email->find();
302             if ($confirm_email->fetch()) {
303                 $user = User::staticGet($confirm_email->user_id);
304             } else {
305                 $confirm_email = null;
306             }
307         } else {
308             $confirm_email = null;
309         }
310
311         if (!$user) {
312             // TRANS: Information on password recovery form if no known username or e-mail address was specified.
313             $this->showForm(_('No user with that email address or username.'));
314             return;
315         }
316
317         // Try to get an unconfirmed email address if they used a user name
318
319         if (!$user->email && !$confirm_email) {
320             $confirm_email = new Confirm_address();
321             $confirm_email->user_id = $user->id;
322             $confirm_email->address_type = 'email';
323             $confirm_email->find();
324             if (!$confirm_email->fetch()) {
325                 $confirm_email = null;
326             }
327         }
328
329         if (!$user->email && !$confirm_email) {
330             // TRANS: Client error displayed on password recovery form if a user does not have a registered e-mail address.
331             $this->clientError(_('No registered email address for that user.'));
332             return;
333         }
334
335         // Success! We have a valid user and a confirmed or unconfirmed email address
336
337         $confirm = new Confirm_address();
338         $confirm->code = common_confirmation_code(128);
339         $confirm->address_type = 'recover';
340         $confirm->user_id = $user->id;
341         $confirm->address = (!empty($user->email)) ? $user->email : $confirm_email->address;
342
343         if (!$confirm->insert()) {
344             common_log_db_error($confirm, 'INSERT', __FILE__);
345             // TRANS: Server error displayed if e-mail address confirmation fails in the database on the password recovery form.
346             $this->serverError(_('Error saving address confirmation.'));
347             return;
348         }
349
350          // @todo FIXME: needs i18n.
351         $body = "Hey, $user->nickname.";
352         $body .= "\n\n";
353         $body .= 'Someone just asked for a new password ' .
354                  'for this account on ' . common_config('site', 'name') . '.';
355         $body .= "\n\n";
356         $body .= 'If it was you, and you want to confirm, use the URL below:';
357         $body .= "\n\n";
358         $body .= "\t".common_local_url('recoverpassword',
359                                    array('code' => $confirm->code));
360         $body .= "\n\n";
361         $body .= 'If not, just ignore this message.';
362         $body .= "\n\n";
363         $body .= 'Thanks for your time, ';
364         $body .= "\n";
365         $body .= common_config('site', 'name');
366         $body .= "\n";
367
368         $headers = _mail_prepare_headers('recoverpassword', $user->nickname, $user->nickname);
369         // TRANS: Subject for password recovery e-mail.
370         mail_to_user($user, _('Password recovery requested'), $body, $headers, $confirm->address);
371
372         $this->mode = 'sent';
373         // TRANS: User notification after an e-mail with instructions was sent from the password recovery form.
374         $this->msg = _('Instructions for recovering your password ' .
375                           'have been sent to the email address registered to your ' .
376                           'account.');
377         $this->success = true;
378         $this->showPage();
379     }
380
381     function resetPassword()
382     {
383         // CSRF protection
384         $token = $this->trimmed('token');
385         if (!$token || $token != common_session_token()) {
386             // TRANS: Form validation error message.
387             $this->showForm(_('There was a problem with your session token. Try again, please.'));
388             return;
389         }
390
391         $user = $this->getTempUser();
392
393         if (!$user) {
394             // TRANS: Client error displayed when trying to reset as password without providing a user.
395             $this->clientError(_('Unexpected password reset.'));
396             return;
397         }
398
399         $newpassword = $this->trimmed('newpassword');
400         $confirm = $this->trimmed('confirm');
401
402         if (!$newpassword || strlen($newpassword) < 6) {
403             // TRANS: Reset password form validation error message.
404             $this->showPasswordForm(_('Password must be 6 characters or more.'));
405             return;
406         }
407         if ($newpassword != $confirm) {
408             // TRANS: Reset password form validation error message.
409             $this->showPasswordForm(_('Password and confirmation do not match.'));
410             return;
411         }
412
413         // OK, we're ready to go
414
415         $original = clone($user);
416
417         $user->password = common_munge_password($newpassword, $user->id);
418
419         if (!$user->update($original)) {
420             common_log_db_error($user, 'UPDATE', __FILE__);
421             // TRANS: Reset password form validation error message.
422             $this->serverError(_('Cannot save new password.'));
423             return;
424         }
425
426         $this->clearTempUser();
427
428         if (!common_set_user($user->nickname)) {
429             // TRANS: Server error displayed when something does wrong with the user object during password reset.
430             $this->serverError(_('Error setting user.'));
431             return;
432         }
433
434         common_real_login(true);
435
436         $this->mode = 'saved';
437         // TRANS: Success message for user after password reset.
438         $this->msg = _('New password successfully saved. ' .
439                        'You are now logged in.');
440         $this->success = true;
441         $this->showPage();
442     }
443
444     /**
445      * A local menu
446      *
447      * Shows different login/register actions.
448      *
449      * @return void
450      */
451
452     function showLocalNav()
453     {
454         $nav = new LoginGroupNav($this);
455         $nav->show();
456     }
457 }