<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Auth extends Painel_Controller
{
    private $users_online;
    
    function __construct() 
    {
        parent::__construct();
        
        $this->load->library('auth/Tank_auth');
        $this->load->library('form_validation');
        $this->lang->load('tank_auth');
    }
    
    function index() 
    {
        if ($message = $this->session->flashdata('message')) 
        {
            Template::set(array(
                'message' => $message
            ));
            Template::set_view('auth/general_message');
            Template::render();
        } 
        else
        {
            redirect('dashboard');
        }
        
    }
    /**
     * Login user on the site
     *
     * @return void
     */
    function login()
	{
	    
	    $this->load_modal_account_activated();
	    
	    $this->load_modal_redefinir_senha();
	    
	    if ($this->tank_auth->is_logged_in()) 
	    { // logged in
			redirect('dashboard');
		} 
		elseif ($this->tank_auth->is_logged_in(FALSE)) 
		{ // logged in, not activated
		    redirect('auth/send_again/');
		} 
		else 
		{
		    $this->load->library('security_key');
			
		    $data['page'] = 'auth/login';
		    $data['login'] = '';
		    $str = $this->input->post('str');
		    
			if($this->input->is_ajax_request() === TRUE && !empty($str))
			{
			    $data = $this->login_validate($str); 
            }
            
            $data['show_captcha'] = FALSE;
            $data['use_recaptcha'] = $this->config->item('use_recaptcha', 'tank_auth');
            $data['allow_registration'] = $this->config->item('allow_registration', 'tank_auth');
            if ($this->tank_auth->is_max_login_attempts_exceeded($data['login'])) 
            {
                $data['show_captcha'] = TRUE;
            }
            
    	    $data['public_key'] = $this->db->where('name','captcha_public_key')->get('sys_config')->row()->value;
          
		    Template::set($data); 
          	
          	Assets::add_module_css('auth', 'login.css');
          	
            //Assets::add_js(Template::theme_url('jquery.flip'));
          	
          	Assets::add_module_js('auth',array(
          			'pidcrypt.js',
          			'pidcrypt_util.js',
          			'asn1.js',
          			'jsbn.js',
          			'rng.js',
          			'prng4.js',
          			'rsa.js',
          			'encrypt-rsa.js',
          			'login.js',
          			'jquery.flip'
          	));          	
          	
            Template::set_view('painel/login_view');
            
           	Template::render();
		}
	}
	
	private function load_modal_account_activated()
	{
        $modal_account = $this->session->flashdata('account_activated');
        if ($modal_account !== NULL) 
        {
            $data['result'] = $modal_account;
            
            Template::load_view('modal/account_activated', $data, '', '', $data['modal']['account_activated']); 
            
            Assets::add_js("$('.modal-account-activated').modal('show')", 'inline');
            
            Template::set($data); 
        }
	}
	
	private function load_modal_redefinir_senha()
	{
	    $modal_senha = $this->session->modal_troca_senha;
        if ($modal_senha !== NULL) 
        {
            if($modal_senha !== 'Error')
            {
                $set_data = array(
                    'nome' => $modal_senha->nome
                );
                Template::load_view('modal/troca_senha', $set_data, '', '', $data['modal']['troca_senha']);    
            }
            else
            {
                Template::load_view('modal/modal_erro_key', '', '', '', $data['modal']['erro_troca_senha']); 
            }
            Assets::add_js("$('.modal-troca-senha').modal('show')", 'inline');
            Template::set($data); 
        }
	}

    private function login_validate($str) 
    {
    $id_rsa = $this->session->userdata('id_rsa');
    
    if (!empty($id_rsa)) 
    {
        $str_serialized = $this->security_key->decrypt_str($str, $id_rsa);
        
        $this->load->model('seguranca_model');
        $this->session->unset_userdata('id_rsa');
        $this->seguranca_model->delete_key($id_rsa);
        
        log_message('info', $str_serialized);
        parse_str($str_serialized, $output);
    } 
    else
    {
        if (empty($str)) 
        {
            log_message('error', 'var $str is empty');
        }
        if (empty($id_rsa)) 
        {
            log_message('error', 'var $id_rsa is empty');
        }
    }
    
    $login_attempts = $this->config->item('login_count_attempts', 'tank_auth');
    
    if ($login_attempts == TRUE && !empty($output['username'])) 
    {
        $login = $this->security->xss_clean($output['username']);
    } 
    else
    {
        $login = '';
    }
    
    if (isset($output['password'])) 
    {
        $senha = $this->security->xss_clean($output['password']);
        
        if (empty($senha)) 
        {
            $error = "Por favor preencher o campo Senha.";
            echo json_encode(array(
                'valid' => false,
                'error' => $error
            ));
            exit();
        }
    } 
    else
    {
        $error = "Falha de Comunicação com o Servidor."; // não chegou password descriptografado
        echo json_encode(array(
            'valid' => false,
            'error' => $error
        ));
        exit();
    }
    
    $remember = (isset($output['remember'])) ? $output['remember'] : 0;
    
    if ($this->form_validation->integer($remember) !== TRUE) 
    {
        $error = "Valor incorreto do campo mantenha-me conectado.";
        echo json_encode(array(
            'valid' => false,
            'error' => $error
        ));
        exit();
    }
    
    $data['login_by_username'] = ($this->config->item('login_by_username', 'tank_auth') AND $this->config->item('use_username', 'tank_auth'));
    $data['login_by_email'] = $this->config->item('login_by_email', 'tank_auth');
    
    $new_login = $this->session->userdata('new_login');
    
    $logged_in = $this->tank_auth->in_ci_sessions($login) == TRUE;
    
    $user_conected = FALSE;
    
    if (($logged_in == TRUE && empty($new_login)) OR (!empty($new_login) && $new_login != $login && $logged_in == TRUE)) 
    {
        $user_conected = TRUE;
    }
    // validation ok
    if ($this->tank_auth->login($login, $senha, $remember, $data['login_by_username'], $data['login_by_email'], $user_conected)) 
    { // success
        $this->session->unset_userdata('new_login');
        
        echo json_encode(array(
            'valid' => true,
            'redirect' => base_url('dashboard')  // setar uri destino caso esteja na session
        ));
        exit();
    } 
    else
    {
        $error = '';
        
        $this->session->unset_userdata('id_rsa');
        
        $errors = $this->tank_auth->get_error_message();
        if (isset($errors['banned'])) // banned user
        
        {
            $error = $this->lang->line('auth_message_banned') . ' ' . $errors['banned'];
        } 
        elseif (isset($errors['not_activated'])) // not activated user
        
        {
            
            $error = "Login inativo!";
        } 
        elseif (isset($errors['user_conected'])) 
        {
            $error = $errors['user_conected'];
        } 
        else
        { // fail
            $error = "Login ou Senha Inválida!";
        }
        
        echo json_encode(array(
            'valid' => false,
            'error' => $error
        ));
        exit();
    }
    
    $data['login'] = $login;
    
    return $data;
}

public function esqueci_a_senha() 
{
    //$data['result_cadastro'] = $this->session->flashdata('result_cadastro'); //result da ativacao do cadastro da nova senha
    
    if ($this->input->post() == TRUE) 
    {
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
        
        if ($this->form_validation->run() != FALSE) 
        {
            $email = $this->input->post('email');
            
            $this->load->model('auth/users');
            
            $result_email = $this->users->get_usuario_by_email($email);
            
            if ($result_email !== NULL) 
            {   
                $id_cadastro = $result_email->id_cadastro;
                $nome = $result_email->nome;
                $new_password_key = $result_email->new_password_key;
                if ($new_password_key === NULL) 
                {
                    $new_password_key = md5(rand() . microtime());
                    
                    $result_new_password = $this->users->update_new_password_key($email, $new_password_key);
                    
                    if ($result_new_password === TRUE) 
                    {
                        $this->send_message_by_email($nome, $id_cadastro, $email, $new_password_key);
                    } 
                    else
                    {
                        echo json_encode(array(
                            'valid' => false,
                            'msg' => 'O email de confirmação para troca de senha não pode ser enviado. Por favor, tente novamente mais tarde.'
                        ));
                    }
                } 
                else
                {
                    $this->send_message_by_email($nome, $id_cadastro, $email, $new_password_key);
                    /*echo json_encode(array(
                        'valid' => false,
                        'msg' => 'Uma mensagem já foi enviada para o email inserido. Confira em sua Caixa de Entrada, Span, ou Lixeira. Caso não encontre entre em contato conosco.'
                    ));*/
                }
            } 
            else
            {
                echo json_encode(array(
                    'valid' => false,
                    'msg' => 'O email <b>' . $email . '</b> não foi encontrado.'
                ));
            }
        } 
        else
        {
            echo json_encode(array(
                'valid' => false,
                'msg' => 'Por favor, insira um email válido.'
            ));
        }
    }
}

public function send_message_by_email($nome, $id_cadastro, $email, $new_password_key) 
{
    $this->load->library('email');
    
    $url = base_url() . "auth/auth/new_password/" . $id_cadastro . $new_password_key;
    
    $data = array(
        'nome' => $nome,
        'url' => $url
    );
    
    $config['protocol'] = 'mail';
    $config['mailpath'] = '/usr/sbin/sendmail';
    // $config['charset'] = 'utf-8';
    $config['wordwrap'] = TRUE;
    
    $this->email->initialize($config);

    $this->email->from('noreply@blogvb.com', "Blog VB");
    $this->email->to($email);
    $this->email->subject('Atualização de Senha');
    
    Template::load_view('painel/email/new_password-html', $data, '', '', $view);
    $this->email->message($view);
    
    $message = '<p class="text-center">Uma mensagem de confirmação foi enviada para o e-mail:<br/><u>' . $email . '</u>.<br/> 
    	Por favor, clique no link de confirmação da mensagem para cadastrar nova senha. 
    	Se depois de 24 horas você não tiver recebido, entre em contato conosco.</p>';
    
    if ($this->email->send()) 
    {
        echo json_encode(array(
            'valid' => true,
            'msg' => $message
        ));
    } 
    else
    {
        echo json_encode(array(
            'valid' => false,
            'msg' => 'O email de confirmação para a troca da senha não pode ser enviado. Por favor, tente novamente mais tarde.'
        ));
    }
}

public function new_password() 
{
    $key_concat = $this->uri->segment(4);
    $this->load->model('sistema/usuario_model');
    $user = $this->usuario_model->get_user_by_key($key_concat);
    
    if ($user !== NULL) 
    {
        $this->session->set_userdata('modal_troca_senha', $user);
    }
    else
    {
        $this->session->set_userdata('modal_troca_senha', 'Error');
    }
    $this->session->mark_as_temp('modal_troca_senha', 600);
    
    redirect('painel');
}

public function atualizar_senha() 
{
    if ($this->input->post() == TRUE) 
    {
        $this->load->library('form_validation');
        
        $this->form_validation->set_rules('nova_senha', 'Senha', 'required|trim');
        $this->form_validation->set_rules('conf_nova_senha', 'Confirmar Senha', 'required|trim|matches[nova_senha]');
        
        if ($this->form_validation->run() != FALSE) 
        {
            //$auth = new Tank_auth();
            $senha = $this->input->post('nova_senha');
            //$password = $auth->password_hash($senha);
            $password = $this->password_hash($senha);
            $modal_senha = $this->session->userdata('modal_troca_senha');
            $key = $modal_senha->id . $modal_senha->new_password_key;
            
            //$result = FALSE;
            $this->load->model('sistema/usuario_model');
            $result = $this->usuario_model->definir_nova_senha($password, $key);
            
            if ($result === TRUE) 
            {
                echo json_encode(array(
                    'valid' => true,
                    'msg' => 'Senha atualizada com sucesso.'
                ));
                $this->session->unset_userdata('modal_troca_senha');
            } 
            else
            {
                echo json_encode(array(
                    'valid' => false,
                    'msg' => 'A senha não pode ser atualizada. Favor tentar novamente ou entre em contato conosco.'
                ));
            }
        } 
        else
        {
            echo json_encode(array(
                'valid' => false,
                'msg' => 'As senhas não correspondem.'
            ));
        }
    }
}

function password_hash($senha) 
{
    // Hash password using phpass
    $hasher = new PasswordHash($this->config->item('phpass_hash_strength', 'tank_auth') , $this->config->item('phpass_hash_portable', 'tank_auth'));
    $senha = $hasher->HashPassword($senha);
    
    return $senha;
}

public function check_google_captcha() 
{
    $url = 'https://www.google.com/recaptcha/api/siteverify';
    // init curl
    $ch = curl_init();
    
    $secret = $this->db->where('name','captcha_private_key')->get('sys_config')->row()->value;
    $response = $this->input->post('response');
    //Set the URL to work with
    curl_setopt($ch, CURLOPT_URL, $url);
    // ENABLE HTTP POST
    curl_setopt($ch, CURLOPT_POST, TRUE);
    //Set the post parameters
    curl_setopt($ch, CURLOPT_POSTFIELDS, 'secret=' . $secret . '&response=' . $response);
    //Handle cookies for the login
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookie-google.txt');
    //curl_setopt($ch,CURLOPT_USERAGENT,'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.52 Safari/537.17');
    curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($ch, CURLOPT_VERBOSE, TRUE);
    
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    //Setting CURLOPT_RETURNTRANSFER variable to 1 will force cURL
    //not to print out the results of its query.
    //Instead, it will return the results as a string return value
    //from curl_exec() instead of the usual TRUE/FALSE.
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    //execute the request (the login)
    $response = curl_exec($ch);
    //the login is now done and you can continue to get the
    //protected content.
    
    curl_close($ch);
    
    echo json_encode($response);
}

public function generate_key() 
{
    if ($this->input->is_ajax_request() === TRUE) 
    {
        $this->load->library('auth/security_key');
        $id_rsa = $this->security_key->crete_key();
        $public_key = $this->security_key->get_public_key($id_rsa);
        
        echo json_encode(array(
            'valid' => TRUE,
            'public_key' => $public_key
        ));
        exit();
    } 
    else
    {
        echo json_encode(array(
            'valid' => FALSE
        ));
        exit();
    }
}

public function consulta_captcha() 
{
    $login = $this->input->post('login');
    
    if ($this->tank_auth->is_max_login_attempts_exceeded($login)) 
    {
        echo json_encode(array(
            'result' => true
        ));
    } 
    else
    {
        echo json_encode(array(
            'result' => false
        ));
    }
}
/**
 * Logout user
 *
 * @return void
 */
function logout() 
{
    $this->tank_auth->logout();
    
    $this->_show_message($this->lang->line('auth_message_logged_out'));
}

public function redireciona()
{
    $modal_account = (boolean)$this->uri->segment(3);
    $this->session->set_flashdata('account_activated',$modal_account);
    redirect('painel');
}
/**
 * Register user on the site
 *
 * @return void
 */
function register() 
{
    if ($this->tank_auth->is_logged_in()) 
    { // logged in
        redirect('');
    } 
    elseif ($this->tank_auth->is_logged_in(FALSE)) 
    { // logged in, not activated
        /*redirect('/auth/send_again/');*/
        redirect('/seguranca/reenvio/');
    } 
    elseif (!$this->config->item('allow_registration', 'tank_auth')) 
    { // registration is off
        $this->_show_message($this->lang->line('auth_message_registration_disabled'));
    } 
    else
    {
        $use_username = $this->config->item('use_username', 'tank_auth');
        if ($use_username) 
        {
            $this->form_validation->set_rules('username', 'Username', 'trim|required|min_length[' . $this->config->item('username_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('username_max_length', 'tank_auth') . ']|alpha_dash');
        }
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        $this->form_validation->set_rules('password', 'Password', 'trim|required|min_length[' . $this->config->item('password_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('password_max_length', 'tank_auth') . ']|alpha_dash');
        $this->form_validation->set_rules('confirm_password', 'Confirm Password', 'trim|required|matches[password]');
        
        $captcha_registration = $this->config->item('captcha_registration', 'tank_auth');
        $use_recaptcha = $this->config->item('use_recaptcha', 'tank_auth');
        if ($captcha_registration) 
        {
            if ($use_recaptcha) 
            {
                $this->form_validation->set_rules('recaptcha_response_field', 'Confirmation Code', 'trim|required|callback__check_recaptcha');
            } 
            else
            {
                $this->form_validation->set_rules('captcha', 'Confirmation Code', 'trim|required|callback__check_captcha');
            }
        }
        $data['errors'] = array();
        
        $email_activation = $this->config->item('email_activation', 'tank_auth');
        
        if ($this->form_validation->run()) 
        { // validation ok
            if (!is_null($data = $this->tank_auth->create_user($use_username ? $this->form_validation->set_value('username') : '', $this->form_validation->set_value('email') , $this->form_validation->set_value('password') , $email_activation))) 
            { // success
                
                $data['site_name'] = $this->config->item('website_name', 'tank_auth');
                
                if ($email_activation) 
                { // send "activate" email
                    $data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;
                    
                    $this->_send_email('activate', $data['email'], $data);
                    
                    unset($data['password']); // Clear password (just for any case)
                    
                    $this->_show_message($this->lang->line('auth_message_registration_completed_1'));
                } 
                else
                {
                    if ($this->config->item('email_account_details', 'tank_auth')) 
                    { // send "welcome" email
                        
                        $this->_send_email('welcome', $data['email'], $data);
                    }
                    unset($data['password']); // Clear password (just for any case)
                    
                    $this->_show_message($this->lang->line('auth_message_registration_completed_2') . ' ' . anchor('/auth/login/', 'Login'));
                }
            } 
            else
            {
                $errors = $this->tank_auth->get_error_message();
                foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
            }
        }
        if ($captcha_registration) 
        {
            if ($use_recaptcha) 
            {
                $data['recaptcha_html'] = $this->_create_recaptcha();
            } 
            else
            {
                $data['captcha_html'] = $this->_create_captcha();
            }
        }
        $data['use_username'] = $use_username;
        $data['captcha_registration'] = $captcha_registration;
        $data['use_recaptcha'] = $use_recaptcha;
        
        $this->load->view('auth/register_form', $data);
    }
}
/**
 * Send activation email again, to the same or new email address
 *
 * @return void
 */
function send_again() 
{
    if (!$this->tank_auth->is_logged_in(FALSE)) 
    { // not logged in or activated
        redirect('painel');
    } 
    else
    {
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        
        $data['errors'] = array();
        
        if ($this->form_validation->run()) 
        { // validation ok
            if (!is_null($data = $this->tank_auth->change_email($this->form_validation->set_value('email')))) 
            { // success
                
                $data['site_name'] = $this->config->item('website_name', 'tank_auth');
                $data['activation_period'] = $this->config->item('email_activation_expire', 'tank_auth') / 3600;
                
                $this->_send_email('activate', $data['email'], $data);
                
                $this->_show_message(sprintf($this->lang->line('auth_message_activation_email_sent') , $data['email']));
            } 
            else
            {
                $errors = $this->tank_auth->get_error_message();
                foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
            }
        }
        
        Template::set($data);
        Template::set_view('auth/reenvia_view');
        Template::render();
    }
}
/**
 * Activate user account.
 * User is verified by user_id and authentication code in the URL.
 * Can be called by clicking on link in mail.
 *
 * @return void
 */
function activate() 
{
    $user_id = $this->uri->segment(3);
    $new_email_key = $this->uri->segment(4);
    // Activate user
    if ($this->tank_auth->activate_user($user_id, $new_email_key)) 
    { // success
        $this->tank_auth->logout();
        $this->_show_message($this->lang->line('auth_message_activation_completed') . ' ' . anchor('/auth/login/', 'Login'));
    } 
    else
    { // fail
        $this->_show_message($this->lang->line('auth_message_activation_failed'));
    }
}
/**
 * Generate reset code (to change password) and send it to user
 *
 * @return void
 */
function forgot_password() 
{
    if ($this->tank_auth->is_logged_in()) 
    { // logged in
        redirect('');
    } 
    elseif ($this->tank_auth->is_logged_in(FALSE)) 
    { // logged in, not activated
        /*redirect('/auth/send_again/');*/
        redirect('/seguranca/reenvio/');
    } 
    else
    {
        $this->form_validation->set_rules('login', 'Email or login', 'trim|required');
        
        $data['errors'] = array();
        
        if ($this->form_validation->run()) 
        { // validation ok
            if (!is_null($data = $this->tank_auth->forgot_password($this->form_validation->set_value('login')))) 
            {
                
                $data['site_name'] = $this->config->item('website_name', 'tank_auth');
                // Send email with password activation link
                $this->_send_email('forgot_password', $data['email'], $data);
                
                $this->_show_message($this->lang->line('auth_message_new_password_sent'));
            } 
            else
            {
                $errors = $this->tank_auth->get_error_message();
                foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
            }
        }
        $this->load->view('auth/forgot_password_form', $data);
    }
}
/**
 * Replace user password (forgotten) with a new one (set by user).
 * User is verified by user_id and authentication code in the URL.
 * Can be called by clicking on link in mail.
 *
 * @return void
 */
function reset_password() 
{
    $user_id = $this->uri->segment(3);
    $new_pass_key = $this->uri->segment(4);
    
    $this->form_validation->set_rules('new_password', 'New Password', 'trim|required|min_length[' . $this->config->item('password_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('password_max_length', 'tank_auth') . ']|alpha_dash');
    $this->form_validation->set_rules('confirm_new_password', 'Confirm new Password', 'trim|required|matches[new_password]');
    
    $data['errors'] = array();
    
    if ($this->form_validation->run()) 
    { // validation ok
        if (!is_null($data = $this->tank_auth->reset_password($user_id, $new_pass_key, $this->form_validation->set_value('new_password')))) 
        { // success
            
            $data['site_name'] = $this->config->item('website_name', 'tank_auth');
            // Send email with new password
            $this->_send_email('reset_password', $data['email'], $data);
            
            $this->_show_message($this->lang->line('auth_message_new_password_activated') . ' ' . anchor('/auth/login/', 'Login'));
        } 
        else
        { // fail
            $this->_show_message($this->lang->line('auth_message_new_password_failed'));
        }
    } 
    else
    {
        // Try to activate user by password key (if not activated yet)
        if ($this->config->item('email_activation', 'tank_auth')) 
        {
            $this->tank_auth->activate_user($user_id, $new_pass_key, FALSE);
        }
        
        if (!$this->tank_auth->can_reset_password($user_id, $new_pass_key)) 
        {
            $this->_show_message($this->lang->line('auth_message_new_password_failed'));
        }
    }
    $this->load->view('auth/reset_password_form', $data);
}
/**
 * Change user password
 *
 * @return void
 */
function change_password() 
{
    if (!$this->tank_auth->is_logged_in()) 
    { // not logged in or not activated
        redirect('painel');
    } 
    else
    {
        $this->form_validation->set_rules('old_password', 'Old Password', 'trim|required');
        $this->form_validation->set_rules('new_password', 'New Password', 'trim|required|min_length[' . $this->config->item('password_min_length', 'tank_auth') . ']|max_length[' . $this->config->item('password_max_length', 'tank_auth') . ']|alpha_dash');
        $this->form_validation->set_rules('confirm_new_password', 'Confirm new Password', 'trim|required|matches[new_password]');
        
        $data['errors'] = array();
        
        if ($this->form_validation->run()) 
        { // validation ok
            if ($this->tank_auth->change_password($this->form_validation->set_value('old_password') , $this->form_validation->set_value('new_password'))) 
            { // success
                $this->_show_message($this->lang->line('auth_message_password_changed'));
            } 
            else
            { // fail
                $errors = $this->tank_auth->get_error_message();
                foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
            }
        }
        $this->load->view('auth/change_password_form', $data);
    }
}
/**
 * Change user email
 *
 * @return void
 */
function change_email() 
{
    if (!$this->tank_auth->is_logged_in()) 
    { // not logged in or not activated
        redirect('painel');
    } 
    else
    {
        $this->form_validation->set_rules('password', 'Password', 'trim|required');
        $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
        
        $data['errors'] = array();
        
        if ($this->form_validation->run()) 
        { // validation ok
            if (!is_null($data = $this->tank_auth->set_new_email($this->form_validation->set_value('email') , $this->form_validation->set_value('password')))) 
            { // success
                
                $data['site_name'] = $this->config->item('website_name', 'tank_auth');
                // Send email with new email address and its activation link
                $this->_send_email('change_email', $data['new_email'], $data);
                
                $this->_show_message(sprintf($this->lang->line('auth_message_new_email_sent') , $data['new_email']));
            } 
            else
            {
                $errors = $this->tank_auth->get_error_message();
                foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
            }
        }
        $this->load->view('auth/change_email_form', $data);
    }
}
/**
 * Replace user email with a new one.
 * User is verified by user_id and authentication code in the URL.
 * Can be called by clicking on link in mail.
 *
 * @return void
 */
function reset_email() 
{
    $user_id = $this->uri->segment(3);
    $new_email_key = $this->uri->segment(4);
    // Reset email
    if ($this->tank_auth->activate_new_email($user_id, $new_email_key)) 
    { // success
        $this->tank_auth->logout();
        $this->_show_message($this->lang->line('auth_message_new_email_activated') . ' ' . anchor('/auth/login/', 'Login'));
    } 
    else
    { // fail
        $this->_show_message($this->lang->line('auth_message_new_email_failed'));
    }
}
/**
 * Delete user from the site (only when user is logged in)
 *
 * @return void
 */
function unregister() 
{
    if (!$this->tank_auth->is_logged_in()) 
    { // not logged in or not activated
        redirect('/auth/login/');
    } 
    else
    {
        $this->form_validation->set_rules('password', 'Password', 'trim|required');
        
        $data['errors'] = array();
        
        if ($this->form_validation->run()) 
        { // validation ok
            if ($this->tank_auth->delete_user($this->form_validation->set_value('password'))) 
            { // success
                $this->_show_message($this->lang->line('auth_message_unregistered'));
            } 
            else
            { // fail
                $errors = $this->tank_auth->get_error_message();
                foreach ($errors as $k => $v) $data['errors'][$k] = $this->lang->line($v);
            }
        }
        $this->load->view('auth/unregister_form', $data);
    }
}
/**
 * Show info message
 *
 * @param	string
 * @return	void
 */
function _show_message($message) 
{
    $this->session->set_flashdata('message', $message);
    redirect('/auth/');
}
/**
 * Send email message of given type (activate, forgot_password, etc.)
 *
 * @param	string
 * @param	string
 * @param	array
 * @return	void
 */
function _send_email($type, $email, &$data) 
{
    $this->load->library('email');
    $this->email->from($this->config->item('webmaster_email', 'tank_auth') , $this->config->item('website_name', 'tank_auth'));
    $this->email->reply_to($this->config->item('webmaster_email', 'tank_auth') , $this->config->item('website_name', 'tank_auth'));
    $this->email->to($email);
    $this->email->subject(sprintf($this->lang->line('auth_subject_' . $type) , $this->config->item('website_name', 'tank_auth')));
    $this->email->message($this->load->view('email/' . $type . '-html', $data, TRUE));
    $this->email->set_alt_message($this->load->view('email/' . $type . '-txt', $data, TRUE));
    $this->email->send();
}
/**
 * Create CAPTCHA image to verify user as a human
 *
 * @return	string
 */
function _create_captcha() 
{
    $this->load->helper('captcha');
    
    $cap = create_captcha(array(
        'img_path' => './' . $this->config->item('captcha_path', 'tank_auth') ,
        'img_url' => base_url() . $this->config->item('captcha_path', 'tank_auth') ,
        'font_path' => './' . $this->config->item('captcha_fonts_path', 'tank_auth') ,
        'font_size' => $this->config->item('captcha_font_size', 'tank_auth') ,
        'img_width' => $this->config->item('captcha_width', 'tank_auth') ,
        'img_height' => $this->config->item('captcha_height', 'tank_auth') ,
        'show_grid' => $this->config->item('captcha_grid', 'tank_auth') ,
        'expiration' => $this->config->item('captcha_expire', 'tank_auth') ,
    ));
    // Save captcha params in session
    $this->session->set_flashdata(array(
        'captcha_word' => $cap['word'],
        'captcha_time' => $cap['time'],
    ));
    
    return $cap['image'];
}
/**
 * Callback function. Check if CAPTCHA test is passed.
 *
 * @param	string
 * @return	bool
 */
function _check_captcha($code) 
{
    $time = $this->session->flashdata('captcha_time');
    $word = $this->session->flashdata('captcha_word');
    
    list($usec, $sec) = explode(" ", microtime());
    $now = ((float)$usec + (float)$sec);
    
    if ($now - $time > $this->config->item('captcha_expire', 'tank_auth')) 
    {
        $this->form_validation->set_message('_check_captcha', $this->lang->line('auth_captcha_expired'));
        return FALSE;
    } 
    elseif (($this->config->item('captcha_case_sensitive', 'tank_auth') AND $code != $word) OR strtolower($code) != strtolower($word)) 
    {
        $this->form_validation->set_message('_check_captcha', $this->lang->line('auth_incorrect_captcha'));
        return FALSE;
    }
    return TRUE;
}
/**
 * Create reCAPTCHA JS and non-JS HTML to verify user as a human
 *
 * @return	string
 */
function _create_recaptcha() 
{
    $this->load->helper('recaptcha');
    // Add custom theme so we can get only image
    $options = "<script>var RecaptchaOptions = {theme: 'custom', custom_theme_widget: 'recaptcha_widget'};</script>\n";
    // Get reCAPTCHA JS and non-JS HTML
    $html = recaptcha_get_html($this->config->item('recaptcha_public_key', 'tank_auth'));
    
    return $options . $html;
}
/**
 * Callback function. Check if reCAPTCHA test is passed.
 *
 * @return	bool
 */
function _check_recaptcha() 
{
    $this->load->helper('recaptcha');
    
    $resp = recaptcha_check_answer($this->config->item('recaptcha_private_key', 'tank_auth') , $_SERVER['REMOTE_ADDR'], $_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
    
    if (!$resp->is_valid) 
    {
        $this->form_validation->set_message('_check_recaptcha', $this->lang->line('auth_incorrect_captcha'));
        return FALSE;
    }
    return TRUE;
}
}
/* End of file auth.php */
/* Location: ./application/controllers/auth.php */