<?php
class UsersController extends AppController 
{
    public $name = 'Users';
    public $uses = array('User', 'Profile', 'UserSetting', 'UserFollow', 'Install', 'News', 'Event', 'File', 'Message');
    public $components = array('RequestHandler', 'Cookie', 'Auth', 'Email', 'Activity');


    public function beforeFilter() 
    {
        parent::beforeFilter();
        $this->Auth->authenticate = array(
            'Form' => array(
                'userModel' => 'User',
                'fields' => array('username' => 'email'),
                'scope' => array(
                    'User.deleted' => 0,
                ),
            ),
        );
        
        //Everyone has access to these actions
        $this->Auth->allow('login', 'register', 'confirm', 'recover', (Configure::read('install') ? 'add' : null));
        
        $this->Cookie->name = Configure::read('CFG.site_short_name') . 'Cookie';
        $this->Cookie->key = 'kjf5ss0d8322idfvg8dy732r10jajofn[337hhd0s8[214678';
    }
    
    public function isAuthorized($user) 
    {
        //All members have access to these actions
        if (in_array($this->action, array('index', 'view', 'post_login', 'logout', 'vcard'))) {
            if (in_array($this->action, array('index', 'view')) && !$this->User->access($this->Auth->user('id'))) {
                $this->Session->setFlash(__('You must first complete your profile.'), 
                    'default', array('class' => 'alert alert-danger'));
                return $this->redirect(array('controller' => 'users', 'action' => 'edit', $this->Auth->user('id')));
            }
            return true;
        }
        
        //All members have access to these actions if the item is their own
        if (in_array($this->action, array('edit', 'password'))) {
            $itemId = (int) $this->request->params['pass'][0];
            if ($itemId == $user['id']) {
                return true;
            }
        }
    
        return parent::isAuthorized($user);
    }

    public function index() 
    {
        $this->set('title_for_layout', __('Members'));
        
        //Get all members
        //Count items from user based on role from logged in user
        if ($this->Auth->user('role') != 'admin') {
            $this->User->bindModel(array(
                'hasMany' => array(
                    'News' => array(
                        'className' => 'News',
                        'conditions' => array('News.admin' => '0' ,'News.deleted' => '0'),
                        'order' => 'News.created DESC'
                    ),
                    'Event' => array(
                        'className' => 'Event',
                        'conditions' => array('Event.admin' => '0' ,'Event.deleted' => '0'),
                        'order' => 'Event.created DESC'
                    ),
                    'File' => array(
                        'className' => 'File',
                        'conditions' => array('File.admin' => '0' ,'File.deleted' => '0'),
                        'order' => 'File.created DESC'
                    ),
                    'Message' => array(
                        'className' => 'Message',
                        'conditions' => array('Message.admin' => '0' ,'Message.deleted' => '0'),
                        'order' => 'Message.created DESC'
                    )
                )
            ));
        }
        $users = $this->User->find('all', array(
            'conditions' => array('User.deleted' => 0),
            'order' => array('Profile.last_name ASC'),
            'recursive' => 1
            )
        );
                
        App::uses('Pagination', 'Lib');
        $paginate = new Pagination($users, 8);
        if (isset($this->request->query['p']) && empty($paginate->data)) {
            return $this->redirect(array('action' => 'index'));
        }
        
        $this->set('users', $paginate);
        
        $this->User->unbindModel(
            array('hasMany' => array('News', 'Event', 'File', 'Message'))
        );
        $current_user = $this->User->find('first', array(
                'conditions' => array('User.id' => $this->Auth->user('id'), 'User.deleted' => 0),
            )
        );
        $this->set('current_user', $current_user);
        
    }
    
