Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/site/app/controllers/users_controller.php
blob: 91f8fbcc91dfb2fc559bb0dba0b0821d63251d9a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
<?php
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is addons.mozilla.org site.
 *
 * The Initial Developer of the Original Code is
 * The Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s):
 *   Andrei Hajdukewycz <sancus@off.net> (Original Author)
 *   Wil Clouser <clouserw@mozilla.com>
 *   Frederic Wenzel <fwenzel@mozilla.com>
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

class UsersController extends AppController
{
    var $name = 'Users';
    var $uses = array('User', 'Addon', 'Eventlog', 'Review', 'Version');
    var $components = array('Amo', 'Email', 'Ldap', 'Session', 'Pagination', 'Recaptcha');
    var $helpers = array('Html', 'Link', 'Javascript');
    var $beforeFilter = array('checkCSRF', 'getNamedArgs', '_checkSandbox');
    var $exceptionCSRF = array("/users/login", "/users/register", "/users/pwreset");	
    var $layout = 'mozilla';
    var $namedArgs = true;

    var $securityLevel = 'high';

    function beforeFilter() {
        // Disable ACLs because this controller is entirely public.
        $this->SimpleAuth->enabled = false;
        $this->SimpleAcl->enabled = false;
        
        // Disable memcache for user queries except in public display page
        if ($this->action != 'info') {
            $this->User->caching = false;
        }
    }
    
    /**
     * Directly calling the user index page just forwards us to the most
     * userful place. For guests, that's the login page. For users, it's
     * their editing page.
     */
    function index() {
        if ($this->Session->check('User')) {
            // logged in
            $this->redirect('/users/edit');
            return;
            
        } else {
            // guest
            $this->redirect('/users/login');
            return;
        }
    }

    
    /**
     * Register a new user
     */
    function register() {
        $this->disableCache();
    
        $this->pageTitle = _('users_register_pagetitle'). ' :: '. sprintf(_('addons_home_pagetitle'), APP_PRETTYNAME);
        $this->publish('cssAdd', array('forms'));
        $this->publish('breadcrumbs', array(_('users_register_pagetitle') => '/users/register'));
        $this->publish('subpagetitle', _('user_form_registration'));
        if (empty($this->data)) {
            $this->render();
            return;
        
        } else {
            // filter nickname characters
            $this->data['User']['nickname'] = $this->_filterNick($this->data['User']['nickname']);
            
            // check captcha
            if ($this->Recaptcha->enabled && (!isset($this->params['form']) ||
                !$this->Recaptcha->is_valid($this->params['form']))) {
                $this->User->invalidate('captcha');
            }
            
            $this->data['User']['confirmationcode'] = md5(mt_rand());
            
            $this->Amo->clean($this->data);
            $this->User->data = $this->data;
            // hash password(s)
            $this->User->data['User']['password'] = md5($this->User->data['User']['password']);
            
            // compare passwords
            if ($this->data['User']['password'] !== $this->data['User']['confirmpw'])
                $this->User->invalidate('confirmpw');
            // no empty pw
            if ($this->data['User']['password'] == '')
                $this->User->invalidate('password');
            // email has to be unique
            $allemail = $this->User->findAllByEmail($this->data['User']['email']);
            if (!empty($allemail)) {
                $this->User->invalidate('email');
                $this->publish('error_email_notunique', true);
            }
            // if nickname is defined it has to be unique
            if (!$this->data['User']['nickname'] == '') {
                $allnicks = $this->User->findAllByNickname($this->data['User']['nickname']);
                if (!empty($allnicks))
                    $this->User->invalidate('nickname');
            }
            
            // any errors? Get our of here.
            if (!$this->User->save()) {
                $this->publish('errorMessage', true);
                $this->render();
                return;
            }
            
            // send confirmation email
            $this->_sendConfirmationCode($this->User->getLastInsertId());
            
            // show success message
            $this->render('register_complete');
            // @TODO enable default user access
        }
    }

    /**
     * Send the user his confirmation code by email
     * @param int user id
     * @return true on success
     */
    function _sendConfirmationCode($id) {
        $data = $this->User->findById($id);

        // don't allow sending an email to already confirmed users.
        if (empty($data['User']['confirmationcode'])) {
            $this->flash(_('error_user_already_confirmed'), '/', 3);
            return false;
        }
        
        $this->publish('userid', $id);
        $this->publish('data', $data);
        $this->Email->template = 'email/confirm';
        $this->Email->to = $data['User']['email'];
        $this->Email->subject = sprintf(_('user_email_confirm_subject'), APP_PRETTYNAME);
        $result = $this->Email->send();
        return true;
    }
    

