ApiController::inactiveClient()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 14
Code Lines 9

Duplication

Lines 14
Ratio 100 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 1
dl 14
loc 14
rs 9.4285
c 0
b 0
f 0
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
19
	    $this->loadModel('Cliente');
20
		$this->autoRender = false;
21
		$this->response->type('json');
22
		
23
		$type = $this->request;
24
25
	    if (!$this->validate_use_api($type, $api)) {
26
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
27
	    	return;
28
	    }
29
30
	    if ($type->is('get')) {
31
	    	$conditions = array(
32
				'ativo' => 1,
33
				'id_usuario' => $this->getIdUser(),
34
			);
35
36
			if (isset($id_cliente))
37
			 	$conditions['id'] = $id_cliente;
38
39
40
		    $cliente = $this->Cliente->find('all', 
41
				array('conditions' => 
42
					$conditions
43
				)
44
			);
45
46
			$this->response->body(json_encode($cliente));
47
	    } else if ($type->is('post')) {
48
	    	$dados = $this->request->data;
49
	    	
50
	    	if (empty($dados)) {
51
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
52
				return;
53
	    	}
54
55
	    	if (!empty($dados['nome1']) && !empty($dados['nome2']) && !empty($dados['email']) && !empty($dados['senha'])) {
56
	    		$this->postClient($dados);
57
	    	} 
58
59
	    	$this->loginClient($dados);
60 View Code Duplication
	    } else if ($type->is('put')) {
61
62
	    	$dados = $this->request->data;
63
	    	
64
			if (empty($dados)) {
65
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
66
				return;
67
	    	}
68
69
	    	if ($id_cliente == null) {
70
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
71
	    		return;
72
	    	}
73
74
	    	$this->putClient($dados, $id_cliente);
75
	    } else if ($type->is('delete')) {
76
	    	
77
	    	if ($id_cliente == null) {
78
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
79
	    		return;
80
	    	}
81
82
	    	$this->inactiveClient($id_cliente);
83
	    }
84
	}
85
86
	public function parent($id_cliente = null, $id_parente = null)
87
	{
88
		$api = 'parente';
89
90
	    $this->loadModel('Parente');
91
92
		$this->autoRender = false;
93
		$this->response->type('json');
94
		
95
		$type = $this->request;
96
97
	    if (!$this->validate_use_api($type, $api)) {
98
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
99
	    	return;
100
	    }
101
102
	    if ($type->is('get')) {
103
	    	$conditions = array(
104
				'ativo' => 1,
105
				'usuario_id' => $this->getIdUser(),
106
			);
107
108
			$conditions['cliente_id'] = $id_cliente;
109
110
			if (isset($id_parente)) {
111
				$conditions['id'] = $id_parente;
112
			}
113
114
		    $parentes = $this->Parente->find('all', 
115
				array('conditions' => 
116
					$conditions
117
				)
118
			);
119
120
			$this->response->body(json_encode($parentes));
121
	    } else if ($type->is('post')) {
122
	    	$dados = $this->request->data;
123
	    	
124
	    	if (empty($dados)) {
125
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
126
				return;
127
	    	}
128
129
	    	if (!empty($dados['cliente_id'])) {
130
	    		$this->postParent($dados);
131
	    	} 
132
133
	    	$this->loginParent($dados);
134 View Code Duplication
	    } else if ($type->is('put')) {
135
136
	    	$dados = $this->request->data;
137
	    	
138
			if (empty($dados)) {
139
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
140
				return;
141
	    	}
142
143
	    	if ($id_parente == null) {
144
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
145
	    		return;
146
	    	}
147
148
	    	$this->putParent($dados, $id_parente);
149
	    } else if ($type->is('delete')) {
150
	    	
151
	    	if ($id_parente == null) {
152
	    		$this->response->body(json_encode(array('message' => 'Você não passou o id do usuario')));
153
	    		return;
154
	    	}
155
156
	    	$this->inactiveClient($id_parente);
157
	    }
158
	}
159
160
	public function occurrences($id_cliente = null) 