    public function view($id = null) 
    {
        //Count items from user based on role from logged in user
        if ($this->Auth->user('role') != 'admin') {
            $this->User->bindModel(array(
                'hasMany' => array(
                    'News' => array(
                        'className' => 'News',
                        'conditions' => array('News.admin' => '0' ,'News.deleted' => '0'),
                        'order' => 'News.created DESC'
                    ),
                    'Event' => array(
                        'className' => 'Event',
                        'conditions' => array('Event.admin' => '0' ,'Event.deleted' => '0'),
                        'order' => 'Event.created DESC'
                    ),
                    'File' => array(
                        'className' => 'File',
                        'conditions' => array('File.admin' => '0' ,'File.deleted' => '0'),
                        'order' => 'File.created DESC'
                    ),
                    'Message' => array(
                        'className' => 'Message',
                        'conditions' => array('Message.admin' => '0' ,'Message.deleted' => '0'),
                        'order' => 'Message.created DESC'
                    )
                )
            ));
        }
        $user = $this->User->find('first', array(
                'conditions' => array('User.id' => $id, 'User.deleted' => 0),
            )
        );
        
        $this->set('user', $user);
        $this->set('title_for_layout', $user['Profile']['first_name'] . ' ' . $user['Profile']['last_name']);
        
        //Get all items from member in all categories based on member role (administrator/user)
        $items = $this->User->getItems($this->Auth->user('role'), $id);
    
        $this->set('items', $items);
        
        $this->User->unbindModel(
            array('hasMany' => array('News', 'Event', 'File', 'Message'))
        );
        $current_user = $this->User->find('first', array(
                'conditions' => array('User.id' => $this->Auth->user('id'), 'User.deleted' => 0),
            )
        );
        $this->set('current_user', $current_user);
    }
    
    public function add($json = false) 
    {
        if ($json) {
            $this->layout = false;
            $this->autoRender = false;
        } else {
            $this->set('title_for_layout', __('Add Member'));
        }
        
        //If data submitted save data
        if ($this->request->is('post')) {
            $user = $this->User->find('first', array(
                    'conditions' => array('User.email' => $this->request->data['User']['email'], 'User.deleted' => 0),
                )
            );
            if ($user) {
                if ($json) { 
                    parent::returnJson('error', String::insert(__(':user_email belongs to an existing account'), array('user_email' => $this->request->data['User']['email'])));
                    return;
                } else {
                    $this->Session->setFlash(String::insert(__(':user_email belongs to an existing account'), array('user_email' => $this->request->data['User']['email'])), 
                        'default', array('class' => 'alert alert-danger'));
                    return;
                }
            }
            
            $this->request->data['UserSetting']['date_format'] = Configure::read('CFG.date_format');
            $this->request->data['UserSetting']['time_format'] = Configure::read('CFG.time_format');
            if ($this->User->saveAll($this->request->data)) {
                $this->Activity->log($this->User->id, 'User', 'add');
                
                if ($json) {
                    parent::returnJson('ok', __('Member successfully created'));
                    return;
                }
                $this->Session->setFlash(__('Member successfully created'), 
                    'default', array('class' => 'alert alert-success'));
                
                // Send mail
                if (isset($this->request->data['User']['notify']) && $this->request->data['User']['notify']) {
                    $this->layout = false;
                    $this->render(false);
                    
                    App::uses('CakeEmail', 'Network/Email');
                    $email = new CakeEmail('default');
                    $email->viewVars(
                        array(
                            'name' => $this->request->data['Profile']['first_name'] . ' ' . $this->request->data['Profile']['last_name'],
                            'email' => $this->request->data['User']['email'],
                            'password' => $this->request->data['User']['password'],
                        )
                    );
                    $email->emailFormat('both');
                    $email->template('user_add');
                    $email->from(array(Configure::read('CFG.email_from_email') => Configure::read('CFG.email_from_name')));
                    $email->to($this->request->data['User']['email']);
                    $email->subject(Configure::read('CFG.site_name') . ' - ' . __('Welcome'));
                    $email->send();
                }
                
                return $this->redirect(array('action' => 'index'));
            }
            
            if ($json) {
                parent::returnJson('error', __('An error has occurred'));
                return;
            }
            $this->Session->setFlash(__('An error has occurred'), 
                'default', array('class' => 'alert alert-danger'));
        }
    }
    