    /**
     * To verify a user's email they get sent a verification link. This checks
     * if the accessed url is correct and unlocks the user.
     * @param int $id the user's id
     * @param string $code the verification code sent in the email
     */
    function verify($id = 0, $code = '') {
        $this->Amo->clean($id);
        $this->Amo->clean($code);
        
        if (!$id || !$code) {
            $this->flash(sprintf(_('error_missing_argument'), 'user_id or code'), '/', 3);
            return;
        }

        $thisuser = $this->User->findById($id);
        if (empty($thisuser)) {
            $this->flash(_('error_user_notfound'), '/', 3);
            return;
        }

        if ($code == 'resend') { // resend the confirmation code to the user's email address
            if (true === $this->_sendConfirmationCode($id))
                $this->flash(_('user_confirmationcode_resent'), '/', 3);
            return;
        }

        if ($code !== $thisuser['User']['confirmationcode']) {
            $this->flash(_('error_user_badconfirmationcode'), '/', 3);
            return;
        }

        // remove confirmation code from DB
        $this->User->id = $id;
        $this->User->saveField('confirmationcode', '');
        $this->flash(_('user_verified_okay'), '/users/login?to='.urlencode('/'), 3);
    }


    /**
     * Request a password reset. The user gets sent an email with a url. When they
     * access it, they can change their password.
     * @param int $id user id
     * @param string $code the password reset code sent in the email
     */
    function pwreset($id = 0, $code = '') {
        $this->Amo->clean($id);
        $this->Amo->clean($code);
        
        $this->pageTitle = _('users_pwreset_pagetitle').' :: '.sprintf(_('addons_home_pagetitle'), APP_PRETTYNAME);
        $this->publish('cssAdd', array('forms'));
        $this->publish('breadcrumbs', array(_('users_pwreset_pagetitle') => '/users/pwreset'));
        $this->publish('subpagetitle', _('user_pwreset_header'));
        if (!$id && !$code) {
            if (!isset($this->data['User']['email'])) {
                $this->render();    // display 'enter email' form
            
            } else {
            
                $thisuser = $this->User->findByEmail($this->data['User']['email']);
                if (empty($thisuser)) {
                    // user not found
                    $this->User->invalidate('email');
                    $this->render();
                } else {
                    // user found: send pw reset URL via email
                    $this->publish('data', $thisuser);
                    $this->publish('resetcode', md5($thisuser['User']['password']));
                    $this->Email->template = 'email/pwreset';
                    $this->Email->to = $this->data['User']['email'];
                    $this->Email->subject = sprintf(_('user_email_pwreset_subject'), APP_PRETTYNAME);
                    $result = $this->Email->send();

                    $this->flash(_('user_pwreset_link_sent'), '/', 3);
                }
            }
            return;
        }
        
        if (!$id || !$code) {
            $this->flash(sprintf(_('error_missing_argument'), 'user_id or code'), '/', 3);
            return;
        }

        $thisuser = $this->User->findById($id);
        if (empty($thisuser)) {
            $this->flash(_('error_user_notfound'), '/', 3);
            return;
        }

        if ($code !== md5($thisuser['User']['password'])) {
            $this->flash(_('error_user_badconfirmationcode'), '/', 3);
            return;
        }

        $this->publish('email', $thisuser['User']['email']);
        if (isset($this->data['User']['confirmpw'])) {
            // confirm passwords
            if ($this->data['User']['password'] !== $this->data['User']['confirmpw']) {
                $this->User->invalidate('confirmpw');
                $this->data['User']['password'] = '';
                $this->data['User']['confirmpw'] = '';
                $this->render();
                return;
            }
            if ($this->data['User']['password'] == '') {
                $this->User->invalidate('password');
                $this->data['User']['password'] = '';
                $this->data['User']['confirmpw'] = '';
                $this->render();
                return;
            }

            // store new pw
            $newpw = array();
            $newpw['User']['password'] = md5($this->data['User']['password']);
            $this->User->id = $id;
            $this->User->save($newpw);
            // success
            $this->flash(_('user_pwreset_okay'), '/users/login', 3);
        }
    }
    

