Skip to content

Instantly share code, notes, and snippets.

@francisrod01
Created July 11, 2013 01:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save francisrod01/5971795 to your computer and use it in GitHub Desktop.
Save francisrod01/5971795 to your computer and use it in GitHub Desktop.
Foco nesse validaSenha(), veja se ele não atrapalha algo. ;)
<?php
// menu lateral
echo $this->element($pages_dir . '/menu-topo/usuarios');
?>
<div class="users form">
<?php echo $this->Form->create('User', array('type'=>'file')); ?>
<fieldset>
<legend><?php __('Adicionar Usu&aacute;rio'); ?></legend>
<?php
echo $this->Form->input('group_id', array(
'label'=>__('Grupo', true), 'empty'=>__('-- Selecione uma op&ccedil;&atilde;o --', true),
'escape'=>false
));
echo $this->Form->input('UserPerfil.nome');
echo $this->FormEscape->input('UserPerfil.url_rewrite', array('label'=>__('Url curta', true)));
echo $this->Form->input('UserPerfil.sexo', array(
'options' => array(
'f' => __('Feminino', true),
'm' => __('Masculino', true)
),
'type' => 'radio'
));
echo $this->FormEscape->input('email');
echo $this->Form->input('_pwd', array(
'label'=>__('Senha', true), 'type'=>'password',
'autocomplete'=> 'off'
));
echo $this->Form->input('UserPerfil.endereco', array('label'=>__('Endere&ccedil;o', true)));
echo $this->Form->input('UserPerfil.numero', array('label'=>__('N&uacute;mero', true)));
echo $this->Form->input('UserPerfil.complemento');
echo $this->Form->input('UserPerfil.cidade_id');
echo $this->Form->input('UserPerfil.cep');
echo $this->Form->input('active', array(
'label'=>__('Ativo', true), 'type'=>'checkbox'
));
?>
</fieldset>
<?php echo $this->Form->end(__('Salvar', true)); ?>
</div>
<?php
// menu lateral
echo $this->element($pages_dir . '/menu-lateral/menu');
?>
<?php
class User extends AppModel {
var $name = 'User';
var $validate = array(
'group_id' => array(
'notempty' => array(
'rule' => array('notempty'),
//'message' => 'Your custom message here',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'email' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Informe seu E-mail',
//'allowEmpty' => false,
//'required' => false,
'last' => true, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
'email' => array(
'rule' => array('email'),
'message' => 'Este e-mail &eacute; inv&aacute;lido',
//'allowEmpty' => false,
//'required' => false,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
),
),
'_pwd' => array(
'notempty' => array(
'rule' => array('notempty'),
'message' => 'Informe sua senha',
//'allowEmpty' => false,
//'required' => false,
'last' => true, // Stop validation after this rule
'on' => 'create', // Limit validation to 'create' or 'update' operations
),
'between' => array(
'rule' => array('between', 5, 20),
'message' => 'A senha deve estar entre 5 e 20 caracteres',
//'allowEmpty' => false,
//'required' => true,
//'last' => false, // Stop validation after this rule
//'on' => 'create', // Limit validation to 'create' or 'update' operations
)
),
'confirm_pass' => array(
'person' => array(
'rule' => array('validaSenha'),
'message' => 'A confirma&ccedil;&atilde;o de senha precisa ser igual a senha'
),
)
);
// The Associations below have been created with all possible keys, those that are not needed can be removed
var $belongsTo = array(
'Group' => array(
'className' => 'Group',
'foreignKey' => 'group_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
var $hasOne = array(
'UserPerfil' => array(
'className' => 'UserPerfil',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
);
var $hasMany = array( 'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'NoticiaComentario' => array(
'className' => 'NoticiaComentario',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'NoticiaDepoimento' => array(
'className' => 'NoticiaDepoimento',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'AgenciaPacoteComentario' => array(
'className' => 'AgenciaPacoteComentario',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'AgenciaPacoteDepoimento' => array(
'className' => 'AgenciaPacoteDepoimento',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'UserAccount' => array(
'className' => 'UserAccount',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'UserAccess' => array(
'className' => 'UserAccess',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
),
'UserChave' => array(
'className' => 'UserChave',
'foreignKey' => 'user_id',
'dependent' => false,
'conditions' => '',
'fields' => '',
'order' => '',
'limit' => '',
'offset' => '',
'exclusive' => '',
'finderQuery' => '',
'counterQuery' => ''
)
);
/**
* @todo Custom functions
*/
function validateUser($data) {
$return = FALSE;
$conditions = array(
'User.email' => $data['User']['email'],
'User.pwd' => $data['User']['pwd'],
'User.active' => 1
);
$user = $this->find(
'first', array('conditions' => $conditions)
);
if (!empty($user)) {
$return = $user;
}
return $return;
}
function validaSenha() {
if ($this->data[$this->name]['_pwd'] === $this->data[$this->name]['confirm_pass']) {
return true;
}
else {
return false;
}
}
/**
* Define os Behaviors utilizados pelo Model
*
* @var array
* @access public
* @link http://book.cakephp.org/pt/view/1072/Usando-Behaviors
*/
var $actsAs = array(
'acl' => array(
'requester'
)
);
/**
* Parent Node
*
* Função que pega o registro "Pai" do usuário atual
*
* @return array
* @access public
*/
function parentNode() {
if (!$this->id && empty($this->data)) {
return null;
}
//$data = $this->data;
//if (empty($this->data)) {
$data = $this->read();
//}
if (!$data['User']['group_id']) {
return null;
}
else {
return array('Group' => array('id' => $data['User']['group_id']));
}
}
/**
* After Save
*
* Função de callback após salvar o registro
*
* @param boolean $created Será true se for um novo registro
* @return void
* @access public
* @link http://book.cakephp.org/pt/view/1053/afterSave
*/
function afterSave($created) {
$parent = $this->parentNode();
$parent = $this->node($parent);
$node = $this->node();
$aro = $node[0];
$aro['Aro']['parent_id'] = $parent[0]['Aro']['id'];
$aro['Aro']['alias'] = $this->data['User']['email'];
$this->Aro->save($aro);
}
}
<?php
class UsersController extends AppController {
var $name = 'Users';
var $helpers = array(
'Html', 'Form', 'Javascript', 'FormatNumber', 'FormEscape', 'Date', 'Youtube', 'Facebook'
);
var $components = array(
'TinyValue', 'FormatNumber', 'qqFileUploader', 'Youtube', 'Facebook',
'CheckField', 'SwiftMailer', 'Mailer'
);
function beforeFilter() {
parent::beforeFilter();
// Se nao for usuario redireciona para a pagina principal de admin
if ($this->Session->read('Auth')) {
if ($this->user_data_group_id !== 1 AND $this->user_data_group_id !== 3) {
$this->Session->setFlash(array(
'message' => __('Somente Usu&aacute;rios podem acessar este conte&uacute;do', true),
'default',
'class' => 'message-error'
));
$this->redirect('/admin');
}
}
$users = $this->User->find('all', array(
'conditions' => array('User.tinyparam' => "")
));
if (isset($users[0])) {
foreach ($users as $user) {
$userId = $user['User']['id'];
$tinyparam = $this->TinyValue->generateHash(12, 'lower');
$tinyparam = $userId . $tinyparam;
$this->User->query("UPDATE users SET tinyparam = '$tinyparam' WHERE id = $userId");
}
}
if (!isset($this->params['prefix'])) {
$this->layout = $this->folder_layout . '/painel_usuario';
}
}
/**
* @todo Private Actions
*/
// Apos carregar a action responsavel
function _afterRender() {
$this->render('/' . $this->folder_view . '/' . $this->params['controller'] . '/' . $this->params['action']);
}
function _sendEmail($subject, $name, $email, $message) {
$this->Mailer->to = "<$email>";
$this->Mailer->subject = $subject;
$title_for_layout = $this->project_name . ' &raquo; ' . $subject;
$message_view = $message;
$this->set(compact('title_for_layout', 'message_view'));
$this->Mailer->template = 'contact';
$this->Mailer->layout = 'simple_mail';
if (!$this->Mailer->send()) {
$this->log(
$this->Mailer->subject . ' -> Name: ' . $name .
' | E-posta: ' . $email .
' | Message: '. $message .
' | smtp error: '. serialize($this->Mailer->smtpError)
);
}
return $this->Mailer->smtpError ? false : true;
}
/**
* @todo Public actions
*/
function login() {
// O Auth Component se encarrega de fazer tudo sozinho.
if ($this->Session->read('Auth.User')) {
$session_auth = $this->Session->read('Auth');
$UserId = $session_auth['User']['id'];
$groupId = $session_auth['User']['group_id'];
$this->User->id = $UserId;
$this->User->saveField('last_login', date('Y-m-d H:i:s'));
// Searching other's data
$this->User->UserPerfil->unbindModel(array('belongsTo' => array('User')));
$dataProfile = $this->User->UserPerfil->findById($UserId);
$this->Session->write('Auth.UserPerfil', $dataProfile['UserPerfil']);
// Saving Cookie from User
$this->Cookie->path = Configure::read('FOLDER_PATH') . DS . 'sessions';
$this->Cookie->write('User.GroupId', $groupId);
$this->Cookie->write('User.Id', $UserId);
$this->redirect($this->Auth->redirect());
}
$this->_afterRender();
}
function logout() {
// Global Admin, Editors, Agency, Hostel Profile session
if ($this->Session->read('Auth')) {
$this->Session->delete('Auth');
if ($this->Cookie->read('Auth')) {
$this->Cookie->delete('Auth');
}
$this->Session->setFlash(__('Sua sessão foi encerrada.', true));
$this->redirect($this->Auth->logout());
}
// User Profile session
if ($this->Session->read('sessionProfile')) {
$this->Session->delete('sessionProfile');
if ($this->Cookie->read('sessionProfile')) {
$this->Cookie->delete('sessionProfile');
}
$this->Session->setFlash(__('Sua sessão foi encerrada.', true));
$this->redirect(array('controller' => 'users', 'action' => 'acessar'));
}
}
/*
* @todo Painel de usuario (fora do admin)
*/
function confirm($param = null) {
$user = $this->User->findByParam($param);
if (!$param OR empty($user)) {
$this->Session->setFlash(
__('Esta conta n&atilde;o foi encontrada', true),
'default', array('class' => 'flash_bad')
);
$this->redirect(array('action' => 'login'));
}
if ($user['User']['active'] === '1') {
$this->Session->setFlash(
__('Esta conta j&aacute; se encontra ativa', true),
'default', array('class' => 'flash_bad')
);
$this->redirect(array('action' => 'login'));
}
else {
$this->User->id = $user['User']['id'];
$this->User->saveField('active', 1);
$this->User->saveField('last_access', date('Y-m-d H:i:s'));
$this->Session->write('User', $user);
$this->Session->setFlash(
__('Conta confirmada com sucesso!', true),
'default', array('class' => 'flash_good')
);
// Joga para redirecionar para o painel correto
$this->_checkPathAccess($user);
}
}
function email_available() {
# Caso a requisição for AJAX
if ($this->RequestHandler->isAjax()) {
$this->autoRender = false;
$this->layout = 'ajax';
# Define debug como 0 para retornar o json
Configure::write('debug', 0);
$email = $this->data['User']['email'];
if (empty($email)) {
echo __('Informe um e-mail v&aacute;lido', true);
exit;
}
if ($this->CheckField->validateEmail($email) === false) {
echo __('Informe um E-mail v&aacute;lido!', true);
exit;
}
if ($this->CheckField->customCheckDnsrr($email, 'MX') === false) {
echo __('O e-mail informado n&atilde;o existe!', true);
exit;
}
// Find by user
$user = $this->User->findByUsrEmail($email);
if (!empty($user)) {
echo __('Este email j&aacute; est&aacute; em uso', true);
}
else {
echo 1;
}
}
}
function endereco_cep() {
// Recupera o cep informado no formulario
$cep_num = $this->data['User']['zip_code'];
// Busca o logradouro e bairro_id na tabela enderecos
$logradouro = $this->Endereco->find('first', array(
'conditions' => array('Endereco.cep' => $cep_num),
'fields' => array('Endereco.logradouro', 'Endereco.bairro_id')
));
// Armazena o numero do cep no array cep
$cep['Cep']['numero'] = $cep_num;
// Guarda o logradouro recuperado da tabela enderecos
$endereco = $logradouro['Endereco']['logradouro'];
// Guarda o bairro_id recuperado da tabela enderecos
$bairro = $logradouro['Endereco']['bairro_id'];
// Busca o nome do bairro e cidade_id na tabela bairros
$bairro = $this->Bairro->find('first',
array(
'conditions' => array('Bairro.id' => $bairro),
'recursive' => -1, // Para nao retornar os relacionamentos de bairros
'fields' => array('Bairro.descricao', 'Bairro.cidade_id')
)
);
$cidade = $bairro['Bairro']['cidade_id']; // Guarda o cidade_id recuperado da tabela bairros
// Busca o nome da cidade e estado_id na tabela cidades
$cidade = $this->Cidade->find('first',
array(
'conditions'=>array('Cidade.id' => $cidade),
'recursive'=>-1, // Para nao retornar os relacionamentos de cidades
'fields'=>array('Cidade.cidade', 'Cidade.estado_id')
)
);
$estado = $cidade['Cidade']['estado_id']; // Guarda estado_id recuperado da tabela cidades
/*
* Busca o nome do estado e pais_id na tabela estados
* Nota: So existem os estados brasileiros no sql que disponibilizei
*/
$estado = $this->Estado->find('first',
array(
'conditions'=>array('Estado.id' => $estado),
'recursive' => -1, // Para nao retornar os relacionamentos de estados
'fields' => array('Estado.estado', 'Estado.paise_id')
)
);
$pais = $estado['Estado']['paise_id']; // Guarda o pais_id recuperado da tabela estados
// Busca o nome do pais na tabela paises
$pais = $this->Paise->find('first',
array(
'conditions'=>array('Paise.id' => $pais),
'recursive'=>-1, // Para nao retornar os relacionamentos de paises
'fields' => array('Paise.nome')
)
);
/*
* Monta um array de endereco com os dados recolhidos anteriormente das tabelas
* e seta o array para ser utilizado na view
*/
$endereco = Set::merge($cep, $logradouro, $bairro, $cidade, $estado, $pais);
$this->set('address', $endereco);
}
function forgot() {
if (!empty($this->data)) {
$email = $this->data['User']['email'];
if (empty($email)) {
$this->Session->setFlash(
__('Para come&ccedil;ar &eacute; preciso informar seu e-mail', true),
'default', array('class' => 'flash_bad')
);
}
else if ($this->CheckField->validateEmail($email) === false) {
$this->Session->setFlash(
__('Informe um E-mail v&aacute;lido', true),
'default', array('class' => 'flash_bad')
);
}
else {
// Find by user
$user = $this->User->findByUsrEmail($email);
if (empty($user)) {
$this->Session->setFlash(
__('Esta conta de usu&aacute;rio n&atilde;o est&aacute; cadastrada', true),
'default', array('class' => 'flash_bad')
);
$this->redirect(array('action' => 'forgot'));
}
else {
$this->loadModel('Forgot');
$findForgot = $this->Forgot->findByUserId($user['User']['id']);
if (!empty($findForgot)) {
$this->Session->setFlash(
__('Voc&ecirc; j&aacute; solicitou altera&ccedil;&atilde;o de senha', true),
'default', array('class' => 'flash_warning')
);
$this->redirect(array('action' => 'forgot'));
}
else {
# Gerando url para cadastrar nova senha
$f_key = $this->TinyValue->generateHash(16, 'lower');
$this->data['Forgot']['user_id'] = $user['User']['id'];
$this->data['Forgot']['f_key'] = $f_key;
$email = $user['User']['usr_email'];
$link = "http://" . Configure::read('SERVER_NAME') . "/new_pass/" . $f_key;
// MailerComponent
$subject = __('Acesso Facil - Pedido de nova senha', true);
$message =
__('Ol&aacute;', true) .
"<p>" . __('Voc&ecirc; soliticou nova senha no Acesso Facil', true) . "</p>" .
"<p>" . __('Caso n&atilde;o tenha solicitado, apenas ignore este e-mail.', true) . "</p>" .
"<strong>" . __('Dados de usu&aacute;rio', true) . "</strong>" . "<br />" .
"<strong>" . __('E-mail: ', true) . "</strong>" . $email . "<br />" .
__('Para cadastrar nova senha do painel acesse o seguinte link: ', true) . "<br />" .
__('<a href="' . $link . '" target="_blank">' . $link . '</a>', true) . "<br /><br />" .
"<strong>" . __('Acesso Facil', true) . ' - ' . date('Y') . "</strong>" . "<br />" .
__('Sistema de Gest&atilde;o de forma r&aacute;pida e efetiva!', true) . "<br />" .
'<a href="http://www.acessofacil.in/" target="_blank">http://www.acessofacil.in/</a>';
if ($this->_sendEmail("$subject", __('Pedido de nova senha', true), "$email", "$message")) {
$this->Forgot->create();
if ($this->Forgot->save($this->data)) {
$this->render('success_forgot');
//$this->redirect(array('action' => 'success_forgot'));
}
}
}
}
}
}
}
function new_pass($f_key = null) {
if (!empty($this->data)) {
// Validando link do email
$this->loadModel('Forgot');
$findForgot = $this->Forgot->findByFKey($f_key);
if (!$f_key OR empty($findForgot)) {
$this->Session->setFlash(
__('Sua solicita&ccedil;&atilde;o n&atilde;o foi encontrada.', true),
'default', array('class' => 'flash_warning')
);
$this->redirect('/login');
}
else {
$new_pass = $this->data['User']['new_pass'];
if (strlen($new_pass) < 5) {
$this->Session->setFlash(
__('Informe uma senha com mais de 5 caracteres', true),
'default', array('class' => 'flash_warning')
);
$this->redirect('/new_pass/' . $f_key);
}
else {
$generate = Security::hash($new_pass, 'sha256', true);
// Atualizando campo senha na base de dados
$this->User->id = $findForgot['Forgot']['user_id'];
$this->User->saveField('pwd', $generate);
// Deletando solicitacao de nova senha
$this->Forgot->delete($findForgot['Forgot']['id']);
$this->Session->setFlash(
__('Sua senha foi modificada com sucesso.', true),
'default', array('class' => 'flash_good')
);
$this->redirect('/login');
}
}
}
// Validando link do email
$this->loadModel('Forgot');
$findForgot = $this->Forgot->findByFKey($f_key);
if (!$f_key OR empty($findForgot)) {
$this->Session->setFlash(
__('Sua solicita&ccedil;&atilde;o n&atilde;o foi encontrada.', true),
'default', array('class' => 'flash_warning')
);
$this->redirect('/login');
}
$this->set(compact('f_key'));
}
// Funcao de redirecionamento de pagina
function __isUser($redirect = FALSE, $url = NULL) {
if ($this->Session->read('sessionProfile')) {
if ($redirect === TRUE AND !empty($url)) {
$this->redirect($url);
}
else if ($redirect === TRUE AND empty($url)) {
$this->redirect(array('action' => 'perfil'));
}
}
}
function __isNotUser($redirect = FALSE, $url = NULL) {
if (!$this->Session->read('sessionProfile')) {
if ($redirect === TRUE AND !empty($url)) {
$this->redirect($url);
}
else if ($redirect === TRUE AND empty($url)) {
$this->redirect(array('action' => 'acessar'));
}
}
}
function perfil() {
$this->__isNotUser(TRUE); # verifica se usuário já está logado ou não.
$userId = $this->sessProfile['User']['id'];
$dataUser = $this->User->findById($userId);
$title_for_layout = html_entity_decode(__('Perfil do Usu&aacute;rio', true));
$this->set(compact('title_for_layout', 'dataUser'));
$this->_afterRender();
}
/**
* @todo No painel de administrador
*/
function admin_index() {
$this->User->recursive = 0;
$this->set('users', $this->paginate());
$this->render($this->pages_dir . '/users/admin_index');
}
function admin_view($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid user', true));
$this->redirect(array('action' => 'index'));
}
$this->set('user', $this->User->read(null, $id));
$this->render($this->pages_dir . '/users/admin_view');
}
function admin_add() {
if (!empty($this->data)) {
$dataUser = $this->data['User'];
$dataUserPerfil = $this->data['UserPerfil'];
unset($this->data);
$name = $dataUserPerfil['nome'];
$url_rewrite = $dataUserPerfil['url_rewrite'];
$email = $dataUser['email'];
// Verificando url
$url_rewrite = $this->TinyValue->filterUrl($dataUserPerfil['nome'], TRUE, TRUE);
$validateUrl = $this->User->UserPerfil->findUrl_rewrite($url_rewrite);
// Se o retorno não for booleano
if (!is_bool($validateUrl)) {
$url_rewrite = $validateUrl;
}
// Find by user
$user = $this->User->findByEmail($email);
if (!empty($user['User']['email'])) {
$this->Session->setFlash(__('O Usu&aacute;rio foi salvo.', true));
}
else {
# Preparando mensagem do e-mail
$_pwd = $dataUser['_pwd'];
$pwd = Security::hash($_pwd, Configure::read('hash'), true);
$tinyparam = $this->TinyValue->generateHash(20, 'lower');
$remoteAddr = getenv('REMOTE_ADDR');
$userAgent = getenv('HTTP_USER_AGENT');
// Se a conta foi marcada como ativa
if ($dataUser['active'] === '1') {
$dataUser['last_login'] = date('Y-m-d H:i:s');
$welcomeLabel = __('Acesse seu perfil no ' . $this->project_name . ' e aproveite!', true);
$linkLabel = __('Acesse seu perfil abaixo e aproveite o melhor conte&uacute;do!', true);
$linkValue = $this->url_domain . "/usuario/perfil/" . $url_rewrite;
$linkValue2 = __('Acesse aqui', true);
}
else {
$dataUser['last_login'] = NULL;
$welcomeLabel = __('Confirme seu cadastro no ' . $this->project_name . ' e aproveite!', true);
$linkLabel = __('Para ativar, confirme no seguinte link: ', true);
$linkValue = $this->url_domain . "/usuario/confirm/" . $tinyparam;
$linkValue2 = __('Confirme aqui', true);
}
$linkUrl = '<a href="' . $linkValue . '" target="_blank" style="text-decoration: none;">' .
' <font color="#009900">' . $linkValue2 . '</font>' .
'</a>';
$siteUrl = $this->url_domain;
// MailerComponent
$mailName = __('Registro de Novo Usu&aacute;rio', true);
$mailSubject = $this->project_name . __(' - Novo cadastro', true);
$message = __('Ol&aacute; ', true) . $dataUserPerfil['nome'] . ',' . "<br />" .
"<p>" . $welcomeLabel . "</p>" .
"<strong>" . __('Estes s&atilde;o seus dados de cadastro:', true) . "</strong>" . "<br />" .
"<strong>" . __('E-mail: ', true) . "</strong>" . $email . "<br />" .
"<strong>" . __('Senha: ', true) . "</strong>" . $_pwd . "<br /><br />" .
"<strong>" . __('Seu IP: ', true) . "</strong>" . $remoteAddr . "<br /><br />" .
"<strong>" . __('Browser: ', true) . "</strong>" . $userAgent . "<br /><br />" .
$linkLabel . "<br />" . $linkUrl . "<br /><br />" .
"<strong>" . $this->project_name . ' - ' . date('Y') . "</strong>" . "<br />" .
$this->project_desc . "<br />" .
'<a href="' . $siteUrl . '" target="_blank">' . $siteUrl . '</a>';
// ------------------------------------------------
# Recriando array de dados para salvar todos juntos
$this->data['User']['group_id'] = 7; // users
$this->data['User']['email'] = $email;
$this->data['User']['pwd'] = $pwd;
$this->data['User']['active'] = $dataUser['active']; // conta ativada
$this->data['User']['last_login'] = $dataUser['last_login'];
$this->data['User']['tinyparam'] = $tinyparam;
$this->data['UserPerfil']['nome'] = $dataUserPerfil['nome'];
$this->data['UserPerfil']['url_rewrite'] = $url_rewrite;
$this->data['UserPerfil']['sexo'] = $dataUserPerfil['sexo'];
$this->data['UserPerfil']['cidade_id'] = $dataUserPerfil['cidade_id'];
$this->User->create();
if ($this->User->saveAll($this->data)) {
if ($this->_sendEmail("$mailSubject", $mailName, "$email", "$message")) {
$this->Session->setFlash(__('O Usu&aacute;rio foi salvo e o e-mail foi enviado.', true));
$this->redirect(array('action' => 'index'));
}
}
else {
$this->Session->setFlash(
__('O Usu&aacute;rio n&atilde;o p&ocirc;de ser salvo. Por favor tente novamente.', true)
);
}
}
}
$groups = $this->User->Group->find('list');
$cidades = $this->User->UserPerfil->Cidade->find('list');
$this->set(compact('groups', 'cidades'));
$this->render($this->pages_dir . '/users/admin_add');
}
function admin_edit($id = null) {
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid user', true));
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->User->save($this->data)) {
$this->Session->setFlash(__('O Usu&aacute;rio foi salvo.', true));
$this->redirect(array('action' => 'index'));
}
else {
$this->Session->setFlash(__('O Usu&aacute;rio n&atilde;o p&ocirc;de ser salvo. Por favor tente novamente.', true));
}
}
if (empty($this->data)) {
$this->data = $this->User->read(null, $id);
}
$groups = $this->User->Group->find('list');
$estados = $this->User->Estado->find('list');
$paises = $this->User->Paise->find('list');
$this->set(compact('groups', 'estados', 'paises'));
$this->render($this->pages_dir . '/users/admin_edit');
}
function admin_delete($id = null) {
if (!$id) {
$this->Session->setFlash(__('Invalid id for user', true));
$this->redirect(array('action' => 'index'));
}
if ($this->User->delete($id)) {
$this->Session->setFlash(__('Usu&aacute;rio deletado com sucesso.', true));
$this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('O Usu&aacute;rio n&atilde;o foi deletado.', true));
$this->redirect(array('action' => 'index'));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment