Completed
Push — master ( a8e8b7...373ce5 )
by Reginaldo
19:01
created

UsuarioController::uploadZipTemplate()   B

Complexity

Conditions 3
Paths 2

Size

Total Lines 35
Code Lines 16

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 16
nc 2
nop 1
dl 0
loc 35
rs 8.8571
c 0
b 0
f 0
1
<?php
2
3
class UsuarioController extends AppController{
4
	public function beforeFilter(){
5
		return true;
6
   	}
7
8
	//faz o login no sistema, com a função autentica_email
9
	public function login(){
10
		$this->layout = 'ajax';//chama o layout para executar uma função ajax
11
12
		$login_email = $this->request->data['email'];//recebe o post email
13
		$login_senha = $this->request->data['senha'];//recebe o post senha
14
		echo json_encode(true);
15
	}
16
17
	public function processar_login() {
18
		//destroe alguma session criada anteriomente
19
		$this->Session->Destroy();
20
21
		$dados = $this->request->data('dados');
22
		$this->loadModel('Usuario');
23
		$resposta = $this->Usuario->find('all',
24
			array('conditions' => 
25
				array('Usuario.email' => $dados['email'], 
26
					  'Usuario.senha' => sha1($dados['senha'])
27
				)
28
			)
29
		);
30
		
31
		if (count($resposta) < 1) {
32
			$this->Session->setFlash('Ocorreu um erro ao logar na sua conta, verifique seus dados!');
33
            return $this->redirect('/home/login');
34
		}
35
36
		//faz o foreach com o array de dados do usuario
37
		foreach($resposta as $valor) {
38
			//escreve a sessao do usuario
39
			$this->Session->write('Usuario.id',   $valor['Usuario']['id']);
40
			$this->Session->write('Usuario.nome', $valor['Usuario']['nome']);//nome do usuario
41
			$this->Session->write('Usuario.email',$valor['Usuario']['email']);//email do usuario
42
			$this->Session->write('Usuario.senha',$valor['Usuario']['senha']);//senha do usuario criptografada
43
			$this->Session->write('Usuario.erp',  $valor['Usuario']['erp']);//situacao ativa(1) ou nao(0) no erp
44
			$this->Session->write('Usuario.ead',  $valor['Usuario']['ead']);//situacao ativa(1) ou nao(0) no ead
45
			$this->Session->write('Usuario.site', $valor['Usuario']['site']);//situacao ativa(1) ou nao(0) no site
46
		}
47
48
		$this->Session->setFlash('Bem vindo, '.$this->Session->read('Usuario.nome').'!');
49
        return $this->redirect('/dashboard/home');
50
	}
51
52
	public function processar_logout() {
53
		$this->Session->Destroy();
54
		return $this->redirect('/home/login');
55
	}
56
57
	public function logout(){
58
		$this->Session->Destroy();
59
60
		echo '<script>location.href="/winners/framework/"</script>';
61
	}
62
63
	//autentica email verifica se o email e senha existem para efetuar o login, ou outra acao.
64 View Code Duplication
	public function autentica_email($email,$senha){
65
		$this->loadModel('Usuario');
66
		$resposta = $this->Usuario->find('count', 
67
								array('conditions' => array('AND' => array('Usuario.email' => $email, 'Usuario.senha' => sha1($senha))
68
										)
69
									)
70
								);
71
		$this->set('resposta', $resposta);
72
73
		return $resposta;
74
	}			
75
76
	//se o email estiver livre retorna false, senão retorna true
77
	public function verificar_email($email){
78
		$this->layout = 'ajax';
79
		
80
		if(empty($email)){
81
			$email = $this->request->data['email'];
82
		}
83
84
		$this->loadModel('Usuario');
85
		$resposta = $this->Usuario->find('count',
86
											array('conditions' => array('Usuario.email' => $email))
87
										);
88
		$this->set('resposta', $resposta);
89
90
		if($resposta >= 1){
91
			return true;
92
		}else{
93
			return false;
94
		}
95
	}
96
97 View Code Duplication
	public function recuperar_dados($email,$senha){
98
		$this->loadModel('Usuario');
99
		$resposta = $this->Usuario->find('all', 
100
								array('conditions' => array('AND' => array('Usuario.email' => $email, 'Usuario.senha' => sha1($senha))
101
										)
102
									)
103
								);
104
105
		$this->set('resposta', $resposta);
106
107
		return $resposta;
108
	}
109
110
	public function novo_usuario() {
111
		$dados = $this->request->data('dados');
112
		$dados['senha'] = sha1($dados['senha']);
113
114
		if ($this->verificar_email($dados['email']) !== false) {
115
			$this->Session->setFlash('Email já cadastrado no sistema!');
116
			$this->redirect('/');
117
		}
118
119
		if ($this->Usuario->save($dados)) {
120
			$this->relacionar_modulos_teste($this->Usuario->id);
121
122
			$this->notificar_cadastro($dados['nome'], $dados['email']);
123
			$this->processar_login();
124
		}
125
126
		$this->Session->setFlash('Ocorreu um erro, tente novamente!');
127
		$this->redirect('/');
128
	}
129
130
	public function enviar_email_sucesso($email, $nome) {	
0 ignored issues
show
Unused Code introduced by
The parameter $email is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $nome is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
131
		$name = $dados['name'];
0 ignored issues
show
Bug introduced by
The variable $dados does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
132
		$email_address = $dados['email'];
133
	
134
		// Create the email and send the message
135
		$to = '[email protected]'; // Add your email address inbetween the '' replacing [email protected] - This is where the form will send a message to.
136
		$email_subject = "Contato Winners Desenvolvimento";
137
		$email_body = "Muito Obrigado por nos contactar";
138
		$headers = "From: [email protected]\n"; // This is the email address the generated message will be from. We recommend using something like [email protected].
139
		$headers .= "Reply-To: $email_address";	
140
		mail($to, $email_subject, $email_body, $headers);
141
	}
142
143
	public function notificar_cadastro($nome, $email) {
144
		$headers = "From: [email protected]\n"; // This is the email address the generated message will be from. We recommend using something like [email protected].
145
		$headers .= "Reply-To: $email_address";	
0 ignored issues
show
Bug introduced by
The variable $email_address does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
146
		mail('[email protected], [email protected], [email protected], [email protected]', 'Notificação de cadastro', 'O usuario ' . $nome . ' email ' . $email . ' ', $headers);
147
	}
148
149
	public function relacionar_modulos_teste($id) {
150
		$this->loadModel('ModuloRelacionaUsuario');
151
		
152
		$modulos = array(
153
			0 => array(
154
				'id_usuario' => $id,
155
				'id_modulo' => 1,
156
				'ativo' => 1
157
			),
158
			2 => array(
159
				'id_usuario' => $id,
160
				'id_modulo' => 2,
161
				'ativo' => 1
162
			),
163
			3 => array(
164
				'id_usuario' => $id,
165
				'id_modulo' => 3,
166
				'ativo' => 1
167
			),
168
			4 => array(
169
				'id_usuario' => $id,
170
				'id_modulo' => 4,
171
				'ativo' => 1
172
			)		
173
		);
174
175
		$this->ModuloRelacionaUsuario->saveAll($modulos);
176
177
		return true;
178
	}
179
180
	public function s_editar_dados() {
0 ignored issues
show
Coding Style introduced by
s_editar_dados uses the super-global variable $_FILES which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
181
		$this->verificar_acesso();
182
183
		$this->layout = 'wadmin';
184
185
		$estoque_minimo = $this->request->data['estoque_minimo'];
186
187
		$sale_without_stock = $this->request->data['sale_without_stock'];
188
189
		$template = $_FILES['template'];
190
		
191
		$layout_loja = $this->request->data['layout_loja'];
192
		
193
		if (!empty($template['name']) && isset($template['name']))
194
			$layout_loja = $this->uploadZipTemplate($template);
195
		
196
		$data = array(
197
			'estoque_minimo' => $estoque_minimo, 
198
			'sale_without_stock' => $sale_without_stock,
199
			'loja_active' => $this->request->data['loja_active'],
200
			'loja' => $this->request->data['loja'],
201
			'layout_loja' => $layout_loja	,
202
			'cep_origem' => $this->request->data['cep_origem'],
203
			'descricao' => $this->request->data['descricao'],
204
			'token_pagseguro' => $this->request->data['token_pagseguro'],
205
			'email_pagseguro' => $this->request->data['email_pagseguro']
206
		);
207
208
		$this->loadModel('Usuario');
209
210
		$this->Usuario->id = $this->instancia;
211
212
		$retorno = $this->Usuario->save($data);
213
214
		if(!$retorno) {
215
			$this->Session->setFlash('Ocorreu um erro ao salvar as novas infomações, tente novamente!');
216
            
217
            return $this->redirect('/usuario/meus_dados');
218
		}
219
220
		$this->Session->setFlash('Dados atualizados com sucesso!');
221
        
222
        return $this->redirect('/usuario/meus_dados');
223
	}
224
225
	public function meus_dados() {
226
		$this->verificar_acesso();
227
228
		$this->layout = 'wadmin';
229
230
		$dadosUsuario = $this->Usuario->find('all', array(
231
				'conditions' => array(
232
					'Usuario.id' => $this->instancia
233
				)
234
			)
235
		);
236
237
    	$this->set('modulos', $this->modulos);
238
    	$this->set('usuario', $dadosUsuario);
239
	}
240
241
	public function new_token() {
242
		$this->verificar_acesso();
243
244
		$this->loadModel('Usuario');
245
246
		$response = $this->Usuario->find('all', array(
247
				'conditions' => array(
248
					'Usuario.id' => $this->instancia
249
				)
250
			)
251
		);
252
253
		$token = md5(uniqid());
254
255
		$this->Usuario->id = $this->instancia;
256
257
		$dados['token'] = $token;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$dados was never initialized. Although not strictly required by PHP, it is generally a good practice to add $dados = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
258
259
		$this->Usuario->save($dados);
260
261
		echo json_encode($token);
262
		exit();
0 ignored issues
show
Coding Style Compatibility introduced by
The method new_token() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
263
	}
264
265
	public function uploadZipTemplate($template) {
266
		$z = new ZipArchive();
267
		
268
		$abriu = $z->open($template['tmp_name']);
269
		
270
		if ($abriu === true) {
271
272
		    // Listando os nomes dos elementos
273
		    for ($i = 0; $i < $z->numFiles; $i++) {
274
275
        		$nome = $z->getNameIndex($i);
276
277
		        $response = $z->extractTo(ROOT . DS . "app/View/");
278
279
		    }
280
281
		    // Fechando o arquivo
282
283
		    $z->close();
284
285
		} else {
286
		    echo 'Erro: ' . $abriu;
287
		}
288
        
289
        $nomeLayout = substr($template['name'], 0, -4);
290
291
        $origem  = ROOT . DS . "app/View/" . $nomeLayout . DS . "Layouts" . DS . $nomeLayout . ".ctp";
292
        $destino = ROOT . DS . "app/View/" . "Layouts" . DS . $nomeLayout . ".ctp";
293
        
294
		shell_exec("mv " . $origem . " " . $destino);
295
296
		shell_exec("rm -R " . ROOT . DS . "app/View/" . $nomeLayout . "Layouts/");
297
298
		return $nomeLayout;
299
	}
300
301
}