161
	{
162
		$api = 'parente';	
163
164
		$this->autoRender = false;
165
		$this->response->type('json');
166
		$this->loadModel('Ocorrencias');
167
168
		$type = $this->request;
169
170
	    if ($type->is('get'))
171
	    {
172
	    	$conditions = array(
173
				'ativo' => 1,
174
				'cliente_id' => $id_cliente,
175
			);
176
177
			$conditions['cliente_id'] = $id_cliente;
178
179
		    $ocorrencias = $this->Ocorrencias->find('all', 
180
				array('conditions' => 
181
					$conditions
182
				)
183
			);
184
185
			$this->response->body(json_encode($ocorrencias));	    	
186
	    }
187
	}
188
189
	public function newsletter($sendMail = null)
190
	{
191
		$api = 'newsletter';
192
193
		$this->loadModel('Newsletter');
194
195
		$this->autoRender = false;
196
		$this->response->type('json');
197
		
198
		$type = $this->request;
199
200
	    if (!$this->validate_use_api($type, $api)) {
201
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
202
	    	return;
203
	    }
204
205
    	$request = $this->request->data;
206
    	
207
    	if (empty($request)) {
208
			$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
209
			return;
210
    	}
211
212
		$dados = array(
213
			'email'  => $request['email'],
214
			'origem' => $request['origem'],
215
			'ativo'  => 1,
216
			'usuario_id' => $this->getIdUser()
217
		);
218
219
		if ($sendMail == 'enviar_email')
220
		{
221
			return $this->sendMail($dados);
222
		}
223
224
		$this->Newsletter->save($dados);
225
226
		$this->response->body('{"message": "success", "result":' . json_encode($dados) . '}');
227
		return;		
228
	}
229
230
	public function banner()
231
	{
232
		$api = 'banner';
233
234
		$this->loadModel('Banner');
235
236
		$this->autoRender = false;
237
		$this->response->type('json');
238
239
		$type = $this->request;
240
241
		if (!$this->validate_use_api($type, $api)) {
242
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
243
	    	return;
244
	    }
245
246
    	$conditions = array(
247
			'ativo' => 1,
248
			'usuario_id' => $this->getIdUser()
249
		);
250
251
	    $banner = $this->Banner->find('all', 
252
			array('conditions' => 
253
				$conditions
254
			)
255
		);
256
257
	    if (!empty($banner)) {
258
			$this->response->body('{"message": "success", "result":'.json_encode($banner).'}');
259
			return;
260
	    }
261
		
262
		$this->response->body('{"message": "error"}');
263
		return;	
264
	}
265
266
	public function consulta()
267
	{
268
		$api = 'consulta';
269
270
		$this->loadModel('Consulta');
271
272
		$this->autoRender = false;
273
		$this->response->type('json');
274
275
		$type = $this->request;
276
277
		if (!$this->validate_use_api($type, $api)) {
278
	    	echo '{message: Você não tem permissão para usar nosso modulo}';
279
	    	return;
280
	    }
281
282
283
	    if ($type->is('get')) {
284
	    	$conditions = array(
285
				'ativo' => 1,
286
				'id_usuario' => $this->getIdUser()
287
			);
288
289
		    $consulta = $this->Consulta->find('all', 
290
				array('conditions' => 
291
					$conditions
292
				)
293
			);
294
295
		    if (!empty($consulta)) {
296
				$this->response->body('{"message": "success", "result":'.json_encode($consulta).'}');
297
				return;
298
		    }
299
		}
300
301
		if ($type->is('post'))
302
		{
303
	    	$dados = $this->request->data;
304
	    	
305
	    	if (empty($dados)) {
306
				$this->response->body(json_encode(array('message' => 'Ocorreu algum erro com os parametros passados')));
307
				return;
308
	    	}
309
310
	    	return $this->postConsulta($dados);			
311
		}
312
313
		$this->response->body('{"message": "error"}');
314
		return;	
315
	}
316
317 View Code Duplication
	public function loginClient($dados)
318
	{
319
320
    	$conditions = array(
321
			'ativo' => 1,
322
			'id_usuario' => $this->getIdUser(),
323
			'email' => $dados['email'],
324
			'senha' => sha1($dados['senha'])
325
		);
326
327
	    $cliente = $this->Cliente->find('all', 
328
			array('conditions' => 
329
				$conditions
330
			)
331
		);
332
333
	    if (!empty($cliente)) {
334
			$this->response->body('{"message": "success", "result":'.json_encode($cliente).'}');
335
			return;
336
	    }
337
		
338
		$this->response->body('{"message": "error"}');
339
		return;	    
340
	}
341
342
	public function postClient($dados)
343
	{
344
		$this->loadModel('Cliente');
345
346
    	$dados['senha'] = sha1($dados['senha']);
347
		$dados['ativo'] = 1;
348
		$dados['id_usuario'] = $this->instancia;
349
		
350
		if ($this->Cliente->save($dados)) {
351
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
352
			return;
353
		}
354
355
		$this->response->body('{"message": "error"}');
356
		return true;
357
	}
358
359 View Code Duplication
	public function putClient($dados, $id_cliente)
360
	{
361
		if ($dados['senha'] != '') {
362
			$dados['senha'] = sha1($dados['senha']);
363
		}
364
365
		$this->Cliente->id = $id_cliente;
366
		$this->Cliente->id_usuario = $this->getIdUser();
367
368
		if ($this->Cliente->save($dados)) {
369
			$this->response->body('{"message": "success", "result": '. json_encode($dados) .'}');
370
			return;
371
		}
372
373
		$this->response->body('{"message": "error"}');
374
		return;
375
	}
376
377 View Code Duplication
	public function inactiveClient($id_cliente) 
378
	{
379
		$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...
380
		
381
		$this->Cliente->id = $id_cliente;
382
383
		if ($this->Cliente->save($dados)) {
384
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
385
			return;
386
		} else {
387
			$this->response->body('{"message": "error"}');
388
			return;
389
		}	
390
	}
391
392
	public function sendMail($dados)
393
	{
394
		App::uses('CakeEmail', 'Network/Email');
395
396
		$email = new CakeEmail('default');
397
		
398
		$email->from('[email protected]', 'OdontoClinic Pimentas')
399
			  ->to($dados['email'])
400
			  ->subject('Newsletter OdontoClinic Pimentas');
401
		
402
		$mensagem = 'Obrigado pelo cadastro, em breve você vai receber novidades e promoções!';
403
		if (file_exists(APP . 'webroot/odontoclinicpimentas/ebooks/' . $dados['origem'] . '.pdf'))
404
		{
405
			$email->attachments(APP . '/webroot/odontoclinicpimentas/ebooks/' . $dados['origem'] . '.pdf') ;
406
407
			$mensagem = '
408
				Obrigado pelo cadastro, para mais informações veja o arquivo em anexo!
409
			';
410
		}
411
		
412
		$mensagem .= "\n OdontoClinic Pimentas
413
					\n Rua 7, 23
414
					\n Jardim Nova Cidade, 07252-380
415
					\n (11) 2486-8936";
416
417
		$email->send($mensagem);
418
419
		return $this->response->body('{"message": "success", "result":' . json_encode($dados) . '}');
420
	}
421
422 View Code Duplication
	public function postParent($dados)
423
	{
424
    	$dados = array(
425
			'senha'      => sha1($dados['senha']),
426
			'usuario_id' => $this->getIdUser(),
427
			'cliente_id' => $dados['cliente_id'],
428
			'login'      => $dados['login'],
429
			'ativo'      => 1,
430
		);
431
		
432
		if ($this->Parente->save($dados)) {
433
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
434
			return;
435
		}
436
437
		$this->response->body('{"message": "error"}');
438
		return;
439
	}
440
441 View Code Duplication
	public function loginParent($dados) 
442
	{
443
    	$conditions = array(
444
			'ativo' => 1,
445
			'usuario_id' => $this->getIdUser(),
446
			'login' => $dados['login'],
447
			'senha' => sha1($dados['senha'])
448
		);
449
450
	    $parente = $this->Parente->find('all', 
451
			array('conditions' => 
452
				$conditions
453
			)
454
		);
455
456
	    if (!empty($parente)) {
457
			$this->response->body('{"message": "success", "result":'.json_encode($parente).'}');
458
			return;
459
	    }
460
		
461
		$this->response->body('{"message": "error"}');
462
		return;	
463
	}
464
465 View Code Duplication
	public function putParent($dados, $id_parente) 
466
	{
467
		if ($dados['senha'] != '') {
468
			$dados['senha'] = sha1($dados['senha']);
469
		}
470
471
		$this->Parente->id = $id_parente;
472
		$this->Parente->id_usuario = $this->getIdUser();
473
474
		if ($this->Parente->save($dados)) {
475
			$this->response->body('{"message": "success", "result": '. json_encode($dados) .'}');
476
			return;
477
		}
478
479
		$this->response->body('{"message": "error"}');
480
		return;
481
	}
482
483 View Code Duplication
	public function inactiveParent($id_parente) 
484
	{
485
		$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...
486
		
487
		$this->Parente->id = $id_parente;
488
489
		if ($this->Parente->save($dados)) {
490
			$this->response->body('{"message": "success", "result":'.json_encode($dados).'}');
491
			return;
492
		} else {
493
			$this->response->body('{"message": "error"}');
494
			return;
495
		}	
496
	}
497
498
	public function postConsulta($dados)
499
	{
500
    	$dados = array(
501
			'nome'       => $dados['nome'],
502
			'email'      => $dados['email'],
503
			'data'       => $dados['date'],
504
			'hora'       => $dados['hora'],
505
			'telefone'   => $dados['telefone'],
506
			'id_usuario' => $this->getIdUser(),
507
			'ativo'      => 1,
508
		);
509
		
510
		if ($this->Consulta->save($dados)) {
511
			$this->response->body('{"message": "success", "result":' . json_encode($dados) . '}');
512
			return;
513
		}
514
515
		$this->response->body('{"message": "error"}');
516
		return;
517
	}
518
519
	/**
520
	* Valida o usuario que está tentando usar a api
521
	*/
522
	public function validate_use_api($req, $api)
523
	{
524
		$this->loadModel('Usuario');
525
		
526
		$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...
527
528
		$resposta = $this->Usuario->find('all',
529
			array('conditions' => 
530
				array('Usuario.token' => $data['auth']['token'])
531
			)
532
		);
533
534
		if (isset($resposta[0]) && !empty($resposta[0]))
535
		{
536
			$resposta = $resposta[0];
537
		}
538
539
		if (empty($resposta))
540
		{
541
			return false;
542
		}
543
544
		$this->setIdUser($resposta['Usuario']['id']);
545
546
		if (!$this->verifyUseApi($api)) 
547
		{
548
			return false;
549
		}
550
551
		return true;
552
	}
553
554
	public function verifyUseApi($api)
555
	{
556
		$this->loadModel('ModuloRelacionaUsuario');
557
558
		$modulos = $this->ModuloRelacionaUsuario->find('all',
559
		array('conditions' => 
560
			array('ModuloRelacionaUsuario.id_usuario' => $this->getIdUser(), 
561
				  'ModuloRelacionaUsuario.ativo' => 1,
562
				  'Modulo.ativo' => 1
563
				)
564
			)
565
		);
566
567
		foreach ($modulos as $i => $modulo) {
568
			if ($modulo['Modulo']['modulo'] == $api) {
569
				return true;
570
			}
571
		}
572
573
		return false;
574
	}
575
576
	public function setIdUser($id)
577
	{
578
		$this->instancia = $id;
579
	}
580
581
	public function getIdUser()
582
	{
583
		if (!is_numeric($this->instancia))
584
		{
585
			return false;
586
		}
587
588
		return $this->instancia;
589
	}
590
}
591