    public function edit($id = null) 
    {
        $this->set('title_for_layout', __('Edit Profile'));
        
        $user = $this->User->find('first', array(
                'conditions' => array('User.id' => $id, 'User.deleted' => 0),
            )
        );
        if (!$user) {
            return $this->redirect(array('action' => 'index'));
        }
        
        $this->set('user', $user);
        
        //If data submitted save data
        if ($this->request->is('post')) {
            $this->request->data['User']['id'] = $id;
            $user = $this->User->find('first', array(
                    'conditions' => array('User.id' => $id, 'User.deleted' => 0),
                )
            );
            $this->request->data['Profile']['id'] = $user['Profile']['id'];
            $this->request->data['Profile']['user_id'] = $id;
            
            if (($this->Auth->user('role') != 'admin') && isset($this->request->data['user']['role'])) {
                unset($this->request->data['user']['role']);
            }
            
            if ($this->User->saveAll($this->request->data)) {
                $this->Activity->log($this->User->id, 'Profile', 'edit');
                
                if ($id == $this->Auth->user('id')) {
                    $user = $this->User->find('first', array(
                            'conditions' => array('User.id' => $id, 'User.deleted' => 0),
                        )
                    );
                    $this->Session->write('Auth.User', $user['User']);
                    $this->Session->write('Auth.Profile', $user['Profile']);
                    $this->Session->write('Auth.UserSetting', $user['UserSetting']);
                }
                
                $this->Session->setFlash('Profile successfully saved', 
                    'default', array('class' => 'alert alert-success'));
                return $this->redirect(array('action' => 'view', $id));
            }
            $this->Session->setFlash(__('An error has occurred'));
        }    
    }
    
    public function delete($id = null) 
    {
        $this->layout = false;
        $this->render = false;
        
        //Check if member exists; Else redirect to index
        if (!$id) {
            return $this->redirect(array('action' => 'index'));
        }
        $item = $this->User->find('first', array(
                'conditions' => array('User.id' => $id, 'User.deleted' => 0),
            )
        );
        if (!$item) {
            return $this->redirect(array('action' => 'index'));
        }
        
        //Set deleted field to 1 for member
        $this->request->data['User']['id'] = $id;
        $this->request->data['User']['deleted'] = 1;
        if ($this->User->save($this->request->data)) {
            $this->Activity->log($this->User->id, 'User', 'delete');
            
            $this->Session->setFlash(__('Member successfully deleted'), 
                'default', array('class' => 'alert alert-success'));
            return $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('An error has occurred'), 
            'default', array('class' => 'alert alert-danger'));
        return $this->redirect(array('action' => 'index'));
    }
    
    function settings() 
    {
        $this->layout = false;
        
        //If data submitted save settings
        if ($this->request->is('post')) {
            $user = $this->User->find('first', array(
                    'conditions' => array('User.id' => $this->Auth->user('id'), 'User.deleted' => 0),
                )
            );
            if (empty($user)) {
                parent::returnJson('error', __('An error has occurred'));
                return;
            }
            $this->request->data['UserSetting']['id'] = $user['UserSetting']['id'];
            if ($this->UserSetting->saveAll($this->request->data)) {
                
                $user = $this->User->find('first', array(
                        'conditions' => array('User.id' => $this->Auth->user('id'), 'User.deleted' => 0),
                    )
                );
                $this->Session->write('Auth.UserSetting', $user['UserSetting']);
                
                parent::returnJson('ok', __('Settings saved'));
                return;
            }
            parent::returnJson('error', __('An error has occurred'));
            return;
        } else {
            $this->autoRender = false;
        }
    }
    
    public function register() 
    {
        $this->layout = "user";
        $this->set('title_for_layout', (Configure::read('CFG.users_register') ? __('Sign Up') : __('Request account')));
        
        //If data submitted send data
        if ($this->request->is('post')) {
            $user = $this->User->find('first', array(
                    'conditions' => array('User.email' => $this->request->data['User']['email'], 'User.deleted' => 0),
                )
            );
            if (!empty($user) && $user['User']['confirmed']) {
                $this->Session->setFlash(String::insert(__(':user_email belongs to an existing account'), array('user_email' => $this->request->data['User']['email'])), 
                    'default', array('class' => 'alert alert-danger'));
                return;
            }
            if (!empty($user) && !$user['User']['confirmed']) {
                // Send mail
                $this->layout = false;
                $this->render(false);
                
                App::uses('CakeEmail', 'Network/Email');
                $email = new CakeEmail('default');
                $email->viewVars(
                    array(
                        'name' => $user['Profile']['first_name'] . ' ' . $user['Profile']['last_name'],
                        'user_id' => $user['User']['id'],
                        'token' => $user['User']['confirm_token'],
                    )
                );
                $email->emailFormat('both');
                $email->template('user_confirm');
                $email->from(array(Configure::read('CFG.email_from_email') => Configure::read('CFG.email_from_name')));
                $email->to($this->request->data['User']['email']);
                $email->subject(Configure::read('CFG.site_name') . ' - ' . __('Confirm your account'));
                
                if ($email->send()) {
                    $this->Session->setFlash(String::insert(__(':user_email belongs to an unconfirmed existing account. To confirm your account, click the link in the email we sent you.'), array('user_email' => $this->request->data['User']['email'])), 
                'default', array('class' => 'alert alert-danger'));
                    return $this->redirect(array('action' => 'login'));
                }
                $this->Session->setFlash(__('An error has occurred'), 
                    'default', array('class' => 'alert alert-danger'));
                return $this->redirect(array('action' => 'login'));
            }
            
            if (Configure::read('CFG.users_register')) {
                $this->request->data['User']['role'] = 'user';
                $this->request->data['User']['confirmed'] = 0;
                $this->request->data['User']['confirm_token'] = sha1(date('Y-m-d H:i:s'));
                $this->request->data['UserSetting']['date_format'] = Configure::read('CFG.date_format');
                $this->request->data['UserSetting']['time_format'] = Configure::read('CFG.time_format');
                if ($this->User->saveAll($this->request->data)) {
                    $this->Activity->log($this->User->id, 'User', 'register');
                    
                    $this->Session->setFlash(__('Member successfully created'), 
                        'default', array('class' => 'alert alert-success'));
                    
                    // Send mail
                    $this->layout = false;
                    $this->render(false);
                    
                    App::uses('CakeEmail', 'Network/Email');
                    $email = new CakeEmail('default');
                    $email->viewVars(
                        array(
                            'name' => $this->request->data['Profile']['first_name'] . ' ' . $this->request->data['Profile']['last_name'],
                            'user_id' => $this->User->id,
                            'token' => $this->request->data['User']['confirm_token'],
                        )
                    );
                    $email->emailFormat('both');
                    $email->template('user_confirm');
                    $email->from(array(Configure::read('CFG.email_from_email') => Configure::read('CFG.email_from_name')));
                    $email->to($this->request->data['User']['email']);
                    $email->subject(Configure::read('CFG.site_name') . ' - ' . __('Confirm your account'));
                    
                    if ($email->send()) {
                        $this->Session->setFlash(String::insert(__('Thanks for signing up for :site_name! To confirm your account, click the link in the email we sent you.'), array('site_name' => Configure::read('CFG.site_name'))), 
                            'default', array('class' => 'alert alert-success'));
                        $this->redirect(array('action'=>'login'));
                    }
                    $this->Session->setFlash(__('An error has occurred'), 
                        'default', array('class' => 'alert alert-danger'));
                }
            } else {
                // Send mail
                $this->layout = false;
                $this->render(false);
                
                App::uses('CakeEmail', 'Network/Email');
                $email = new CakeEmail('default');
                $email->viewVars(
                    array(
                        'name' => $this->request->data['Profile']['first_name'] . ' ' . $this->request->data['Profile']['last_name'],
                        'email' => $this->request->data['User']['email'],
                    )
                );
                $email->emailFormat('both');
                $email->template('user_request');
                $email->from(array(Configure::read('CFG.email_from_email') => Configure::read('CFG.email_from_name')));
                $email->to(Configure::read('CFG.email_to_email'));
                $email->subject(Configure::read('CFG.site_name') . ' - ' .  __('Request account'));
                if ($email->send()) {
                    $this->Session->setFlash(__('Your request is pending. We will contact you as soon as possible.'), 
                        'default', array('class' => 'alert alert-success'));
                    return $this->redirect(array('action' => 'login'));
                }
                $this->Session->setFlash(__('An error has occurred'), 
                    'default', array('class' => 'alert alert-danger'));
            }
        }
    }
    
