Completed
Push — master ( 437eb7...f05958 )
by Reginaldo
33:54
created

ApiController::sendMail()   B

Complexity

Conditions 2
Paths 2

Size

Total Lines 29
Code Lines 13

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 29
rs 8.8571
cc 2
eloc 13
nc 2
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]', 'OdontoClinic Pimentas')
398
			  ->to($dados['email'])
399
			  ->subject('Newsletter OdontoClinic Pimentas');
400
		
401
		$mensagem = 'Obrigado pelo cadastro, em breve você vai receber novidades e promoções!';
402
		if (file_exists('/opt/lampp/htdocs/winners-base/app/webroot/odontoclinicpimentas/ebooks/' . $dados['origem'] . '.pdf'))
403
		{
404
			$email->attachments('/opt/lampp/htdocs/winners-base/app/webroot/odontoclinicpimentas/ebooks/' . $dados['origem'] . '.pdf') ;
405
406
			$mensagem = '
407
				Obrigado pelo cadastro, para mais informações veja o arquivo em anexo!
408
			';
409
		}
410
		
411
		$mensagem .= "\n OdontoClinic Pimentas
412
					\n Rua 7, 23
413
					\n Jardim Nova Cidade, 07252-380
414
					\n (11) 2486-8936";
415
					
416
		$email->send($mensagem);
417
418
		return $this->response->body('{"message": "success", "result":' . json_encode($dados) . '}');
419
	}
420
421 View Code Duplication
	public function postParent($dados)
422
	{
423
    	$dados = array(
424
			'senha'      => sha1($dados['senha']),
425
			'usuario_id' => $this->getIdUser(),
426
			'cliente_id' => $dados['cliente_id'],
427
			'login'      => $dados['login'],
428
			'ativo'      => 1,
429
		);
430
		
431
		if ($this->Parente->save($dados)) {
432
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
433
			return;
434
		}
435
436
		$this->response->body('{"message": "error"}');
437
		return;
438
	}
439
440 View Code Duplication
	public function loginParent($dados) 
441
	{
442
    	$conditions = array(
443
			'ativo' => 1,
444
			'usuario_id' => $this->getIdUser(),
445
			'login' => $dados['login'],
446
			'senha' => sha1($dados['senha'])
447
		);
448
449
	    $parente = $this->Parente->find('all', 
450
			array('conditions' => 
451
				$conditions
452
			)
453
		);
454
455
	    if (!empty($parente)) {
456
			$this->response->body('{"message": "success", "result":'.json_encode($parente).'}');
457
			return;
458
	    }
459
		
460
		$this->response->body('{"message": "error"}');
461
		return;	
462
	}
463
464 View Code Duplication
	public function putParent($dados, $id_parente) 
465
	{
466
		if ($dados['senha'] != '') {
467
			$dados['senha'] = sha1($dados['senha']);
468
		}
469
470
		$this->Parente->id = $id_parente;
471
		$this->Parente->id_usuario = $this->getIdUser();
472
473
		if ($this->Parente->save($dados)) {
474
			$this->response->body('{"message": "success", "result": '. json_encode($dados) .'}');
475
			return;
476
		}
477
478
		$this->response->body('{"message": "error"}');
479
		return;
480
	}
481
482 View Code Duplication
	public function inactiveParent($id_parente) 
483
	{
484
		$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...
485
		
486
		$this->Parente->id = $id_parente;
487
488
		if ($this->Parente->save($dados)) {
489
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
490
			return;
491
		} else {
492
			$this->response->body('{"message": "error"}');
493
			return;
494
		}	
495
	}
496
497
	public function postConsulta($dados)
498
	{
499
    	$dados = array(
500
			'nome'       => $dados['nome'],
501
			'email'      => $dados['email'],
502
			'data'       => $dados['date'],
503
			'hora'       => $dados['hora'],
504
			'telefone'   => $dados['telefone'],
505
			'id_usuario' => $this->getIdUser(),
506
			'ativo'      => 1,
507
		);
508
		
509
		if ($this->Consulta->save($dados)) {
510
			$this->response->body('{"message": "success", "result":' . json_encode($dados) . '}');
511
			return;
512
		}
513
514
		$this->response->body('{"message": "error"}');
515
		return;
516
	}
517
518
	/**
519
	* Valida o usuario que está tentando usar a api
520
	*/
521
	public function validate_use_api($req, $api)
522
	{
523
		$this->loadModel('Usuario');
524
		
525
		$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...
526
		
527
		$resposta = $this->Usuario->find('all',
528
			array('conditions' => 
529
				array('Usuario.email' => $data['auth']['email'], 
530
					  'Usuario.senha' => sha1($data['auth']['senha'])
531
				)
532
			)
533
		)[0];
534
535
		if (empty($resposta))
536
		{
537
			return false;
538
		}
539
540
		$this->setIdUser($resposta['Usuario']['id']);
541
542
		if (!$this->verifyUseApi($api)) 
543
		{
544
			return false;
545
		}
546
547
		return true;
548
	}
549
550
	public function verifyUseApi($api)
551
	{
552
		$this->loadModel('ModuloRelacionaUsuario');
553
554
		$modulos = $this->ModuloRelacionaUsuario->find('all',
555
		array('conditions' => 
556
			array('ModuloRelacionaUsuario.id_usuario' => $this->getIdUser(), 
557
				  'ModuloRelacionaUsuario.ativo' => 1,
558
				  'Modulo.ativo' => 1
559
				)
560
			)
561
		);
562
563
		foreach ($modulos as $i => $modulo) {
564
			if ($modulo['Modulo']['modulo'] == $api) {
565
				return true;
566
			}
567
		}
568
569
		return false;
570
	}
571
572
	public function setIdUser($id)
573
	{
574
		$this->instancia = $id;
575
	}
576
577
	public function getIdUser()
578
	{
579
		if (!is_numeric($this->instancia))
580
		{
581
			return false;
582
		}
583
584
		return $this->instancia;
585
	}
586
}
587