/controller/UserController.php
PHP | 247 lines | 209 code | 20 blank | 18 comment | 42 complexity | 97e599b4f27670abcf38953bb8bd7d64 MD5 | raw file
- <?php
- require_once './Controller.php';
- require_once '../model/Contact.php';
- require_once './ExceptionController.php';
- require_once '../model/Config.php';
- class UserController extends Controller {
- const ERROR_CODE_PREFIX = '11';
- const URL_CONTROL_PANEL = '../view/control_panel.php';
- const URL_REQUEST_ACTIVE = '../view/activate_account.php';
- const URL_RESEARCH = '/dictionary/view/result_of_research.php';
- const URL_PROFILE = '../view/profile.php';
- protected $user;
- protected $contact;
- public function __construct() {
- parent::__construct();
- try {
- $this->user = new User();
- $this->contact = new Contact();
- switch ($_SERVER['REQUEST_METHOD']) {
- case "POST":
- var_dump($_POST);
- switch ($_POST['option']) {
- case 'new_user':
- $this->newUser();
- break;
- case 'edit':
- $this->editUser();
- break;
- case 'login':
- $login = $_POST['login'];
- $password = md5($_POST['password']);
- $this->login($login, $password);
- break;
- case 'request_password':
- $email = $_POST['email'];
- $this->requestPassword($email);
- break;
- default:
- break;
- }
- exit();
- case "GET":
- if (!empty($_GET['option']) && $_GET['option'] == 'logout') {
- self::logout();
- }
- exit();
- default :
- throw new ExceptionController('Método não suportado!', self::ERROR_CODE_PREFIX . ExceptionController::INVALID_OPTION, NULL);
- }
- } catch (Exception $e) {
- if ($e instanceof ExceptionController || $e instanceof CrudException) {
- $_SESSION['error_code'] = $e->getCode();
- $_SESSION['error_message'] = $e->getMessage();
- if (empty($_SERVER['HTTP_REFERER'])) {
- header("Location: " . ExceptionController::PATH_ERROR_PAGE);
- } else {
- header("Location: {$_SERVER['HTTP_REFERER']}");
- }
- } else {
- ExceptionController::handleException($e);
- }
- }
- }
- private function newUser() {
- $this->user->name = $this->validateName($_POST['name']);
- $this->user->email = $this->validateEmail($_POST['email']);
- $this->user->password = $this->validatePassword($_POST['password'], $_POST['re_password']);
- $this->user->id_city = $_POST['id_city'];
- $this->user->id_user = $this->user->create();
- if ($this->user->id_user > 0) {
- self::setSession($this->user->cpf, $this->user->password, $this->user->email);
- header('location: ' . self::URL_CONTROL_PANEL);
- } else {
- throw new ExceptionController('Não foi possível registrar sua conta, verifique se as informações foram digitadas corretamente!', self::ERROR_CODE_PREFIX . '80');
- }
- }
- private function editUser() {
- $this->requireUserSession();
- $this->_currentUser->name = $this->validateName($_POST['name']);
- // $this->_currentUser->email = $this->validateEmail($_POST['email']);
- $this->_currentUser->mother_name = $this->validateName($_POST['mothername']);
- if (!empty($_POST['new_password'])) {
- $this->_currentUser->password = $this->validatePassword($_POST['new_password'], $_POST['re_password']);
- }
- $this->_currentUser->cpf = Validate::cpf($_POST['cpf']);
- $this->_currentUser->institution = $_POST['institution'];
- $this->_currentUser->active = 1;
- $this->_currentUser->dt_born = Validate::formatDateFromPtBr($_POST['dt_born']);
- $this->_currentUser->rg = $_POST['rg'];
- $this->_currentUser->phone = $_POST['phone'];
- $this->_currentUser->cellfone = $_POST['cellfone'];
- $this->_currentUser->adress = $_POST['adress'];
- $this->_currentUser->number = $_POST['number'];
- $this->_currentUser->postal_code = Validate::cep($_POST['postal_code']);
- $this->_currentUser->district = $_POST['district'];
- if (!$this->_currentUser->update(array('id_user' => $this->_currentUser->id_user)) > 0) {
- throw new ExceptionController('Não foi possível atualizar seu perfil', self::ERROR_CODE_PREFIX . ExceptionController::FAIL_UPDATE);
- } else {
- $_SESSION['sucess'] = 'Perfil atualizado com sucesso.';
- header("Location: " . self::URL_PROFILE);
- }
- }
- protected static function setSession($password, $email = NULL) {
- /**
- * Método que cria sessão de email e senha do usuário corrente, caso ele seja validado
- * @param String $email Email do usuário corrente
- * @param String $password Senha do usuário corrente criptografada
- *
- * */
- $_SESSION['email'] = $email; //setando email
- $_SESSION['password'] = $password; //setando senha
- $_SESSION['type_user'] = 0;
- }
- private function login($login, $password) {
- /**
- * Método que valida o login do usuário recebendo por parâmetro email e senha
- *
- * @param String $email Email do usuário corrente
- * @param String $password Senha do usuário corrente criptografada
- *
- * */
- $validate = new Validate();
- if ($validate->validateEmail($login)) {
- if ($this->user->validateUser($login, $password)) { //realiza validação do usuário buscando dados no banco
- $object_user = $this->user->retriveUser($login);
- self::setSession($password, $object_user->email); //chama método estático setSession
- } else {
- throw new ExceptionController('Usuário Inválido.', self::ERROR_CODE_PREFIX . '03');
- }
- } else {
- throw new ExceptionController('Usuário inválido.', self::ERROR_CODE_PREFIX . '04');
- }
- if (isset($_POST['redirect'])) {
- header("Location: " . $_POST['redirect'] . ($_POST['redirect'] == self::URL_RESEARCH ? '?register' : ''));
- } else {
- header("Location: " . self::URL_CONTROL_PANEL);
- }
- }
- public function requestPassword($email) {
- $user = $this->user->retriveUser($_POST['email']);
- if (count($user) > 0) {
- $new_password = substr(md5(uniqid()), 0, 5);
- $this->contact->email = $email;
- $this->resetPassword($user->id_user, $new_password);
- $this->contact->subject = "Nova Senha - Inventum";
- $this->sendEmail($this->contact->email, $user->name, $this->contact->subject, $new_password);
- header("Location: ../view/index.php");
- } else {
- throw new ExceptionController('Email Inválido.', self::ERROR_CODE_PREFIX . '03');
- }
- }
- public function resetPassword($id_user, $password) {
- if ($this->user->updatePassword(md5($password), $id_user)) {
- $_SESSION['sucess'] = "Senha modificada com sucesso.";
- } else {
- throw new ExceptionController($this->getErrorMessage('09'), self::ERROR_CODE_PREFIX . '01');
- ob_end_flush();
- }
- }
- private function sendEmail($to, $name, $subject, $password) {
- $email = new Email();
- $this->contact->content = $email->generateEmail(Email::TYPE_REQUEST_PASSWORD, $name, $password);
- $res = $this->contact->create(array('id_contact' => $this->contact->id_contact));
- $email->sendRequestEmail($to, $subject, $this->contact->content);
- return TRUE;
- }
- public static function logout() {
- /**
- * Método logout para deslogar o usuário
- * */
- session_start(); //inicia session
- $_SESSION = array(); //atribue um array vazio para a sessão
- session_destroy(); // destrói a sessão
- header("Location: ../view/index.php"); //redireciona para o login
- ob_end_flush();
- }
- // =========================================================================
- private function validateEmail($email) {
- $validate = new Validate();
- if ($validate->validateEmail($email)) {
- if (!$this->user->searchValue('email', $email, $this->user->id_user)) {
- return strtolower($email);
- } else {
- throw new ExceptionController('Email já cadastrado', 1101);
- }
- } else {
- throw new ExceptionController('Email inválido', self::ERROR_CODE_PREFIX . ExceptionController::INVALID_EMAIL);
- }
- }
- private function validateName($name) {
- $validate = new Validate();
- if (stripos($name, " ")) {
- if ($validate->validateField($name, 100, 2) && $validate->getWordsNumber($name > 1)) {
- return ucwords(strtolower($name));
- } else {
- throw new ExceptionController('Nome Inválido', self::ERROR_CODE_PREFIX . ExceptionController::INVALID_USER_NAME);
- }
- } else {
- throw new ExceptionController('Informe o nome completo, seu e de sua mãe', self::ERROR_CODE_PREFIX . ExceptionController::INVALID_USER_NAME);
- }
- }
- private function validateCpf($cpf) {
- $validate = new Validate();
- $cpf = str_replace(array('.', '-'), '', $cpf);
- if ($validate->validateCpf($cpf)) {
- if (!$this->user->searchValue('cpf', $cpf, $this->user->id_user)) {
- return $cpf;
- } else {
- throw new ExceptionController('CPF já cadastrado', 1101);
- }
- } else {
- throw new ExceptionController('CPF inválido', self::ERROR_CODE_PREFIX . ExceptionController::INVALID_EMAIL);
- }
- }
- private function formatDate($date) {
- $date = str_replace('/', '-', $date);
- return date('Y-m-d', strtotime($date));
- }
- private function validatePassword($pass, $rePass) {
- if (md5($pass) == md5($rePass)) {
- return md5($pass);
- } else {
- throw new ExceptionController('As senhas digitadas não correspondem', self::ERROR_CODE_PREFIX . '06');
- }
- }
- }
- new UserController();