    /**
     * Give the user a log in form and actually log them in.
     */
    function login() {
        // clean up referer
        if (!isset($this->data['Login']['referer'])) {
            $referer = $this->referer('/', true);
        } else {
            $referer = html_entity_decode($this->data['Login']['referer']);
            // Don't need any referrers that have :// or newlines in them
            if (preg_match("/(:\/\/|\r|\n)/", $referer)) {
                $referer = '/'; // evil referer: forward to front page instead
            }
        }
        
        // if we are logged in, go to the main page
        if ($this->Session->check('User')) {
            $this->redirect($this->referer('/', true));
            return;
        }
    
        $this->pageTitle = _('users_login_pagetitle').' :: '.sprintf(_('addons_home_pagetitle'), APP_PRETTYNAME);
        $this->publish('cssAdd', array('forms'));
        $this->publish('breadcrumbs', array(_('users_login_pagetitle') => '/users/login'));
        $this->publish('subpagetitle', _('user_form_login'));
        $this->publish('loginerror', false);
        
        // by default, just give them a login screen
        if (!isset($this->data['Login']['email']) || !isset($this->data['Login']['password'])) {
            $this->render();
            return;
        }
        
        // if any field is empty, return error
        if (empty($this->data['Login']['email']) || empty($this->data['Login']['password'])) {
            $this->data['Login']['password'] = '';
            $this->publish('loginerror', true);
            $this->render();
            return;
        }

        $someone = $this->User->findByEmail($this->data['Login']['email']);
        if (!empty($someone['User']['id']) && $someone['User']['confirmationcode'] != '') {
            // user not confirmed yet
            $this->publish('userid', $someone['User']['id']);
            $this->publish('email', $someone['User']['email']);
            $this->render('activatefirst');
            return;
        }

        if (!empty($someone['User']['password']) && $someone['User']['password'] == md5($this->data['Login']['password'])) {
            
            //Set expiration to two weeks if they check 'remember me'
            $expirationTime = isset($this->data['Login']['remember']) ? 60*60*24*7*2 : 0;
            
            // correct credentials
            $someone['User']['Group'] = $someone['Group'];
            $this->Session->start($expirationTime);
            $this->Session->write('User', $someone['User']);
            
            // Set app cookie
            setcookie('AMOappName', APP_SHORTNAME, 0, '/');
            
            $this->redirect($referer, null, false, false);
            return;
            
        } else {
            $this->data['Login']['password'] = '';
            $this->publish('loginerror', true);
        }
    }
    

    /**
     * Log the user out (destroy their session and such).
     */
    function logout() {
        if (array_key_exists('to', $_GET)) {
            $_to = html_entity_decode($_GET['to']);
            if (preg_match("/(:\/\/|developers|editors|localizers|admin|users|\r|\n)/", $_to)) {
                $_to = '/';
            }
        }

        $_to = isset($_to) ? $_to : $this->referer('/', true);

        // remove our user from the session table
        if ($this->Session->valid())
            $this->Session->stop();

        $this->redirect($_to, null, false, false);
    }