    public function confirm($user_id, $token) 
    {
        $this->layout = false;
        $this->render = false;
        
        if(empty($user_id) || empty($token)) {
            $this->Session->setFlash(__('An error has occurred'),
                'default', array('class' => 'alert alert-danger'), 'auth');
            return $this->redirect(array('action' => 'login'));
        }
        
        $user = $this->User->find('first', 
            array(
                'conditions' => array(
                    'User.id' => $user_id,
                    'User.confirm_token' => $token,
                    'User.deleted' => 0,
                )
            )
        );
        if(!empty($user)) {
            if ($user['User']['confirmed']) {
                $this->Session->setFlash(__('You already confirmed your account'),
                    'default', array('class' => 'alert alert-danger'), 'auth');
                return $this->redirect(array('action' => 'login'));
            }
        
            $this->User->id = $user['User']['id'];
            if($this->User->saveField('confirmed', 1)) {
                $this->Activity->log($this->User->id, 'User', 'confirm');
                
                App::uses('CakeEmail', 'Network/Email');
                $email = new CakeEmail('default');
                $email->viewVars(
                    array(
                        'name' => $user['Profile']['first_name'] . ' ' . $user['Profile']['last_name'],
                    )
                );
                $email->emailFormat('both');
                $email->template('user_register');
                $email->from(array(Configure::read('CFG.email_from_email') => Configure::read('CFG.email_from_name')));
                $email->to($user['User']['email']);
                $email->subject(Configure::read('CFG.site_name') . ' - ' .  __('Welcome'));
                $email->send();
                
                $this->Auth->login($user['User']);
                $this->Session->setFlash(__('Your account is now confirmed'),
                    'default', array('class' => 'alert alert-success'), 'auth');
                return $this->redirect(array('action'=>'post_login'));
            }
        }
        $this->Session->setFlash(__('An error has occurred'),
            'default', array('class' => 'alert alert-danger'), 'auth');
        return $this->redirect(array('action' => 'login'));
    }
    
    public function recover() 
    {
        $this->layout = "user";
        $this->set('title_for_layout', __('Forgot Password'));
        
        //If data submitted generate new password and send data
        if ($this->request->is('post')) {
            $user = $this->User->find('first', array(
                    'conditions' => array('User.email' => $this->request->data['User']['email'], 'User.deleted' => 0),
                )
            );
            if (!$user) {
                $this->Session->setFlash(__('Email address not found'), 
                    'default', array('class' => 'alert alert-danger'));
                return $this->redirect(array('action' => 'recover'));
            }
            
            //Generate password
            $possible = '2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ';
            $password = '';
            $maxLength = strlen($possible);
            for ($i = 0; $i < 8; $i++) {
                $password .= substr($possible, mt_rand(0, $maxLength - 1), 1);
            }
            $user['User']['password'] = $password;
            
            if ($this->User->save($user)) {
                $this->Activity->log($this->User->id, 'User', 'recover');
                
                $this->Session->setFlash(__('A new password is send to your email address'), 
                    'default', array('class' => 'alert alert-success'));
                
                // Send mail
                $this->layout = false;
                $this->render(false);
                
                App::uses('CakeEmail', 'Network/Email');
                $email = new CakeEmail('default');
                $email->viewVars(
                    array(
                        'name' => $user['Profile']['first_name'] . ' ' . $user['Profile']['last_name'],
                        'email' => $user['User']['email'],
                        'password' => $password,
                    )
                );
                $email->emailFormat('both');
                $email->template('user_password');
                $email->from(array(Configure::read('CFG.email_from_email') => Configure::read('CFG.email_from_name')));
                $email->to($this->request->data['User']['email']);
                $email->subject(Configure::read('CFG.site_name') . ' - ' .  __('Forgot password'));
                $email->send();
                
                return $this->redirect(array('action' => 'login'));
            }
            $this->Session->setFlash(__('An error has occurred'), 
                'default', array('class' => 'alert alert-danger'));
        }
    }
    
