From 5491fae9f0cd4e38a72d791128109515a57a3865 Mon Sep 17 00:00:00 2001 From: Felipe Guaycuru Date: Fri, 14 Apr 2017 17:02:20 -0300 Subject: [PATCH] Cadastro funcionando e outros fixes --- .htaccess | 2 + ajax/cadastro.php | 126 +++++++++ ajax/{editar.php => editar-perfil.php} | 7 +- ajax/{excluir_conta.php => excluir-conta.php} | 0 ajax/login.php | 12 +- classes/GDE/Aluno.inc.php | 10 + classes/GDE/Base.inc.php | 2 +- classes/GDE/Curso.inc.php | 10 +- classes/GDE/Professor.inc.php | 46 ++++ classes/GDE/Usuario.inc.php | 46 ++-- classes/GDE/Util.inc.php | 4 + common/common.inc.php | 4 +- views/cadastro.php | 258 ++++++++++++++++++ views/configuracoes.php | 4 +- views/editar-perfil.php | 2 +- views/login.php | 7 +- views/validar-email.php | 7 +- web/js/gde.42.js | 17 +- 18 files changed, 524 insertions(+), 40 deletions(-) create mode 100644 ajax/cadastro.php rename ajax/{editar.php => editar-perfil.php} (93%) rename ajax/{excluir_conta.php => excluir-conta.php} (100%) create mode 100644 views/cadastro.php diff --git a/.htaccess b/.htaccess index 8b0c986..d3ca113 100644 --- a/.htaccess +++ b/.htaccess @@ -65,3 +65,5 @@ RewriteRule ^visoes/Sala\.php$ %{ENV:BASE}sala/ [R=302,L,QSA] RewriteRule ^visoes/Sobre\.php$ %{ENV:BASE}sobre/ [R=302,L,QSA] RewriteRule ^visoes/Termos\.php$ %{ENV:BASE}termos/ [R=302,L,QSA] RewriteRule ^visoes/ValidaEmail\.php$ %{ENV:BASE}validar-email/ [R=302,L,QSA] +RewriteRule ^visoes/VisaoCadastro\.php$ %{ENV:BASE}cadastro/ [R=302,L,QSA] +RewriteRule ^visoes/VisaoLogin\.php$ %{ENV:BASE}login/ [R=302,L,QSA] diff --git a/ajax/cadastro.php b/ajax/cadastro.php new file mode 100644 index 0000000..c333884 --- /dev/null +++ b/ajax/cadastro.php @@ -0,0 +1,126 @@ +setSenha($_POST['senha']); + unset($_SESSION['trocar_senha']); + if($Usuario->Save(true) !== false) + Base::OK_JSON($_POST['token']); + else + Base::Error_JSON("Um erro ocorreu. Por favor, tente novamente mais tarde."); + } else { + if(Usuario::Por_Unique($identificador, $campo, true) !== null) + Base::OK_JSON($_POST['token']); + else { + $Ja_tem = Usuario::Por_Unique($identificador, $campo); + if($Ja_tem === null) + $Usuario = new Usuario(); + else + $Usuario = $Ja_tem; + if($Ja_tem === null) + $Usuario->setLogin($_POST['login']); + if(strlen($_POST['senha']) < 3) + Base::Error_JSON("A senha precisa ter no mínimo 3 caracteres."); + if((empty($_POST['email'])) || (Util::Validar_Email($_POST['email']) === false)) + Base::Error_JSON("Favor informar um email válido."); + elseif(Usuario::Por_Unique($_POST['email'], 'email') !== null) + Base::Error_JSON("Já existe um usuário cadastrado com o email informado."); + $Usuario->setSenha($_POST['senha']); + $Usuario->setEmail($_POST['email']); + $Usuario->setNome($_POST['nome']); + $Usuario->setSobrenome($_POST['sobrenome']); + if(!empty($_POST['ingresso'])) + $Usuario->setIngresso(intval($_POST['ingresso'])); + if(($tipo == 'A') && (!empty($_POST['curso']))) { + $Curso = Curso::Por_Numero($_POST['curso']); + if($Curso === null) + Base::Error_JSON('Curso de graduação não encontrado!'); + $Usuario->setCurso($Curso); + if(!empty($_POST['catalogo'])) + $Usuario->setCatalogo(intval($_POST['catalogo'])); + if(!empty($_POST['modalidade'])) + $Modalidade = Modalidade::Por_Curso_Sigla_Catalogo($Curso->getNumero(false), $_POST['modalidade'], array('G', 'T'), $_POST['catalogo']); + else + $Modalidade = null; + $Usuario->setModalidade($Modalidade); + } + if($Ja_tem === null) + $Usuario->setData_Cadastro(); + $Usuario->setAtivo(true); + if($tipo == 'A') { + $Aluno = Aluno::Por_RA($identificador); + if($Aluno === null) { + $Aluno = new Aluno(); + $Aluno->setRA($identificador); + $Aluno->setNome($Usuario->getNome_Completo(false)); + $Aluno->setNivel((!empty($_POST['nivel'])) ? $_POST['nivel'][0] : null); + $Aluno->setCurso($Usuario->getCurso(false)); + if($Usuario->getModalidade(false) !== null) + $Aluno->setModalidade($Usuario->getModalidade(true)->getSigla(false)); + if(!empty($_POST['curso_pos'])) { + $Curso_Pos = Curso::Por_Numero($_POST['curso_pos'], Curso::NIVEIS_POS); + if($Curso_Pos === null) + Base::Error_JSON('Curso de pós-graduação não encontrado!'); + $Aluno->setCurso_Pos($Curso_Pos); + $Aluno->setNivel_Pos((!empty($_POST['nivel_pos'])) ? $_POST['nivel_pos'][0] : null); + $Aluno->setModalidade_Pos(($_POST['modalidade_pos'] == "") ? null : strtoupper(substr($_POST['modalidade_pos'], 0, 2))); + } + $Aluno->Save(false); + } + $Usuario->setAluno($Aluno); + } elseif($tipo == 'D') { + $Professor = Professor::Por_Matricula($identificador); + if($Professor === null) { + if(!empty($_POST['id_professor'])) { + $Professor = Professor::Load($_POST['id_professor']); + $Professor->setMatricula($identificador); + } else { + $ST = Professor::Nome_Unico($_POST['professor']); + if($ST !== false) { + $Professor = $ST; + $Professor->setMatricula($identificador); + } else { + $Professor = new Professor(); + $Professor->setMatricula($identificador); + $Professor->setNome($_POST['professor']); + } + } + $Professor->Save(false); + } + $Usuario->setProfessor($Professor); + } + $Usuario->Enviar_Email_Validar(); + if($Usuario->Save(true) !== false) + Base::OK_JSON($_POST['token']); + else + Base::Error_JSON("Um erro ocorreu. Por favor, tente novamente mais tarde."); + //echo "$.guaycuru.confirmacao(\"Seu cadastro foi efetuado com sucesso!
Agora você pode usar o GDE!\", \"../visoes/VisaoLogin.php?token=".$_POST['token']."\");"; + } + } +} diff --git a/ajax/editar.php b/ajax/editar-perfil.php similarity index 93% rename from ajax/editar.php rename to ajax/editar-perfil.php index a33f62c..1a977e1 100644 --- a/ajax/editar.php +++ b/ajax/editar-perfil.php @@ -19,11 +19,16 @@ if(($_POST['senha'] != null) && ($_POST['senha'] != $_POST['conf_senha'])) { Base::Error_JSON('As senhas não conferem!'); } + if((empty($_POST['email'])) || (Util::Validar_Email($_POST['email']) === false)) + Base::Error_JSON("Favor informar um email válido."); if($_Usuario->getEmail() != $_POST['email']) $_Usuario->setEmail_Validado(false); $_Usuario->setEmail($_POST['email']); - if($_POST['senha'] != null) + if(!empty($_POST['senha'])) { + if(strlen($_POST['senha']) < 3) + Base::Error_JSON("A senha precisa ter no mínimo 3 caracteres."); $_Usuario->setSenha($_POST['senha']); + } $_Usuario->setNome($_POST['nome']); $_Usuario->setSobrenome($_POST['sobrenome']); $Curso = Curso::Por_Numero($_POST['curso']); diff --git a/ajax/excluir_conta.php b/ajax/excluir-conta.php similarity index 100% rename from ajax/excluir_conta.php rename to ajax/excluir-conta.php diff --git a/ajax/login.php b/ajax/login.php index d5e9e80..e627e78 100644 --- a/ajax/login.php +++ b/ajax/login.php @@ -20,12 +20,18 @@ else $_Usuario = Usuario::Verificar_Login($_POST['login'], $_POST['senha'], false, $erro); -if($_Usuario->getID() != null) { // Login OK +if((is_object($_Usuario)) && ($_Usuario->getID() != null)) { // Login OK Base::OK_JSON(); } else { // Login falhou + $extra = array('destino' => ''); switch($erro) { case Usuario::ERRO_LOGIN_NAO_ENCONTRADO: - $erro = 'Login não encontrado.'; + if(!empty($_POST['token'])) { + $erro = 'Login não encontrado. Por favor, efetue seu cadastro.'; + $extra['destino'] = CONFIG_URL . 'cadastro/?token=' . urlencode($_POST['token']); + } else { + $erro = 'Login não encontrado.'; + } break; case Usuario::ERRO_LOGIN_SENHA_INCORRETA: $erro = 'Login ou senha incorretos.'; @@ -40,5 +46,5 @@ $erro = 'Erro desconhecido.'; break; } - Base::Error_JSON($erro); + Base::Error_JSON($erro, 200, $extra); } diff --git a/classes/GDE/Aluno.inc.php b/classes/GDE/Aluno.inc.php index a827d46..23de10e 100644 --- a/classes/GDE/Aluno.inc.php +++ b/classes/GDE/Aluno.inc.php @@ -104,6 +104,8 @@ class Aluno extends Base { /** * @var string * + * Nao podemos utilizar uma Relation com Modalidade pois Aluno nao tem Catalogo + * * @ORM\Column(type="string", length=16, nullable=true) */ protected $modalidade_pos; @@ -158,6 +160,14 @@ public static function Listar_Niveis_Pos() { return self::$_niveis_pos; } + /** + * @param $ra + * @return Aluno|null|false + */ + public static function Por_RA($ra) { + return self::FindOneBy(array('ra' => $ra)); + } + /** * Consultar * diff --git a/classes/GDE/Base.inc.php b/classes/GDE/Base.inc.php index 074cef1..7d852c4 100644 --- a/classes/GDE/Base.inc.php +++ b/classes/GDE/Base.inc.php @@ -216,7 +216,7 @@ public static function FindBy($params = array(), array $order = null, $limit = n * Searches the DB for only one object * * @param array $params Search parameters - * @return mixed Object found, null if not found or false on query error + * @return object|null|false Object found, null if not found or false on query error */ public static function FindOneBy($params) { return self::_EM()->getRepository(get_called_class())->findOneBy($params); diff --git a/classes/GDE/Curso.inc.php b/classes/GDE/Curso.inc.php index 596206a..326a491 100644 --- a/classes/GDE/Curso.inc.php +++ b/classes/GDE/Curso.inc.php @@ -42,16 +42,22 @@ class Curso extends Base { */ protected $nome; + const NIVEIS_GRAD = array('G', 'T'); + const NIVEIS_POS = array('M', 'D'); + /** * Listar * * @param array $niveis + * @param bool $sem_especial * @return ArrayCollection */ - public static function Listar($niveis = array()) { + public static function Listar($niveis = array(), $sem_especial = false) { $dql = 'SELECT C FROM GDE\\Curso C '; if(count($niveis) > 0) $dql .= 'WHERE C.nivel IN (?1) '; + if($sem_especial) + $dql .= 'AND C.numero != 99 '; $dql .= 'ORDER BY C.nome ASC'; $query = self::_EM()->createQuery($dql); if(count($niveis) > 0) @@ -66,7 +72,7 @@ public static function Listar($niveis = array()) { * @param array $niveis * @return self|null */ - public static function Por_Numero($numero, $niveis = array('G', 'T')) { + public static function Por_Numero($numero, $niveis = self::NIVEIS_GRAD) { $dql = 'SELECT C FROM GDE\\Curso C WHERE C.numero = ?1'; if(count($niveis) > 0) $dql .= ' AND C.nivel IN (?2)'; diff --git a/classes/GDE/Professor.inc.php b/classes/GDE/Professor.inc.php index fff8579..3eb7219 100644 --- a/classes/GDE/Professor.inc.php +++ b/classes/GDE/Professor.inc.php @@ -95,6 +95,25 @@ class Professor extends Base { public static $ordens_nome = array('Relevância', 'Nome'); public static $ordens_inte = array('rank', 'P.nome'); + /** + * @param $matricula + * @return Professor|null|false + */ + public static function Por_Matricula($matricula) { + return self::FindOneBy(array('matricula' => $matricula)); + } + + /** + * @param $nome + * @return Professor|false + */ + public static function Nome_Unico($nome) { + $Professores = self::Por_Nome($nome); + if(count($Professores) != 1) + return false; + return $Professores->first(); + } + /** * @param null|string $periodo * @param bool $formatado @@ -130,6 +149,33 @@ public function Monta_Horario($periodo = null) { return $Lista; } + /** + * Por_Nome + * + * @param $nome + * @param null $ordem + * @param null $total + * @param int $limit + * @param int $start + * @return ArrayCollection|Professor[] + */ + public static function Por_Nome($nome, $ordem = null, &$total = null, $limit = -1, $start = -1) { + $param = array(1 => "%".str_replace(' ', '%', $nome)."%"); + if($total !== null) { + $dqlt = "SELECT COUNT(DISTINCT P.id_professor) FROM ".get_class()." AS P WHERE P.nome LIKE ?1"; + $total = self::_EM()->createQuery($dqlt)->setParameters($param)->getSingleScalarResult(); + } + $dql = "SELECT DISTINCT P FROM ".get_class()." AS P WHERE P.nome LIKE ?1"; + if($ordem != null) + $dql .= " ORDER BY ".$ordem; + $query = self::_EM()->createQuery($dql)->setParameters($param); + if($limit > 0) + $query->setMaxResults($limit); + if($start > -1) + $query->setFirstResult($start); + return $query->getResult(); + } + /** * @param $q * @param null $ordem diff --git a/classes/GDE/Usuario.inc.php b/classes/GDE/Usuario.inc.php index 3e87ad0..004a01d 100644 --- a/classes/GDE/Usuario.inc.php +++ b/classes/GDE/Usuario.inc.php @@ -147,13 +147,6 @@ class Usuario extends Base { */ protected $sobrenome; - /** - * @var string - * - * @ORM\Column(type="string", length=255, nullable=true) - */ - protected $nome_completo; - /** * @var string * @@ -564,6 +557,14 @@ public static function Trata_Chat_Status($esta_online, $status, $admin, $puro = return $retorno; } + /** + * @param bool $html + * @return string + */ + public function getNome_Completo($html = false) { + return trim($this->getNome($html).' '.$this->getSobrenome($html)); + } + /** * @param bool $html * @param bool $artigo @@ -654,9 +655,6 @@ public static function getFoto_Padrao($th = false, $url = false) { * @return string A nova senha */ public function setSenha($senha, $codificar = true) { - // ToDo: Move to controller - /*if(($codificar) && (strlen($senha) < 3)) - $this->_Erro(new Erro(get_class(), "senha", "A senha precisa ter no mínimo 3 caracteres."));*/ if($codificar) $senha = self::Codificar_Senha($senha); return parent::setSenha($senha); @@ -799,8 +797,11 @@ public static function Verificar_Login($login, $senha, $lembrar = false, &$erro * @return false|Usuario O Usuario logado (podendo ser vazio ou nao) ou false se o token for invalido */ public static function Efetuar_Login_DAC($token, $verificar_horario = true, &$erro = false) { - if($token == null) + if($token == null) { + if($erro !== false) + $erro = self::ERRO_LOGIN_TOKEN_INVALIDO; return false; + } list($resultado, $matricula, $tipo) = DAC::Validar_Token($token, $verificar_horario); if($resultado === false) { $Usuario = self::Logout(null); @@ -815,10 +816,15 @@ public static function Efetuar_Login_DAC($token, $verificar_horario = true, &$er $Usuario = self::Por_Unique($matricula, 'matricula'); break; default: // Outros (Funcionarios, etc) + if($erro !== false) + $erro = self::ERRO_LOGIN_TOKEN_INVALIDO; return false; } - if($Usuario === null) + if($Usuario === null) { + if($erro !== false) + $erro = self::ERRO_LOGIN_NAO_ENCONTRADO; return false; + } // Salva o cookie do login $Usuario->Salvar_Cookie(false); @@ -1355,14 +1361,22 @@ public function Eliminou(Disciplina $Disciplina, $parcial = false) { return false; } + /** + * @return string + */ + public function Token_Email() { + // ToDo: Nao usar mais sha1 + return sha1($this->login.'GDE'.$this->senha); + } + /** * @return bool */ public function Enviar_Email_Validar() { if($this->getProfessor(false) !== null) - $RA_Matricula = '
  • Matrícula: '.$this->getProfessor()->getMatricula(true).'
  • '; + $RA_Matricula = '
  • Matrícula: '.$this->getProfessor(true)->getMatricula(true).'
  • '; elseif($this->getAluno(false) !== null) - $RA_Matricula = '
  • RA: '.$this->getAluno()->getRA(true).'
  • '; + $RA_Matricula = '
  • RA: '.$this->getAluno(true)->getRA(true).'
  • '; $to = $this->getEmail(false); $subject = 'GDE - Valide seu email'; $message = ' @@ -1391,9 +1405,9 @@ public function Enviar_Email_Validar() {
  • Email: '.$this->getEmail(true).'
  • '.$RA_Matricula.' - Clique aqui para validar seu e-mail. + Clique aqui para validar seu e-mail.

    Se o seu cliente de e-mail não suportar links, copie o endereço abaixo e cole-o na barra de navegação de seu navegador:

    -
    '.CONFIG_URL.'validar-email/?id='.$this->getID().'&token='.$this->getToken().'
    +
    '.CONFIG_URL.'validar-email/?id='.$this->getID().'&token='.$this->Token_Email().'

    Caso não tenha solicitado esse email, por favor desconsidere-o. Provavelmente foi por engano de algum outro usuário.

    Divirta-se!

    Equipe do GDE

    diff --git a/classes/GDE/Util.inc.php b/classes/GDE/Util.inc.php index fb0845c..3f19915 100644 --- a/classes/GDE/Util.inc.php +++ b/classes/GDE/Util.inc.php @@ -73,4 +73,8 @@ public static function Enviar_Email($para, $assunto, $msg, $from = 'GDE 0); + } + } diff --git a/common/common.inc.php b/common/common.inc.php index 572bf93..54e221f 100644 --- a/common/common.inc.php +++ b/common/common.inc.php @@ -144,7 +144,7 @@ if((isset($_SESSION['admin_su'])) && ($_SESSION['admin_su'] !== false)) { ?> var Un_SU = function() { $.guaycuru.abreControlador('ControlAdmin.php?unsu'); -} +}; $(document).ready(function(){ $('body').watcherkeys({callback: $.guaycuru.changeIt}); @@ -171,9 +171,9 @@ }); }); - // ]]> +