    /**
     * Have the user edit their user details
     */
    function edit() {
        if (!$this->Session->check('User')) {
            $this->redirect('/users/login');
            return;
        }
        
        $sessionuser = $this->Session->read('User');
        
        $this->pageTitle = _('users_edit_pagetitle').' :: '.sprintf(_('addons_home_pagetitle'), APP_PRETTYNAME);
        $this->publish('cssAdd', array('forms', 'jquery-ui/flora/flora.tabs'));
        $this->publish('jsAdd', array('jquery-ui/ui.core.min', 'jquery-ui/ui.tabs.min'));
        
        if (empty($this->data)) {
            $this->publish('userAddons', $this->Addon->getAddonsByUser($sessionuser['id']));
            
            $this->data['User'] = $sessionuser;
            $this->data['User']['password'] = '';
            $this->render();
            return;
        }
        
        // build array for edited fields
        $changed = array();
        $changed['firstname'] = $this->data['User']['firstname'];
        $changed['lastname'] = $this->data['User']['lastname'];
        $changed['nickname'] = $this->data['User']['nickname'];
        $changed['emailhidden'] = $this->data['User']['emailhidden'];
        $changed['homepage'] = $this->data['User']['homepage'];

        if (!empty($this->data['User']['password']) &&
            !empty($this->data['User']['newpassword'])) {
            
            // trying to change the password
            if ($sessionuser['password'] !== md5($this->data['User']['password']))
                $this->User->invalidate('password');
            if ($this->data['User']['newpassword'] != $this->data['User']['confirmpw'])
                $this->User->invalidate('confirmpw');

            // store the new chosen pw to the "edited" array.
            // If we invalidated fields up here, it's not going to be
            // stored anyway.
            $changed['password'] = md5($this->data['User']['newpassword']);
        }

        // nickname has to be unique
        if ($changed['nickname'] != '') {
            // filter nickname characters
            $this->data['User']['nickname'] = $this->_filterNick($this->data['User']['nickname']);
            
            $allnicks = $this->User->findAllByNickname($changed['nickname']);
            if (count($allnicks) > 1 ||
                (count($allnicks) == 1 && $allnicks[0]['User']['id'] != $sessionuser['id'])) {
                $this->User->invalidate('nickname');
            }
        }
        
        // email change?
        if (empty($this->data['User']['email'])) {
            $this->User->invalidate('email');
            $this->publish('error_email_empty', true);
            
        } elseif ($this->data['User']['email'] != $sessionuser['email']) {
            
            $newemail = $this->data['User']['email'];
            
            // check email format
            if (!preg_match(VALID_EMAIL, $newemail))
                $this->User->invalidate('email');
            
            // email has to be unique
            if ($this->User->findCount(array('User.email' => $newemail)) > 0) {
                $this->User->invalidate('email');
                $this->publish('error_email_notunique', true);
            }
        } else {
            $newemail = false;
        }
        
        // notifications
        $changed['notifycompat'] = $this->data['User']['notifycompat'];
        $changed['notifyevents'] = $this->data['User']['notifyevents'];
        
        // save it
        $this->User->id = $sessionuser['id'];
        $this->User->data['User'] = $changed;
        if (!$this->User->save()) {
            // wipe password fields before returning
            $this->data['User']['password'] = '';
            $this->data['User']['newpassword'] = '';
            $this->data['User']['confirmpw'] = '';
            // re-attach the email to the data so it can be displayed
            if (!empty($newemail))
                $this->data['User']['email'] = $newemail;
            else
                $this->data['User']['email'] = $sessionuser['email'];

            $this->publish('errorMessage', true);
            $this->render();
            return;
        }
        // if we get here, the data was saved successfully
        
        // send out confirmation email if necessary
        if ($newemail !== false) {
            $this->set('newemail', $newemail);
            $this->set('userid', $sessionuser['id']);
            // generate email change code
            $changedata = array($sessionuser['email'], $newemail, time());
            $token = implode(',', $changedata);
            // hash with a secret to be able to check for validity later
            $secret = $this->_getSecret();
            $changecode = base64_encode($token) . md5($token.$secret);
            $this->set('changecode', $changecode);
            
            // send out the confirmation email
            $this->Email->template = 'email/emailchange';
            $this->Email->to = $newemail;
            // @partial translation fallback, 5/6/08
            if (_('user_emailchange_subject') != 'user_emailchange_subject')
                $this->Email->subject = sprintf(_('user_emailchange_subject'), APP_PRETTYNAME);
            else
                $this->Email->subject = sprintf('Please confirm your email address change at %1$s Add-ons', APP_PRETTYNAME);
            $result = $this->Email->send();
        }
        
        $newprofile = $this->User->findById($sessionuser['id']);
        if (!empty($newprofile)) {
            $this->Session->write('User', $newprofile['User']);
            $this->publish('confirmation_message', _('user_profile_saved'));
        } else {
            // this should never happen, but anyway...
            $this->publish('confirmation_message', _('user_profile_edit_error'));
        }
        $this->publish('confirmation_page', true);
        
        $this->render();
    }
    