    public function login() 
    {
        $this->layout = "user";
        $this->set('title_for_layout', 'Login');
    
        if ($this->request->is('post')) {
            $user = $this->User->find('first', 
                array(
                    'conditions' => array(
                        'User.email' => $this->request->data['User']['email'],
                        'User.password' => $this->Auth->password($this->request->data['User']['password']),
                        'User.deleted' => 0
                    )
                )
            );
            if(!empty($user)) {
                if (!$user['User']['confirmed']) {
                    // Send mail
                    $this->layout = false;
                    $this->render(false);
                    
                    App::uses('CakeEmail', 'Network/Email');
                    $email = new CakeEmail('default');
                    $email->viewVars(
                        array(
                            'name' => $user['Profile']['first_name'] . ' ' . $user['Profile']['last_name'],
                            'user_id' => $user['User']['id'],
                            'token' => $user['User']['confirm_token'],
                        )
                    );
                    $email->emailFormat('both');
                    $email->template('user_confirm');
                    $email->from(array(Configure::read('CFG.email_from_email') => Configure::read('CFG.email_from_name')));
                    $email->to($user['User']['email']);
                    $email->subject(Configure::read('CFG.site_name') . ' - ' . __('Confirm your account'));
                    $email->send();
                
                    $this->Session->setFlash(__('You have to confirm your account. Click the link in the email we sent you.'), 
                        'default', array('class' => 'alert alert-danger'), 'auth');
                    return $this->redirect(array('action' => 'login'));
                }
                if ($this->Auth->login($user['User'])) {
                    if (isset($this->request->data['User']['remember_me']) && $this->request->data['User']['remember_me'] == 1) {
                        unset($this->request->data['User']['remember_me']);
                        
                        $cookie = array(
                            'email' => $this->request->data['User']['email'],
                            'password' => $this->Auth->password($this->request->data['User']['password'])
                        );
                        $this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
                    }
                    return $this->redirect(array('action'=>'post_login'));
                } else {
                    $this->Session->setFlash(__('An error has occurred'),
                        'default', array('class' => 'alert alert-danger'), 'auth');
                    return $this->redirect(array('action' => 'login'));
                }
            } else {
                $this->Session->setFlash(__('Email address or password incorrect'), 
                    'default', array('class' => 'alert alert-danger'), 'auth');
                $this->redirect(array('action' => 'login'));
            }
        }
        
        // Check for cookie
        if (empty($this->request->data)) {
            $cookie = $this->Cookie->read('Auth.User');
            if (is_null($cookie) || !is_array($cookie)) return;
            $user = $this->User->find('first', 
                array(
                    'conditions' => array(
                        'User.email' => $cookie['email'],
                        'User.password' => $cookie['password'],
                        'User.deleted' => 0
                    )
                )
            );
            if (is_null($user) || empty($user['User']['id'])) {
                $this->Cookie->delete('Auth.User');
                return;
            }
            if ($this->Auth->login($user['User'])) {
                $this->Session->delete('Message.auth');
                $this->redirect(array('action'=>'post_login'));
            } else {
                $this->Cookie->delete('Auth.User');
            }
        }
    }
    
    public function post_login() 
    {
        $user = $this->User->find('first', array(
                'conditions' => array('User.id' => $this->Auth->user('id'), 'User.deleted' => 0),
            )
        );
        if (!empty($user['Profile'])) {
            $this->Session->write('Auth.Profile', $user['Profile']);
        }
        if (!empty($user['UserSetting'])) {
            if (empty($user['UserSetting']['user_id'])) {
                $user = $this->create_user_setting($user);
            }
            $this->Session->write('Auth.UserSetting', $user['UserSetting']);
        } else{
            $user = $this->create_user_setting($user);
            $this->Session->write('Auth.UserSetting', $user['UserSetting']);
        }
        if (!empty($user)) {
            // modify last login date
            if (!Configure::read('demo')) {
                $this->User->id = $user['User']['id'];
                $this->User->saveField('last_login', date('Y-m-d H:i:s'));
            }
        }

        $redirect = $this->Auth->redirect();
        if (!in_array($redirect, array('/users/register', '/users/recover'))) {
            $this->redirect($redirect);
        } else {
            $this->redirect($this->Auth->loginRedirect);
        }
        
    }
    
