]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/recoverpassword.php
Updated config.php.sample with example Tag URI configs
[quix0rs-gnu-social.git] / actions / recoverpassword.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, 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('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             $this->clientError(_('You are already logged in!'));
37             return;
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                 $this->clientError(_('Unexpected form submission.'));
45             }
46         } else {
47             if ($this->trimmed('code')) {
48                 $this->checkCode();
49             } else {
50                 $this->showForm();
51             }
52         }
53     }
54
55     function checkCode()
56     {
57
58         $code = $this->trimmed('code');
59         $confirm = Confirm_address::staticGet('code', $code);
60
61         if (!$confirm) {
62             $this->clientError(_('No such recovery code.'));
63             return;
64         }
65         if ($confirm->address_type != 'recover') {
66             $this->clientError(_('Not a recovery code.'));
67             return;
68         }
69
70         $user = User::staticGet($confirm->user_id);
71
72         if (!$user) {
73             $this->serverError(_('Recovery code for unknown user.'));
74             return;
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             $this->serverError(_('Error with confirmation code.'));
87             return;
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             $this->clientError(_('This confirmation code is too old. ' .
98                                    'Please start again.'));
99             return;
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->updateKeys($orig);
109             if (!$result) {
110                 common_log_db_error($user, 'UPDATE', __FILE__);
111                 $this->serverError(_('Could not update user with confirmed email address.'));
112                 return;
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::staticGet($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                                _('If you\'ve forgotten or lost your' .
153                                  ' password, you can get a new one sent to' .
154                                  ' the email address you have stored ' .
155                                  ' in your account.'));
156             } else if ($this->mode == 'reset') {
157                 $this->element('p', null,
158                                _('You\'ve been identified. Enter a ' .
159                                  ' new password below. '));
160             }
161             $this->elementEnd('div');
162         }
163     }
164
165     function showForm($msg=null)
166     {
167         $this->msg = $msg;
168         $this->mode = 'recover';
169         $this->showPage();
170     }
171
172     function showContent()
173     {
174         if ($this->mode == 'recover') {
175             $this->showRecoverForm();
176         } else if ($this->mode == 'reset') {
177             $this->showResetForm();
178         }
179     }
180
181     function showRecoverForm()
182     {
183         $this->elementStart('form', array('method' => 'post',
184                                            'id' => 'recoverpassword',
185                                            'action' => common_local_url('recoverpassword')));
186         $this->input('nicknameoremail', _('Nickname or email'),
187                      $this->trimmed('nicknameoremail'),
188                      _('Your nickname on this server, ' .
189                         'or your registered email address.'));
190         $this->submit('recover', _('Recover'));
191         $this->elementEnd('form');
192     }
193
194     function title()
195     {
196         switch ($this->mode) {
197          case 'reset': return _('Reset password');
198          case 'recover': return _('Recover password');
199          case 'sent': return _('Password recovery requested');
200          case 'saved': return _('Password saved.');
201          default:
202             return _('Unknown action');
203         }
204     }
205
206     function showPasswordForm($msg=null)
207     {
208         $this->msg = $msg;
209         $this->mode = 'reset';
210         $this->showPage();
211     }
212
213     function showResetForm()
214     {
215         $this->elementStart('form', array('method' => 'post',
216                                            'id' => 'recoverpassword',
217                                            'action' => common_local_url('recoverpassword')));
218         $this->hidden('token', common_session_token());
219         $this->password('newpassword', _('New password'),
220                         _('6 or more characters, and don\'t forget it!'));
221         $this->password('confirm', _('Confirm'),
222                         _('Same as password above'));
223         $this->submit('reset', _('Reset'));
224         $this->elementEnd('form');
225     }
226
227     function recoverPassword()
228     {
229         $nore = $this->trimmed('nicknameoremail');
230         if (!$nore) {
231             $this->showForm(_('Enter a nickname or email address.'));
232             return;
233         }
234
235         $user = User::staticGet('email', common_canonical_email($nore));
236
237         if (!$user) {
238             $user = User::staticGet('nickname', common_canonical_nickname($nore));
239         }
240
241         # See if it's an unconfirmed email address
242
243         if (!$user) {
244             $confirm_email = Confirm_address::staticGet('address', common_canonical_email($nore));
245             if ($confirm_email && $confirm_email->address_type == 'email') {
246                 $user = User::staticGet($confirm_email->user_id);
247             }
248         }
249
250         if (!$user) {
251             $this->showForm(_('No user with that email address or username.'));
252             return;
253         }
254
255         # Try to get an unconfirmed email address if they used a user name
256
257         if (!$user->email && !$confirm_email) {
258             $confirm_email = Confirm_address::staticGet('user_id', $user->id);
259             if ($confirm_email && $confirm_email->address_type != 'email') {
260                 # Skip non-email confirmations
261                 $confirm_email = null;
262             }
263         }
264
265         if (!$user->email && !$confirm_email) {
266             $this->clientError(_('No registered email address for that user.'));
267             return;
268         }
269
270         # Success! We have a valid user and a confirmed or unconfirmed email address
271
272         $confirm = new Confirm_address();
273         $confirm->code = common_confirmation_code(128);
274         $confirm->address_type = 'recover';
275         $confirm->user_id = $user->id;
276         $confirm->address = (isset($user->email)) ? $user->email : $confirm_email->address;
277
278         if (!$confirm->insert()) {
279             common_log_db_error($confirm, 'INSERT', __FILE__);
280             $this->serverError(_('Error saving address confirmation.'));
281             return;
282         }
283
284         $body = "Hey, $user->nickname.";
285         $body .= "\n\n";
286         $body .= 'Someone just asked for a new password ' .
287                  'for this account on ' . common_config('site', 'name') . '.';
288         $body .= "\n\n";
289         $body .= 'If it was you, and you want to confirm, use the URL below:';
290         $body .= "\n\n";
291         $body .= "\t".common_local_url('recoverpassword',
292                                    array('code' => $confirm->code));
293         $body .= "\n\n";
294         $body .= 'If not, just ignore this message.';
295         $body .= "\n\n";
296         $body .= 'Thanks for your time, ';
297         $body .= "\n";
298         $body .= common_config('site', 'name');
299         $body .= "\n";
300
301         mail_to_user($user, _('Password recovery requested'), $body, $confirm->address);
302
303         $this->mode = 'sent';
304         $this->msg = _('Instructions for recovering your password ' .
305                           'have been sent to the email address registered to your ' .
306                           'account.');
307         $this->success = true;
308         $this->showPage();
309     }
310
311     function resetPassword()
312     {
313         # CSRF protection
314         $token = $this->trimmed('token');
315         if (!$token || $token != common_session_token()) {
316             $this->showForm(_('There was a problem with your session token. Try again, please.'));
317             return;
318         }
319
320         $user = $this->getTempUser();
321
322         if (!$user) {
323             $this->clientError(_('Unexpected password reset.'));
324             return;
325         }
326
327         $newpassword = $this->trimmed('newpassword');
328         $confirm = $this->trimmed('confirm');
329
330         if (!$newpassword || strlen($newpassword) < 6) {
331             $this->showPasswordForm(_('Password must be 6 chars or more.'));
332             return;
333         }
334         if ($newpassword != $confirm) {
335             $this->showPasswordForm(_('Password and confirmation do not match.'));
336             return;
337         }
338
339         # OK, we're ready to go
340
341         $original = clone($user);
342
343         $user->password = common_munge_password($newpassword, $user->id);
344
345         if (!$user->update($original)) {
346             common_log_db_error($user, 'UPDATE', __FILE__);
347             $this->serverError(_('Can\'t save new password.'));
348             return;
349         }
350
351         $this->clearTempUser();
352
353         if (!common_set_user($user->nickname)) {
354             $this->serverError(_('Error setting user.'));
355             return;
356         }
357
358         common_real_login(true);
359
360         $this->mode = 'saved';
361         $this->msg = _('New password successfully saved. ' .
362                        'You are now logged in.');
363         $this->success = true;
364         $this->showPage();
365     }
366 }