    /**
     * Process an email change request
     * This URL sent to users by email to confirm their new address.
     * @param int id user id
     * @param string confirmcode Confirmation code (to be parsed and verified)
     */
    function emailchange($id = '') {
        $this->Amo->clean($id);
        if (!(int)$id || !$this->params['url']['code']) {
            $this->flash(sprintf(_('error_missing_argument'), 'user_id or code'), '/', 3);
            return;
        }
        $code = $this->params['url']['code'];
        
        // the arguments may not be empty and since an MD5 hash is 32 chars long
        // and a very short token takes 32 chars in base64, we need at least 64
        // characters, or anything bigger but mod 4 = 0 as base64 generates
        // multiples of four chars.
        if (strlen($code) < 64 || strlen($code)%4 != 0) {
            $this->publish('errormsg', _('error_user_badconfirmationcode'));
            $this->render();
            return;
        }
        
        // split code into token and hash
        $token = substr($code, 0, -32);
        $hash = substr($code, -32);
        
        // decode and hash-check the token
        $token = base64_decode($token);
        if (!$token || md5($token.$this->_getSecret()) != $hash) {
            $this->publish('errormsg', _('error_user_badconfirmationcode'));
            $this->render();
            return;
        }
        $changedata = explode(',', $token);
        if (!$changedata || count($changedata) != 3) {
            $this->publish('errormsg', _('error_user_badconfirmationcode'));
            $this->render();
            return;
        }
        $this->Amo->clean($changedata);
        $this->publish('newemail', $changedata[1]);
        
        // is the token expired (48 hours max)?
        if (time()-$changedata[2] > 48*60*60) {
            // @partial translation fallback, 5/6/08
            if (_('error_user_emailchange_expired') != 'error_user_emailchange_expired')
                $this->publish('errormsg', _('error_user_emailchange_expired'));
            else
                $this->publish('errormsg', 'The email change has expired. Please change '
                    .'your email address again in your user profile and click the link '
                    .'in the confirmation email as soon as you receive it.');
            $this->render();
            return;
        }
        
        $thisuser = $this->User->findById($id);
        if (empty($thisuser)) {
            $this->publish('errormsg', _('error_user_notfound'));
            $this->render();
            return;
        }
        
        // does old email still match?
        if ($thisuser['User']['email'] != $changedata[0]) {
            $this->publish('errormsg', _('error_user_badconfirmationcode'));
            $this->render();
            return;
        }
        
        // is new email address still unique?
        if ($this->User->findCount(array('User.email' => $changedata[1])) > 0) {
            $this->publish('errormsg', _('error_user_email_notunique'));
            $this->render();
            return;
        }
        
        // finally, change the mail address and return success message.
        if (!$this->User->save(array('User' => array(
            'id' => $id,
            'email' => $changedata[1]
            )))) {
            $this->publish('errormsg', _('error_user_badconfirmationcode'));
        }
        // fetch new user profile
        if ($this->Session->check('User')) {
            $currentprofile = $this->Session->read('User');
            if ($currentprofile['id'] == $id) {
                $newprofile = $this->User->find(array('User.id' => $id));
                if (!empty($newprofile)) {
                    $this->Session->write('User', $newprofile['User']);
                }
            }
        }
        $this->render();
    }

    /**
     * Show a user info page
     * @param int user id
     * @return void
     */
    function info($userid = null) {
        global $valid_status;
        
        $this->Amo->clean($userid);
        
        if (!is_numeric($userid)) {
            $this->flash(sprintf(_('error_missing_argument'), 'user_id'), '/', 3);
            return;
        }
        $this->User->bindFully(); // we need their addons as well
        $thisuser = $this->User->findById($userid);
        if (empty($thisuser)) {
            $this->flash(_('error_user_notfound'), '/', 3);
            return;
        }
        
        // re-fetch the addons to get the translations too
        $_addonids = array();
        foreach($thisuser['Addon'] as $_addon) $_addonids[] = $_addon['id'];
        if (!empty($_addonids)) {
            $_addoncriteria = array(
                'Addon.id' => $_addonids,
                'Addon.addontype_id' => array(ADDON_EXTENSION, ADDON_THEME),
                'Addon.inactive' => 0,
                'Addon.status' => $valid_status
            );
            $addons = $this->Addon->findAll($_addoncriteria, null, 'Translation.name');
        } else {
            $addons = array();
        }
        
        // get all reviews made by user
        $reviews = $this->Review->findAll("Review.user_id = {$userid} AND Review.reply_to IS NULL");
        foreach ($reviews as &$_review) {
            $_version = $this->Version->findById($_review['Review']['version_id'], 'Version.addon_id');
            if (!empty($_version)) {
                $_addon = $this->Addon->getAddon($_version['Version']['addon_id'], array('compatible_apps', 'latest_version'));
                $_review['Addon'] = $_addon;
            }
        }
        $this->publish('reviews', $reviews);

        if (!empty($thisuser['User']['nickname']))
            $name = $thisuser['User']['nickname'];
        else
            $name = $thisuser['User']['firstname'].' '.$thisuser['User']['lastname'];
        $_title = sprintf(_('users_info_pagetitle'), $name);
        $this->pageTitle = $_title.' :: '.sprintf(_('addons_home_pagetitle'), APP_PRETTYNAME);
        $this->publish('breadcrumbs', array($_title => "/user/{$userid}"));
        $this->publish('subpagetitle', $_title);
        $this->publish('profile', $thisuser);
        $this->publish('addons', $addons);
        $this->render();
    }
    
    /**
     * (User-facing:) Delete a user account
     * Anonymizes a user account (does not delete the row off the database)
     */
    function delete() {
        $this->Amo->checkLoggedIn();
        
        $this->pageTitle = ___('users_delete_pagetitle', 'Delete User Account').' :: '.sprintf(_('addons_home_pagetitle'), APP_PRETTYNAME);
        $this->publish('cssAdd', array('forms'));
        
        $deluser = $this->Session->read('User');
        $this->publish('useremail', $deluser['email']);
        $this->set('userid', $deluser['id']);
        
        if (!empty($this->data['User'])) {
            // deletion requested
            
            // checkbox checked?
            if (empty($this->data['User']['reallydelete'])) {
                $this->set('deleteerror', 'checkbox');
                return;
            }
            
            // password entered correctly?
            if (md5($this->data['User']['password']) != $deluser['password']) {
                $this->set('deleteerror', 'password');
                $this->data['User']['password'] = ''; // do not post back password
                return;
            }
            
            // disallow users that have add-ons to delete their accounts
            if ($this->User->getAddonCount($deluser['id']) > 0) {
                $this->set('deleteerror', 'addons');
                return;
            }
            
            // delete user (includes anonymizing reviews)
            if (!$this->User->anonymize($deluser['id'])) {
                // failure
                $this->set('deleteerror', 'unknown');
                return;
            } else {
                // success: wipe session, display success message
                $this->Session->stop();
                $this->set('success', true);
                return;
            }
        }
    }
    
    /**
     * Associate AMO account with an LDAP group
     * @param string $group The group name
     */
    function associateGroup($group) {
        // Make sure logged into AMO
        $this->Amo->checkLoggedIn("/users/associateGroup/{$group}");
        
        // Make sure entered LDAP info
        if (!isset($_SERVER['PHP_AUTH_USER'])) {
            header('WWW-Authenticate: Basic realm="Mozilla Corporation - LDAP Login"');
            header('HTTP/1.0 401 Unauthorized');
            $this->flash('You must authenticate to view this page.', '/', 3);
            return;
        }
        
        // Connect to LDAP
        if (!$this->Ldap->connect($_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'])) {
            $this->flash('Could not authenticate', '/', 3);
            return;
        }
        
        // Check if in group
        if (!$this->Ldap->hasAccount($_SERVER['PHP_AUTH_USER'], $group)) {
            $this->flash('Not a member of requested group', '/', 3);
            return;
        }
        
        $groups = array(
            '4247a32ebaed692a8d72cea6382f8c5b' => 38
        );
        
        $group_id = $groups[md5($group)];
        $user = $this->Session->read('User');
        
        if (!empty($group_id)) {
            // Make sure not already in group
            if (!empty($user['Group'])) {
                foreach ($user['Group'] as $user_group) {
                    if ($user_group['id'] == $group_id) {
                        $this->flash('You are already a member of this group!', '/', 3);
                        return;
                    }
                }
            }
            
            $this->User->execute("INSERT INTO groups_users (group_id, user_id) VALUES('{$group_id}', '{$user['id']}')");
            
            // Log user action
            $this->Eventlog->log($this, 'user', 'group_associated', null, $group_id);
            
            $this->flash("You have been successfully added to the {$group} group. You must log out and back in for this to take effect.", '/users/logout', 5);
        }
        
        return;
    }
    
    /**
     * return the secret to generate and validate email changes.
     * If necessary, generate it once.
     */
    function _getSecret() {
        $secret = $this->Config->getValue('emailchange_secret');
        if (empty($secret)) {
            // generate a secret for the first time
            $len = mt_rand(10, 255);
            $secret = '';
            while (strlen($secret) < $len)
                $secret .= md5(mt_rand());
            $secret = substr($secret, 0, $len);
            
            // store it in the DB for the future
            $this->Config->save(array('Config' => array(
                'key' => 'emailchange_secret',
                'value' => $secret)));
        }
        return $secret;
    }
    
    /**
     * Remove forbidden characters from nicknames
     */
    function _filterNick($nickname) {
        $nickname = str_replace(html_entity_decode('&#8203;', ENT_NOQUOTES, 'UTF-8'), '', $nickname); // zero-break space: bug 412694
        return trim($nickname);
    }

}

?>