Completed
Push — master ( 4bace5...82c570 )
by Reginaldo
27:50
created

ApiController::sendMail()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 22
Code Lines 10

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 22
rs 9.2
cc 1
eloc 10
nc 1
nop 1
1
<?php
2
3
class ApiController extends AppController {
4
5
	public function beforeFilter()
6
	{
7
		return true;
8
   	}
9
10
	public function wishlist($dados)
0 ignored issues
show
Unused Code introduced by
The parameter $dados 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...
11
	{
12
		return true;
13
	}
14
15
	public function client($id_cliente = null)
16
	{
17
		$api = 'cliente';
18
	    $this->loadModel('Cliente');
19
		$this->autoRender = false;
20
		$this->response->type('json');
21
		
22
		$type = $this->request;
23
24
	    if (!$this->validate_use_api($type, $api)) {
25
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
26
	    	return;
27
	    }
28
29
	    if ($type->is('get')) {
30
	    	$conditions = array(
31
				'ativo' => 1,
32
				'id_usuario' => $this->getIdUser(),
33
			);
34
35
			if (isset($id_cliente))
36
			 	$conditions['id'] = $id_cliente;
37
38
39
		    $cliente = $this->Cliente->find('all', 
40
				array('conditions' => 
41
					$conditions
42
				)
43
			);
44
45
			$this->response->body(json_encode($cliente));
46
	    } else if ($type->is('post')) {
47
	    	$dados = $this->request->data;
48
	    	
49
	    	if (empty($dados)) {
50
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
51
				return;
52
	    	}
53
54
	    	if (!empty($dados['nome1']) && !empty($dados['nome2']) && !empty($dados['email']) && !empty($dados['senha'])) {
55
	    		$this->postClient($dados);
56
	    	} 
57
58
	    	$this->loginClient($dados);
59 View Code Duplication
	    } else if ($type->is('put')) {
60
61
	    	$dados = $this->request->data;
62
	    	
63
			if (empty($dados)) {
64
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
65
				return;
66
	    	}
67
68
	    	if ($id_cliente == null) {
69
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
70
	    		return;
71
	    	}
72
73
	    	$this->putClient($dados, $id_cliente);
74
	    } else if ($type->is('delete')) {
75
	    	
76
	    	if ($id_cliente == null) {
77
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
78
	    		return;
79
	    	}
80
81
	    	$this->inactiveClient($id_cliente);
82
	    }
83
	}
84
85
	public function parent($id_cliente = null, $id_parente = null)
86
	{
87
		$api = 'parente';
88
89
	    $this->loadModel('Parente');
90
91
		$this->autoRender = false;
92
		$this->response->type('json');
93
		
94
		$type = $this->request;
95
96
	    if (!$this->validate_use_api($type, $api)) {
97
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
98
	    	return;
99
	    }
100
101
	    if ($type->is('get')) {
102
	    	$conditions = array(
103
				'ativo' => 1,
104
				'usuario_id' => $this->getIdUser(),
105
			);
106
107
			$conditions['cliente_id'] = $id_cliente;
108
109
			if (isset($id_parente)) {
110
				$conditions['id'] = $id_parente;
111
			}
112
113
		    $parentes = $this->Parente->find('all', 
114
				array('conditions' => 
115
					$conditions
116
				)
117
			);
118
119
			$this->response->body(json_encode($parentes));
120
	    } else if ($type->is('post')) {
121
	    	$dados = $this->request->data;
122
	    	
123
	    	if (empty($dados)) {
124
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
125
				return;
126
	    	}
127
128
	    	if (!empty($dados['cliente_id'])) {
129
	    		$this->postParent($dados);
130
	    	} 
131
132
	    	$this->loginParent($dados);
133 View Code Duplication
	    } else if ($type->is('put')) {
134
135
	    	$dados = $this->request->data;
136
	    	
137
			if (empty($dados)) {
138
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
139
				return;
140
	    	}
141
142
	    	if ($id_parente == null) {
143
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
144
	    		return;
145
	    	}
146
147
	    	$this->putParent($dados, $id_parente);
148
	    } else if ($type->is('delete')) {
149
	    	
150
	    	if ($id_parente == null) {
151
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
152
	    		return;
153
	    	}
154
155
	    	$this->inactiveClient($id_parente);
156
	    }
157
	}
158
159
	public function occurrences($id_cliente = null) 
160
	{
161
		$api = 'parente';	
162
163
		$this->autoRender = false;
164
		$this->response->type('json');
165
		$this->loadModel('Ocorrencias');
166
167
		$type = $this->request;
168
169
	    if ($type->is('get'))
170
	    {
171
	    	$conditions = array(
172
				'ativo' => 1,
173
				'cliente_id' => $id_cliente,
174
			);
175
176
			$conditions['cliente_id'] = $id_cliente;
177
178
		    $ocorrencias = $this->Ocorrencias->find('all', 
179
				array('conditions' => 
180
					$conditions
181
				)
182
			);
183
184
			$this->response->body(json_encode($ocorrencias));	    	
185
	    }
186
	}
187
188
	public function newsletter($sendMail = null)
189
	{
190
		$api = 'newsletter';
191
192
		$this->loadModel('Newsletter');
193
194
		$this->autoRender = false;
195
		$this->response->type('json');
196
		
197
		$type = $this->request;
198
199
	    if (!$this->validate_use_api($type, $api)) {
200
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
201
	    	return;
202
	    }
203
204
    	$request = $this->request->data;
205
    	
206
    	if (empty($request)) {
207
			$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
208
			return;
209
    	}
210
211
		$dados = array(
212
			'email'  => $request['email'],
213
			'origem' => $request['origem'],
214
			'ativo'  => 1,
215
			'usuario_id' => $this->getIdUser()
216
		);
217
218
		if ($sendMail == 'enviar_email')
219
		{
220
			return $this->sendMail($dados);
221
		}
222
223
		$this->Newsletter->save($dados);
224
225
		$this->response->body('{"message": "success", "result":' . json_encode($dados) . '}');
226
		return;		
227
	}
228
229
	public function banner()
230
	{
231
		$api = 'banner';
232
233
		$this->loadModel('Banner');
234
235
		$this->autoRender = false;
236
		$this->response->type('json');
237
238
		$type = $this->request;
239
240
		if (!$this->validate_use_api($type, $api)) {
241
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
242
	    	return;
243
	    }
244
245
    	$conditions = array(
246
			'ativo' => 1,
247
			'usuario_id' => $this->getIdUser()
248
		);
249
250
	    $banner = $this->Banner->find('all', 
251
			array('conditions' => 
252
				$conditions
253
			)
254
		);
255
256
	    if (!empty($banner)) {
257
			$this->response->body('{"message": "success", "result":'.json_encode($banner).'}');
258
			return;
259
	    }
260
		
261
		$this->response->body('{"message": "error"}');
262
		return;	
263
	}
264
265
	public function consulta()
266
	{
267
		$api = 'consulta';
268
269
		$this->loadModel('Consulta');
270
271
		$this->autoRender = false;
272
		$this->response->type('json');
273
274
		$type = $this->request;
275
276
		if (!$this->validate_use_api($type, $api)) {
277
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
278
	    	return;
279
	    }
280
281
282
	    if ($type->is('get')) {
283
	    	$conditions = array(
284
				'ativo' => 1,
285
				'id_usuario' => $this->getIdUser()
286
			);
287
288
		    $consulta = $this->Consulta->find('all', 
289
				array('conditions' => 
290
					$conditions
291
				)
292
			);
293
294
		    if (!empty($consulta)) {
295
				$this->response->body('{"message": "success", "result":'.json_encode($consulta).'}');
296
				return;
297
		    }
298
		}
299
300
		if ($type->is('post'))
301
		{
302
	    	$dados = $this->request->data;
303
	    	
304
	    	if (empty($dados)) {
305
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
306
				return;
307
	    	}
308
309
	    	return $this->postConsulta($dados);			
310
		}
311
312
		$this->response->body('{"message": "error"}');
313
		return;	
314
	}
315
316 View Code Duplication
	public function loginClient($dados)
317
	{
318
319
    	$conditions = array(
320
			'ativo' => 1,
321
			'id_usuario' => $this->getIdUser(),
322
			'email' => $dados['email'],
323
			'senha' => sha1($dados['senha'])
324
		);
325
326
	    $cliente = $this->Cliente->find('all', 
327
			array('conditions' => 
328
				$conditions
329
			)
330
		);
331
332
	    if (!empty($cliente)) {
333
			$this->response->body('{"message": "success", "result":'.json_encode($cliente).'}');
334
			return;
335
	    }
336
		
337
		$this->response->body('{"message": "error"}');
338
		return;	    
339
	}
340
341
	public function postClient($dados)
342
	{
343
		$this->loadModel('Cliente');
344
345
    	$dados['senha'] = sha1($dados['senha']);
346
		$dados['ativo'] = 1;
347
		$dados['id_usuario'] = $this->instancia;
348
		
349
		if ($this->Cliente->save($dados)) {
350
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
351
			return;
352
		}
353
354
		$this->response->body('{"message": "error"}');
355
		return true;
356
	}
357
358 View Code Duplication
	public function putClient($dados, $id_cliente)
359
	{
360
		if ($dados['senha'] != '') {
361
			$dados['senha'] = sha1($dados['senha']);
362
		}
363
364
		$this->Cliente->id = $id_cliente;
365
		$this->Cliente->id_usuario = $this->getIdUser();
366
367
		if ($this->Cliente->save($dados)) {
368
			$this->response->body('{"message": "success", "result": '. json_encode($dados) .'}');
369
			return;
370
		}
371
372
		$this->response->body('{"message": "error"}');
373
		return;
374
	}
375
376 View Code Duplication
	public function inactiveClient($id_cliente) 
377
	{
378
		$dados['ativo'] = 0;
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...
379
		
380
		$this->Cliente->id = $id_cliente;
381
382
		if ($this->Cliente->save($dados)) {
383
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
384
			return;
385
		} else {
386
			$this->response->body('{"message": "error"}');
387
			return;
388
		}	
389
	}
390
391
	public function sendMail($dados)
392
	{
393
		App::uses('CakeEmail', 'Network/Email');
394
395
		$email = new CakeEmail('default');
396
		
397
		$email->from('[email protected]', 'reginaldo')
398
			  ->to('[email protected]')
399
			  ->subject('Contato CakePHP MyStore');
400
401
		$mensagem = '
402
			<p><strong>Nome</strong>: adfasdf</p>
403
			<p><strong>Email</strong>: fasdf@laksjdf</p>
404
			<p><strong>Telefone</strong>: asdfasdf</p>
405
			<p><strong>Mensagem</strong>:fasdf</p>
406
		';
407
		
408
		$email->send($mensagem);
409
410
		print_r($dados);exit;
0 ignored issues
show
Coding Style Compatibility introduced by
The method sendMail() 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...
411
		exit();
0 ignored issues
show
Unused Code introduced by
die; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
Coding Style Compatibility introduced by
The method sendMail() 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...
412
	}
413
414 View Code Duplication
	public function postParent($dados)
415
	{
416
    	$dados = array(
417
			'senha'      => sha1($dados['senha']),
418
			'usuario_id' => $this->getIdUser(),
419
			'cliente_id' => $dados['cliente_id'],
420
			'login'      => $dados['login'],
421
			'ativo'      => 1,
422
		);
423
		
424
		if ($this->Parente->save($dados)) {
425
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
426
			return;
427
		}
428
429
		$this->response->body('{"message": "error"}');
430
		return;
431
	}
432
433 View Code Duplication
	public function loginParent($dados) 
434
	{
435
    	$conditions = array(
436
			'ativo' => 1,
437
			'usuario_id' => $this->getIdUser(),
438
			'login' => $dados['login'],
439
			'senha' => sha1($dados['senha'])
440
		);
441
442
	    $parente = $this->Parente->find('all', 
443
			array('conditions' => 
444
				$conditions
445
			)
446
		);
447
448
	    if (!empty($parente)) {
449
			$this->response->body('{"message": "success", "result":'.json_encode($parente).'}');
450
			return;
451
	    }
452
		
453
		$this->response->body('{"message": "error"}');
454
		return;	
455
	}
456
457 View Code Duplication
	public function putParent($dados, $id_parente) 
458
	{
459
		if ($dados['senha'] != '') {
460
			$dados['senha'] = sha1($dados['senha']);
461
		}
462
463
		$this->Parente->id = $id_parente;
464
		$this->Parente->id_usuario = $this->getIdUser();
465
466
		if ($this->Parente->save($dados)) {
467
			$this->response->body('{"message": "success", "result": '. json_encode($dados) .'}');
468
			return;
469
		}
470
471
		$this->response->body('{"message": "error"}');
472
		return;
473
	}
474
475 View Code Duplication
	public function inactiveParent($id_parente) 
476
	{
477
		$dados['ativo'] = 0;
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...
478
		
479
		$this->Parente->id = $id_parente;
480
481
		if ($this->Parente->save($dados)) {
482
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
483
			return;
484
		} else {
485
			$this->response->body('{"message": "error"}');
486
			return;
487
		}	
488
	}
489
490 View Code Duplication
	public function postConsulta($dados)
491
	{
492
    	$dados = array(
493
			'nome'       => $dados['nome'],
494
			'email'      => $dados['email'],
495
			'data'       => $dados['date'],
496
			'hora'       => $dados['hora'],
497
			'id_usuario' => $this->getIdUser(),
498
			'ativo'      => 1,
499
		);
500
		
501
		if ($this->Consulta->save($dados)) {
502
			$this->response->body('{"message": "success", "result":' . json_encode($dados) . '}');
503
			return;
504
		}
505
506
		$this->response->body('{"message": "error"}');
507
		return;
508
	}
509
510
	/**
511
	* Valida o usuario que está tentando usar a api
512
	*/
513
	public function validate_use_api($req, $api)
514
	{
515
		$this->loadModel('Usuario');
516
		
517
		$data['auth'] = $req->query;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = 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...
518
		
519
		$resposta = $this->Usuario->find('all',
520
			array('conditions' => 
521
				array('Usuario.email' => $data['auth']['email'], 
522
					  'Usuario.senha' => sha1($data['auth']['senha'])
523
				)
524
			)
525
		)[0];
526
527
		if (empty($resposta))
528
		{
529
			return false;
530
		}
531
532
		$this->setIdUser($resposta['Usuario']['id']);
533
534
		if (!$this->verifyUseApi($api)) 
535
		{
536
			return false;
537
		}
538
539
		return true;
540
	}
541
542
	public function verifyUseApi($api)
543
	{
544
		$this->loadModel('ModuloRelacionaUsuario');
545
546
		$modulos = $this->ModuloRelacionaUsuario->find('all',
547
		array('conditions' => 
548
			array('ModuloRelacionaUsuario.id_usuario' => $this->getIdUser(), 
549
				  'ModuloRelacionaUsuario.ativo' => 1,
550
				  'Modulo.ativo' => 1
551
				)
552
			)
553
		);
554
555
		foreach ($modulos as $i => $modulo) {
556
			if ($modulo['Modulo']['modulo'] == $api) {
557
				return true;
558
			}
559
		}
560
561
		return false;
562
	}
563
564
	public function setIdUser($id)
565
	{
566
		$this->instancia = $id;
567
	}
568
569
	public function getIdUser()
570
	{
571
		if (!is_numeric($this->instancia))
572
		{
573
			return false;
574
		}
575
576
		return $this->instancia;
577
	}
578
}
579