    // method for feral update 1.1 to 1.2
    private function create_user_setting($user = array()) 
    {
        $user['UserSetting']['user_id'] = $user['User']['id'];
        $user['UserSetting']['date_format'] = Configure::read('CFG.date_format');
        $user['UserSetting']['time_format'] = Configure::read('CFG.time_format');
        $user['UserSetting']['language'] = Configure::read('CFG.language');
        $user['UserSetting']['timezone'] = Configure::read('CFG.timezone');
        $this->UserSetting->save($user['UserSetting']);
        return $user;
    }
    
    public function logout() 
    {
        $this->Cookie->delete('Auth.User');
        $this->Session->delete('Auth.User');
        $this->Session->delete('Auth.Profile');
        $this->Session->delete('Auth.UserSetting');
        $this->redirect($this->Auth->logout());
    }
    
    //Update password for member
    public function password($id = null) 
    {
        $this->set('title_for_layout', __('Change Password'));
        
        $user = $this->User->find('first', array(
                'conditions' => array('User.id' => $id, 'User.deleted' => 0),
            )
        );
        if (!$user) {
            return $this->redirect(array('action' => 'index'));
        }
        
        $this->set('user', $user);
        
        //If data submitted save data
        if ($this->request->is('post')) {
            $this->request->data['User']['id'] = $id;
            
            if ($this->request->data['User']['password'] != $this->request->data['User']['password2']) {
                $this->Session->setFlash(__('Passwords do not match'), 
                    'default', array('class' => 'alert alert-danger'));
                return;
            }
            if (strlen($this->request->data['User']['password']) < 8) {
                $this->Session->setFlash(__('Password must contain at least 8 characters'), 
                    'default', array('class' => 'alert alert-danger'));
                return;
            }
            
            if (($this->Auth->user('role') != 'admin') && isset($this->request->data['user']['role'])) {
                unset($this->request->data['user']['role']);
            }
            
            unset($this->request->data['User']['password2']);
            if ($this->User->save($this->request->data)) {
                $this->Activity->log($this->User->id, 'User', 'password');
                              
                $this->Session->setFlash(__('Password successfully changed'), 
                    'default', array('class' => 'alert alert-success'));
                return $this->redirect(array('action' => 'view', $id));
            }
            $this->Session->setFlash(__('An error has occurred'), 
                'default', array('class' => 'alert alert-danger'));
        }
        return;
    }
    
    //Download vCard from profile    
    public function vcard($id = null) 
    {
        if (empty($id)) {
            return false;
        }        
        $user = $this->User->find('first', array(
                'conditions' => array('User.id' => $id, 'User.deleted' => 0),
            )
        );
        $this->set('user', $user);
    }
    
    //Set following state for user
    public function follow($id = null) 
    {
        $this->layout = false;
        $this->autoRender = false;
        if (empty($id)) {
            return false;
        }
        if ($id == $this->Auth->user('id')) {
            return false;
        }
        
        $follow = $this->UserFollow->find('first', array(
                'conditions' => array(
                    'UserFollow.user_id' => $this->Auth->user('id'), 
                    'UserFollow.follow_user_id' => $id,
                    'UserFollow.deleted' => 0,
                ),
            )
        );
        //If member already follows => delete; Else create
        if (!empty($follow)) {
            $follow['UserFollow']['deleted'] = 1;
            if ($this->UserFollow->save($follow)) {
                $this->Activity->log($this->UserFollow->id, 'UserFollow', 'unfollow');
                return 2;
            }
        } else {
            $follow['UserFollow']['user_id'] = $this->Auth->user('id');
            $follow['UserFollow']['follow_user_id'] = $id;
            if ($this->UserFollow->save($follow)) {
                $this->Activity->log($this->UserFollow->id, 'UserFollow', 'follow');
                return 1;
            }
        }
        
        return false;
    }
}
