summaryrefslogtreecommitdiffstats
path: root/admin/WebConsole/rest/server.php
blob: b17425663625bc87ec246975643165e41af8cc73 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
<?php
/**
 * @file    index.php
 * @brief   OpenGnsys Server REST API manager.
 * @warning All input and output messages are formatted in JSON.
 * @note    Some ideas are based on article "How to create REST API for Android app using PHP, Slim and MySQL" by Ravi Tamada, thanx.
 * @license GNU GPLv3+
 * @author  Ramón M. Gómez, ETSII Univ. Sevilla
 * @version 1.1.0 - First version
 * @date    2016-09-19
 */


// Auxiliar functions.

/**
 * @brief    Check if user is administrator and print error messages if not.
 * @param    int adminid   Administrator id.
 * @return   boolean       "true" if admin id. is equals to global user id., otherwise "false".
 */
function checkAdmin($adminid) {
	global $userid;

	if ($adminid == $userid) {
		return true;
	} else {
		// Print error message.
		$response['message'] = 'Cannot access this resource';
		jsonResponse(401, $response);
		return false;
	}
}

/**
 * @fn    addClassroomGroup(&$classroomGroups, $rs)
 * @brief Funcion privada usada para añadir grupos de aulas recursivamente
 * @param classroomGroups Grupos de aulas que pueden contener más grupos
 * @param rs resultset de la consulta a la base de datos.
 */
function addClassroomGroup(&$classroomGroups, $rs){

	array_walk($classroomGroups, function(&$group,$key){
		global $rs;
		if (isset($group['id']) && $group['id'] === $rs->campos["group_group_id"]) {
			array_push($group["classroomGroups"],array("id" => $rs->campos["group_id"], 
				"name" => $rs->campos["nombregrupoordenador"], 
				"comments" => $rs->campos["comentarios"],
				"classroomGroups" => array()));
		}
		else if(count($group["classroomGroups"]) > 0){
			addClassroomGroup($group["classroomGroups"], $rs);
		}
		/**/
	});
}


// REST routes.

/**
 * @brief    user login.
 * @note     Route: /login, Method: POST
 * @param    string username   User name.
 * @param    string password   User password.
 * @return   string            JSON response with user id. and API key.
 * @note     User's API key is stored in a new field of "usuarios" table.
 */
$app->post('/login',
    function() use ($app) {
	global $cmd;
	global $userid;

	$response = array();

	// Reading JSON parameters.
	try {
		$input = json_decode($app->request()->getBody());
		$user = htmlspecialchars($input->username);
		$pass = htmlspecialchars($input->password);
	} catch (Exception $e) {
		// Error message.
		$response["message"] = $e->getMessage();
		jsonResponse(400, $response);
		$app->stop();
	}

	// Checking parameters. 
	if (! empty($user) and ! empty($pass)) {
		// Database query.
		$cmd->texto = "SELECT idusuario, apikey
			 	 FROM usuarios
				WHERE usuario='$user' AND pasguor='$pass'";
		$rs=new Recordset;
		$rs->Comando=&$cmd;
		if ($rs->Abrir()) {
			$rs->Primero();
			if (!$rs->EOF){
				// JSON response.
				$userid=$rs->campos["idusuario"];
				$apikey=$rs->campos["apikey"];
				$response['userid'] = $userid;
				$response['apikey'] = $apikey;
				jsonResponse(200, $response);
			} else {
                		// Credentials error.
                		$response['message'] = 'Login failed. Incorrect credentials';
				jsonResponse(401, $response);
				$app->stop();
			}
			$rs->Cerrar();
		} else {
			// Access error.
			$response['message'] = "An error occurred. Please try again";
			jsonResponse(500, $response);
			$app->stop();
		}
	} else {
		# Error: missing some input parameter.
		$response['message'] = 'Missing username or password';
		jsonResponse(400, $response);
		$app->stop();
	}
    }
);

/**
 * @brief    List all defined Organizational Units
 * @note     Route: /ous, Method: GET
 * @param    no
 * @return   JSON array with id. and name for every defined OU
 */
$app->get('/ous', function() {
	global $cmd;

	$cmd->texto = "SELECT * FROM centros";
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false); // Error al abrir recordset
	$response = array();
	$rs->Primero();
	while (!$rs->EOF) {
		$tmp = array();
		$tmp['id'] = $rs->campos["idcentro"];
		$tmp['name'] = $rs->campos["nombrecentro"];
		array_push($response, $tmp);
		$rs->Siguiente();
	}
	$rs->Cerrar(); 
	jsonResponse(200, $response);
   } 
);

/**
 * @brief    Get Organizational Unit data
 * @note     Route: /ous/id, Method: GET
 * @param    id      OU id.
 * @return   JSON string with OU's parameters
 */
$app->get('/ous/:ouid', 'validateApiKey',
    function($ouid) {
	global $cmd;

	$ouid = htmlspecialchars($ouid);
	$cmd->texto = "SELECT * FROM centros WHERE idcentro='$ouid';";
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false); // Error al abrir recordset
	$rs->Primero();
	if (checkParameter($rs->campos["nombrecentro"])) {
		$response['id'] = $ouid;
		$response['name'] = $rs->campos["nombrecentro"];
		$response['description'] = $rs->campos["comentarios"];
		jsonResponse(200, $response);
	}
	$rs->Cerrar(); 
    }
);

// Listar grupos.
$app->get('/ous/:ouid/groups', 'validateApiKey', function($ouid) {
	global $cmd;
	global $userid;

	$ouid = htmlspecialchars($ouid);
	if(checkAdmin($userid, $ouid) == true){
		// Listar las salas de la UO si el usuario de la apikey es su admin.
		// Consulta temporal,
		$cmd->texto = "SELECT * FROM grupos WHERE idcentro='$ouid';";
		$rs=new Recordset;
		$rs->Comando=&$cmd;
		if (!$rs->Abrir()) return(false); // Error al abrir recordset
			$rs->Primero();
			// Comprobar que exista la UO.
			if (checkParameter($rs->campos["idcentro"])) {
				$response = array();
				while (!$rs->EOF) {
					$tmp = array();
					$tmp['id'] = $rs->campos["idgrupo"];
					$tmp['name'] = $rs->campos["nombregrupo"];
					$tmp['type'] = $rs->campos["tipo"];
					$tmp['comments'] = $rs->campos["comentarios"];
				if($rs->campos["grupoid"] != 0){
					$tmp['parent']['id'] = $rs->campos["grupoid"];
				}
				array_push($response, $tmp);
				$rs->Siguiente();
			}
			jsonResponse(200, $response);
		}
		$rs->Cerrar();
	}
    }
);

/**
 * @brief    List all labs defined in an OU
 * @note     Route: /ous/id/labs, Method: GET
 * @param    id      OU id.
 * @return   JSON string with all UO's labs parameters
 */
$app->get('/ous/:ouid/labs', 'validateApiKey',
    function($ouid) {
	global $userid;
	global $cmd;
	global $rs;

	$ouid = htmlspecialchars($ouid);
	// Listar las salas de la UO si el usuario de la apikey es su admin.
	$cmd->texto = <<<EOD
SELECT aulas.*, adm.idadministradorcentro, grp.idgrupo AS group_id,
       grp.nombregrupoordenador, grp.grupoid AS group_group_id, grp.comentarios
  FROM aulas
 RIGHT JOIN administradores_centros AS adm USING(idcentro)
 RIGHT JOIN usuarios USING(idusuario)
  LEFT JOIN gruposordenadores AS grp USING(idaula)
 WHERE idcentro='$ouid' AND adm.idadministradorcentro = '$userid'
 ORDER BY aulas.idaula, grp.idgrupo
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false);	// Error opening recordset.
	// Comprobar que exista la UO y que el usuario sea su administrador.
	$rs->Primero();
	if (checkParameter($rs->campos["idcentro"]) and checkAdmin($rs->campos["idadministradorcentro"])) {
		$response = array();
		while (!$rs->EOF) {
			// En los resultados las aulas vienen repetidas tantas veces como grupos tengan, solo dejamos uno
			$classroomIndex = -1;
			$found=false;
			$index = 0;
			while(!$found && $index < count($response)){
				if(isset($response[$index]["id"]) && $response[$index]["id"] == $rs->campos["idaula"]){
					$classroomIndex = $index;
					$found = true;
				}
				$index++;
			}
			if(!$found){
				$tmp = array();
				$tmp['id'] = $rs->campos["idaula"];
				$tmp['name'] = $rs->campos["nombreaula"];
				$tmp['inremotepc'] = $rs->campos["inremotepc"]==0 ? false: true;
				$tmp['group']['id'] = $rs->campos["grupoid"];
				$tmp['ou']['id'] = $ouid;
				array_push($response, $tmp);
			}
			else{
				// Le añadimos el grupo en cuestion siempre que no sea un subgrupo
				if($rs->campos["group_group_id"] == 0){
					array_push($response[$classroomIndex]['classroomGroups'],
						array("id" => $rs->campos["group_id"],
						"name" => $rs->campos["nombregrupoordenador"],
						"comments" => $rs->campos["comentarios"],
						"classroomGroups" => array()));
				}
				else {
					// Buscamos el grupo donde añadir el grupo
					addClassroomGroup($response[$classroomIndex]['classroomGroups'], $rs);
				}
			}
			$rs->Siguiente();
		}
		jsonResponse(200, $response);
	}
	$rs->Cerrar(); 
    }
);

/**
 * @brief    Get lab data
 * @note     Route: /ous/id1/labs/id2, Method: GET
 * @param    id1     OU id.
 * @param    id2     lab id.
 * @return   JSON string with lab parameters
 */
$app->get('/ous/:ouid/labs/:labid', 'validateApiKey',
    function($ouid, $labid) {
	global $cmd;

	$ouid = htmlspecialchars($ouid);
	$labid = htmlspecialchars($labid);
	$cmd->texto = <<<EOD
SELECT COUNT(idordenador) AS defclients, aulas.*, adm.idadministradorcentro
  FROM aulas
 RIGHT JOIN administradores_centros AS adm USING(idcentro)
 RIGHT JOIN usuarios USING(idusuario)
  LEFT JOIN ordenadores USING(idaula)
 WHERE idcentro='$ouid'
   AND idaula='$labid';
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false); // Error al abrir recordset
	$rs->Primero();
	if (checkParameter($rs->campos["idaula"]) and checkAdmin($rs->campos["idadministradorcentro"])) {
		$response['id'] = $rs->campos["idaula"];
		$response['name'] = $rs->campos["nombreaula"];
		$response['location'] = $rs->campos["ubicacion"];
		$response['description'] = $rs->campos["comentarios"];
		$response['inremotepc'] = $rs->campos["inremotepc"]==0 ? false: true;
		$response['capacity'] = $rs->campos["puestos"];
		$response['defclients'] = $rs->campos["defclients"];
		$response['projector'] = $rs->campos["cagnon"]==0 ? false: true;
		$response['board'] = $rs->campos["pizarra"]==0 ? false: true;
		$response['routerip'] = $rs->campos["router"];
		$response['netmask'] = $rs->campos["netmask"];
		$response['ntp'] = $rs->campos["ntp"];
		$response['dns'] = $rs->campos["dns"];
		$response['proxyurl'] = $rs->campos["proxy"];
		switch ($rs->campos["modomul"]) {
			case 1:  $response['mcastmode'] = "half-duplex"; break;
			case 2:  $response['mcastmode'] = "full-duplex"; break;
			default: $response['mcastmode'] = $rs->campos["modomul"];
		}
		$response['mcastip'] = $rs->campos["ipmul"];
		$response['mcastport'] = $rs->campos["pormul"];
		$response['mcastspeed'] = $rs->campos["velmul"];
		$response['p2pmode'] = $rs->campos["modp2p"];
		$response['p2ptime'] = $rs->campos["timep2p"];
		$response['picture'] = $rs->campos["urlfoto"];
		jsonResponse(200, $response);
	}
	$rs->Cerrar(); 
    }
);

// Listar clientes de un aula.
$app->get('/ous/:ouid/labs/:labid/clients', 'validateApiKey',
    function($ouid, $labid) {
	global $cmd;

	$ouid = htmlspecialchars($ouid);
	$labid = htmlspecialchars($labid);
	// Listar los clientes del aula si el usuario de la apikey es admin de su UO.
	$cmd->texto = <<<EOD
SELECT ordenadores.*, adm.idadministradorcentro
  FROM ordenadores
  JOIN aulas USING(idaula)
 RIGHT JOIN administradores_centros AS adm USING(idcentro)
 RIGHT JOIN usuarios USING(idusuario)
 WHERE idcentro='$ouid'
   AND idaula='$labid';
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false);	// Recordset open error.
	$rs->Primero();
	if (checkParameter($rs->campos["idaula"]) and checkAdmin($rs->campos["idadministradorcentro"])) {
		$response['ouid'] = $ouid;
		$response['labid'] = $labid;
		$response = array();
		while (!$rs->EOF) {
			$tmp = array();
			$tmp['id'] = $rs->campos["idordenador"];
			$tmp['name'] = $rs->campos["nombreordenador"];
			$tmp['ip'] = $rs->campos["ip"];
			$tmp['mac'] = $rs->campos["mac"];
			$tmp['ou']['id'] = $ouid;
			$tmp['lab']['id'] = $labid;
			array_push($response, $tmp);
			$rs->Siguiente();
		}
		jsonResponse(200, $response);
	}
	$rs->Cerrar(); 
    }
);

// Obtener datos de un cliente.
$app->get('/ous/:ouid/labs/:labid/clients/:clntid', 'validateApiKey',
    function($ouid, $labid, $clntid) {
	global $cmd;

	$ouid = htmlspecialchars($ouid);
	$labid = htmlspecialchars($labid);
	$clntid = htmlspecialchars($clntid);
	// Obtener datos del cliente del aula si el usuario de la apikey es admin de su UO.
	$cmd->texto = <<<EOD
SELECT ordenadores.*, adm.idadministradorcentro
  FROM ordenadores
  JOIN aulas USING(idaula)
 RIGHT JOIN administradores_centros AS adm USING(idcentro)
 RIGHT JOIN usuarios USING(idusuario)
 WHERE idcentro='$ouid'
   AND idaula='$labid'
   AND idordenador='$clntid';
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false); // Error al abrir recordset
	$rs->Primero();
	if (checkParameter($rs->campos["idordenador"]) and checkParameter($rs->campos["idaula"]) and checkAdmin($rs->campos["idadministradorcentro"])) {
		$response['id'] = $rs->campos["idordenador"];
		$response['name'] = $rs->campos["nombreordenador"];
		$response['serialno'] = $rs->campos["numserie"];
		$response['netiface'] = $rs->campos["netiface"];
		$response['netdriver'] = $rs->campos["netdriver"];
		$response['mac'] = $rs->campos["mac"];
		$response['ip'] = $rs->campos["ip"];
		$response['netmask'] = $rs->campos["mascara"];
		$response['routerip'] = $rs->campos["router"];
		$response['repo']['id'] = $rs->campos["idrepositorio"];
		//$response['hardprofile']['id'] = $rs->campos["idperfilhard"];
		//$response['menu']['id'] = $rs->campos["idmenu"];
		$response['validation'] = $rs->campos["validacion"]==0 ? false: true;
		$response['boottype'] = $rs->campos["arranque"];
		$response['picture'] = $rs->campos["fotoord"];
		jsonResponse(200, $response);
	}
	$rs->Cerrar(); 
    }
);

// Obtener la configuración de hardware de un cliente.
$app->get('/ous/:ouid/labs/:labid/clients/:clntid/hardware', 'validateApiKey',
    function($ouid, $labid, $clntid) {
	global $cmd;

	$ouid = htmlspecialchars($ouid);
	$labid = htmlspecialchars($labid);
	$clntid = htmlspecialchars($clntid);
	$cmd->texto = <<<EOD
SELECT ordenadores.idordenador, ordenadores.nombreordenador,
       tipohardwares.nemonico, hardwares.descripcion
  FROM perfileshard
 RIGHT JOIN ordenadores USING(idperfilhard)
  JOIN perfileshard_hardwares USING(idperfilhard)
  JOIN hardwares ON perfileshard_hardwares.idhardware=hardwares.idhardware
  JOIN tipohardwares ON tipohardwares.idtipohardware=hardwares.idtipohardware
 WHERE ordenadores.idordenador='$clntid'
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false); // Error al abrir recordset
	$rs->Primero();
//	if ($ouid != $rs->campos["idcentro"]) ...
//	if ($labid != $rs->campos["idaula"]) ...
	if (checkParameter($rs->campos["idordenador"])) {
		$response['id'] = $rs->campos["idordenador"];
		$response['name'] = $rs->campos["nombreordenador"];
		$response['hardware'] = array();
		while (!$rs->EOF) {
			$tmp = array();
			$tmp['type'] = $rs->campos["nemonico"];
			$tmp['description'] = $rs->campos["descripcion"];
			array_push($response['hardware'], $tmp);
			$rs->Siguiente();
		}
		jsonResponse(200, $response);
	}
	$rs->Cerrar(); 
    }
);

// Obtener datos de configuración de discos del cliente.
$app->get('/ous/:ouid/labs/:labid/clients/:clntid/diskcfg', 'validateApiKey',
    function($ouid, $labid, $clntid) {
	global $cmd;

	$ouid = htmlspecialchars($ouid);
	$labid = htmlspecialchars($labid);
	$clntid = htmlspecialchars($clntid);
	$cmd->texto = <<<EOD
SELECT ordenadores.idordenador AS clientid, ordenadores.nombreordenador,
       ordenadores_particiones.*, tipospar.tipopar,
       sistemasficheros.nemonico, nombresos.nombreso, imagenes.nombreca,
       (imagenes.revision - ordenadores_particiones.revision) AS difimagen
  FROM ordenadores_particiones
 RIGHT JOIN ordenadores USING(idordenador)
  LEFT JOIN tipospar USING(codpar)
  LEFT JOIN sistemasficheros USING(idsistemafichero)
  LEFT JOIN nombresos USING(idnombreso)
  LEFT JOIN imagenes USING(idimagen)
 WHERE ordenadores.idordenador='$clntid'
 ORDER BY numdisk ASC, numpar ASC;
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false); // Error al abrir recordset
	$rs->Primero();
//	if ($labid != $rs->campos["idaula"]) ...
	if (checkParameter($rs->campos["clientid"])) {
		$response['id'] = $rs->campos["clientid"];
		$response['name'] = $rs->campos["nombreordenador"];
		$response['diskcfg'] = array();
		while (!$rs->EOF) {
			if ($rs->campos["numdisk"] == 0) {
				$rs->Siguiente();
				continue;
			}
			$tmp = array();
			if ($rs->campos["numpar"] == 0) {
				$tmp['disk'] = $rs->campos["numdisk"];
				switch ($rs->campos["codpar"]) {
					case 1:  $tmp['parttable'] = "MSDOS"; break;
					case 2:  $tmp['parttable'] = "GPT"; break;
					case 3:  $tmp['parttable'] = "LVM"; break;
					case 4:  $tmp['parttable'] = "ZPOOL"; break;
					default: $tmp['parttable'] = $rs->campos["codpar"];
				}
				$tmp['size'] = $rs->campos["tamano"];
			} else {
				$tmp['partition'] = $rs->campos["numpar"];
				$tmp['parttype'] = $rs->campos["tipopar"];
				$tmp['filesystem'] = $rs->campos["nemonico"];
				$tmp['size'] = $rs->campos["tamano"];
				$tmp['usage'] = $rs->campos["uso"];
				if ($rs->campos["nombreso"] != null) {
					$tmp['os'] = $rs->campos["nombreso"];
					if ($rs->campos["idimagen"] > 0) {
						$tmp['image']['id'] = $rs->campos["idimagen"];
						$tmp['image']['deploydate'] = $rs->campos["fechadespliegue"];
						// Comprobar si la imagen está actualizada.
						$tmp['image']['updated'] = ($rs->campos["difimagen"]>0 ? "false" : "true");
					}
				}
				//$tmp['cachedata'] = $rs->campos["cache"];
			}
			array_push($response['diskcfg'], $tmp);
			$rs->Siguiente();
		}
		jsonResponse(200, $response);
	}
	$rs->Cerrar(); 
    }
);

// Obtener estado de ejecución del cliente.
$app->get('/ous/:ouid/labs/:labid/clients/:clntid/status', 'validateApiKey',
    function($ouid, $labid, $clntid) {
	global $cmd;
	global $LONCABECERA;
	global $LONHEXPRM;

	// Status mapping.
	$status = array('OFF'=>"off",
			'INI'=>"initializing",
			'OPG'=>"ogclient",
			'BSY'=>"busy",
			'LNX'=>"linux",
			'WIN'=>"windows");
	// Parameters.
	$ouid = htmlspecialchars($ouid);
	$labid = htmlspecialchars($labid);
	$clntid = htmlspecialchars($clntid);

	// Database query.
	$cmd->texto = <<<EOD
SELECT serv.ipserveradm, serv.portserveradm, clnt.idordenador, clnt.ip
  FROM entornos AS serv, ordenadores AS clnt
 WHERE clnt.idordenador='$clntid';
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false); // Error al abrir recordset
	$rs->Primero();
	if (checkParameter($rs->campos["idordenador"])) {
		// First, try to connect to ogAdmCleint service.
		$serverip = $rs->campos["ipserveradm"];
		$serverport = $rs->campos["portserveradm"];
		$clientid = $rs->campos["idordenador"];
		$clientip = $rs->campos["ip"];

		// Connect to reset client's status.
		$reqframe = "nfn=Sondeo\r".
			    "ido=$clientid\r".
			    "iph=$clientip\r";
		$result = sendCommand($serverip, $serverport, $reqframe, $values);

		// Connect to fetch client's status.
		// Asuming client is off by default.
		$values["tso"]="OFF";
		// Iterate to check client's status.
		// Exit if status!=OFF or end iterations (status=OFF).
		$maxIter = 30;
		for ($i=1; $i<$maxIter and preg_match('/OFF/', $values["tso"]); $i++) {
			// Connect to check status.
			$reqframe = "nfn=respuestaSondeo\r".
				    "ido=$clientid\r".
				    "iph=$clientip\r";
			$result = sendCommand($serverip, $serverport, $reqframe, $values);
			// Wait until next checking (0.1 ms).
			usleep(100000);
		}

		// Parse status response.
		if ($result) {
			// Check status type.
			if (checkParameter($values["tso"])) {
				// Compose JSON response.
				$response['id'] = $clientid;
				$response['ip'] = $clientip;
				$stat = array();
				preg_match('/\/[A-Z]*;/', $values["tso"], $stat);
				// Check if data exists.
				if (empty($stat[0]) or preg_match('/OFF/', $stat[0])) {
					// If no data, check OGAgent API connection.
					$url = "https://$clientip:8000/opengnsys/status";
					$result = multiRequest(Array($url));
					if (empty($result[0])) {
						// Client is off.
						$response['status'] = $status['OFF'];
					} else {
						// Get status and session data.
						$data = json_decode($result[0]);
						if (isset($status[$data->status])) {
							$response['status'] = $status[$data->status];
							$response['loggedin'] = $data->loggedin;
						}
					}
				} else {
					$response['status'] = $status[substr($stat[0], 1, 3)];
				}
				if (empty($response['status'])) {
					$response['status'] = "unknown";
				}
				jsonResponse(200, $response);
			}
		} else {
			// Access error.
			$response['message'] = "Cannot access to OpenGnsys server";
			jsonResponse(500, $response);
		}
	}
	$rs->Cerrar(); 
    }
);


// Listar repositorios.
$app->get('/ous/:ouid/repos', 'validateApiKey',
    function($ouid) {
	global $cmd;

	$ouid = htmlspecialchars($ouid);
	// Listar las salas de la UO si el usuario de la apikey es su admin.
	// Consulta temporal,
	$cmd->texto = "SELECT * FROM repositorios WHERE idcentro='$ouid';";
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false); // Error al abrir recordset
	$rs->Primero();
	// Comprobar que exista la UO.
	if (checkParameter($rs->campos["idcentro"])) {
		$response = array();
		while (!$rs->EOF) {
			$tmp = array();
			$tmp['id'] = $rs->campos["idrepositorio"];
			$tmp['name'] = $rs->campos["nombrerepositorio"];
			$tmp['ou']['id'] = $ouid;
			array_push($response, $tmp);
			$rs->Siguiente();
		}
		jsonResponse(200, $response);
	}
	$rs->Cerrar(); 
    }
);

// Obtener datos de un repositorio.
$app->get('/ous/:ouid/repos/:repoid', 'validateApiKey',
    function($ouid, $repoid) {
	global $cmd;

	$ouid = htmlspecialchars($ouid);
	$repoid = htmlspecialchars($repoid);
	$cmd->texto = "SELECT * FROM repositorios WHERE idrepositorio='$repoid';";
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false); // Error al abrir recordset
	$rs->Primero();
	// Comprobar que exista el repositorio.
	if (checkParameter($rs->campos["idrepositorio"])) {
		$response['id'] = $rs->campos["idrepositorio"];
		$response['name'] = $rs->campos["nombrerepositorio"];
		$response['description'] = $rs->campos["comentarios"];
		$response['ip'] = $rs->campos["ip"];
		//$response['port'] = $rs->campos["puertorepo"];
		jsonResponse(200, $response);
	}
	$rs->Cerrar(); 
    }
);

// Listar imágenes.
$app->get('/ous/:ouid/images', 'validateApiKey',
    function($ouid) {
	global $cmd;

	$ouid = htmlspecialchars($ouid);
	// Listar las salas de la UO si el usuario de la apikey es su admin.
	// Consulta temporal,
	$cmd->texto = "SELECT * FROM imagenes WHERE idcentro='$ouid';";
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false); // Error al abrir recordset
	// Comprobar que exista la UO.
	$rs->Primero();
	if (checkParameter($rs->campos["idcentro"])) {
		$response = array();
		while (!$rs->EOF) {
			$tmp = array();
			$tmp['id'] = $rs->campos["idimagen"];
			$tmp['name'] = $rs->campos["nombreca"];
			$tmp['inremotepc'] = $rs->campos["inremotepc"]==0 ? false: true;
			$tmp['ou']['id'] = $ouid;
			array_push($response, $tmp);
			$rs->Siguiente();
		}
		jsonResponse(200, $response);
	}
    }
);

// Obtener datos de una imagen.
$app->get('/ous/:ouid/images/:imgid', 'validateApiKey',
    function($ouid, $imgid) {
	global $cmd;

	$ouid = htmlspecialchars($ouid);
	$imgid = htmlspecialchars($imgid);
	$cmd->texto = "SELECT * FROM imagenes WHERE idimagen='$imgid';";
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false); // Error al abrir recordset
	$rs->Primero();
	// Comprobar que exista el repositorio.
	if (checkParameter($rs->campos["idimagen"])) {
		$response['id'] = $rs->campos["idimagen"];
		$response['name'] = $rs->campos["nombreca"];
		$response['description'] = $rs->campos["descripcion"];
		$response['comments'] = $rs->campos["comentarios"];
		$response['inremotepc'] = $rs->campos["inremotepc"]==0 ? false: true;
		$response['repo']['id'] = $rs->campos["idrepositorio"];
		switch ($rs->campos["tipo"]) {
			case 1:  $response['type'] = "monolithic"; break;
			case 2:  $response['type'] = "base"; break;
			case 3:  $response['type'] = "incremental";
				 $response['baseimg'] = $rs->campos["imagenid"];
				 $response['path'] = $rs->campos["ruta"];
				 break;
			default: $response['type'] = $rs->campos["tipo"];
		}
		if ($rs->campos["idordenador"] != 0) {
			$response['client']['id'] = $rs->campos["idordenador"];
			$response['client']['disk'] = $rs->campos["numdisk"];
			$response['client']['partition'] = $rs->campos["numpar"];
			$response['creationdate'] = $rs->campos["fechacreacion"];
			$response['release'] = $rs->campos["revision"];
		}
		jsonResponse(200, $response);
	}
	$rs->Cerrar(); 
    }
);

// Lista de softeare instalado en una imagen.
$app->get('/ous/:ouid/images/:imgid/software', 'validateApiKey',
    function($ouid, $imgid) {
	global $cmd;

	$ouid = htmlspecialchars($ouid);
	$imgid = htmlspecialchars($imgid);
	$cmd->texto = <<<EOD
SELECT imagenes.idimagen, imagenes.nombreca, nombresos.nombreso, softwares.descripcion
  FROM perfilessoft
 RIGHT JOIN imagenes USING(idperfilsoft)
  LEFT JOIN nombresos USING(idnombreso)
  LEFT JOIN perfilessoft_softwares USING(idperfilsoft)
  LEFT JOIN softwares USING(idsoftware)
 WHERE imagenes.idimagen='$imgid'
 ORDER BY softwares.descripcion ASC;
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false);	// Error al abrir recordset
	$rs->Primero();
	// Comprobar que exista el repositorio.
	if (checkParameter($rs->campos["idimagen"])) {
		$response['id'] = $rs->campos["idimagen"];
		$response['name'] = $rs->campos["nombreca"];
		$response['os'] = $rs->campos["nombreso"];
		//$response['ostype'] = Tipo de SO (agrupar en array con nombre SO).
		$response['software'] = array();
		while (!$rs->EOF) {
			if ($rs->campos["descripcion"] == null) {
				$rs->Siguiente();
				continue;
			}
			$tmp = array();
			$tmp['application'] = $rs->campos["descripcion"];
			array_push($response['software'], $tmp);
			$rs->Siguiente();
		}
		jsonResponse(200, $response);
	}
	$rs->Cerrar(); 
    }
);

// Arrancar un ordenador con una imagen instalada, elegido al azar.
$app->get('/ous/:id1/images/:id2/boot', 'validateApiKey',
    function($ouid, $imageid) {
	global $cmd;
	global $AMBITO_ORDENADORES;
	global $EJECUCION_COMANDO;
	global $ACCION_INICIADA;
	global $ACCION_SINRESULTADO;

	// Pparameters.
	$ouid = htmlspecialchars($ouid);
	$imegeid = htmlspecialchars($imageid);
	// Boot 1 client.
	$nclients = 1;

	// Query: server data and all clients' boot data availabe for Remote PC with this image installed (random order).
	$cmd->texto = <<<EOD
SELECT s.ipserveradm, s.portserveradm,
       c.idordenador, c.ip, c.mac, p.numdisk, p.numpar
  FROM entornos AS s, ordenadores AS c
  JOIN aulas USING(idaula)
  JOIN centros USING(idcentro)
  JOIN ordenadores_particiones AS p USING(idordenador)
  JOIN imagenes USING(idimagen)
 WHERE centros.idcentro='$ouid'
   AND aulas.inremotepc=1
   AND imagenes.idimagen='$imageid'
   AND imagenes.inremotepc=1
 ORDER BY RAND();
EOD;
	$rs=new Recordset;
	$rs->Comando=&$cmd;
	if (!$rs->Abrir()) return(false);	// Error oppening recordset.
	$rs->Primero();
	if (checkParameter($rs->campos["ipserveradm"])) {

		$response['imageid'] = $imageid;
		$response['sendto'] = array();

		// AVISO: Procesar datos del servidor (solo 1er registro).

		$serverip = $rs->campos["ipserveradm"];
		$serverport = $rs->campos["portserveradm"];

		// AVISO: Procesar datos de los clientes.

		$clientid = array();
		$clientip = array();
		$clientmac = array();
		$clientdisk = array();
		$clientpart = array();
		while (!$rs->EOF) {
			array_push($clientid, $rs->campos["idordenador"]);
			array_push($clientip, $rs->campos["ip"]);
			array_push($clientmac, $rs->campos["mac"]);
			array_push($clientdisk, $rs->campos["numdisk"]);
			array_push($clientpart, $rs->campos["numpar"]);
			$rs->Siguiente();
		}
		$rs->Cerrar(); 

		// AVISO: consultar el estado de todos los clientes y
		//        quitar aquellos que no tengan "OFF", "OPG" o ""
		//        (estudiar si incluir los "BSY")

		// Reset clients' status.
		$reqframe = "nfn=Sondeo\r".
			    "ido=".implode(',', $clientid)."\r".
			    "iph=".implode(';', $clientip)."\r";
		sendCommand($serverip, $serverport, $reqframe, $values);
		 // Wait to get response.
		sleep(3);
		// Connect to check status.
		$reqframe = "nfn=respuestaSondeo\r".
			    "ido=".implode(',', $clientid)."\r".
			    "iph=".implode(';', $clientip)."\r";
		sendCommand($serverip, $serverport, $reqframe, $values);
		// Check status type.
		if (isset($values["tso"])) {
			preg_match_all('/[A-Z]{3}/', $values["tso"], $stat);
		}
		if (isset($stat[0])) {
			for ($i=0; $i<sizeof($stat[0]); $i++) {
				if (! in_array($stat[0][$i], array("OFF", "OPG", ""))) {
					unset($clientid[$i]);
					unset($clientip[$i]);
					unset($clientmac[$i]);
					unset($clientdisk[$i]);
					unset($clientpart[$i]);
				}
			}
		}

		// AVISO: el siguiente código inicia un único cliente.
		//        Para iniciar varios: 
		//	  - id. clientes separados por carácter ','.
		//	  - IP clientes separadas por carácter ';'
		//	  - MAC clientes separadas por carácter ';'

		// Executing boot command.
		$reqframe = "nfn=Arrancar\r".
			    "ido=".implode(',', $clientid)."\r".
			    "iph=".implode(';', $clientip)."\r".
			    "mac=".implode(';', $clientmac)."\r".
			    "mar=1\r";
echo "req=".str_replace("\r"," ",$reqframe).".\n";
		sendCommand($serverip, $serverport, $reqframe, $values);
		if ($values["res"]) {
print_r($values);
			$tmp = array();
			for ($i=0, $boot=0; $i<sizeof($clientid) and $boot!=1; $i++) {
				$reqframe = "nfn=IniciarSesion\r".
					    "ido=".$clientid[$i]."\r".
					    "iph=".$clientip[$i]."\r".
					    "dsk=".$clientdisk[$i]."\r".
					    "par=".$clientpart[$i]."\r";
echo "i=$i: req=".str_replace("\r"," ",$reqframe).".\n";
				sendCommand($serverip, $serverport, $reqframe, $values);
				if ($values["res"]) {

					// AVISO: incluir comando Iniciar sesión en cola de acciones.
					$timestamp=time();
					$cmd->texto = <<<EOD
INSERT INTO acciones
	SET tipoaccion=$EJECUCION_COMANDO,
	    idtipoaccion=9,
	    idcomando=9,
	    parametros='nfn=IniciarSesion\rdsk=$clientdisk[$i]\rpar=$clientpart[$i]',
	    descriaccion='RemotePC Session',
	    idordenador=$clientid[$i],
	    ip='$clientip[$i]',
	    sesion=$timestamp,
	    fechahorareg=NOW(),
	    estado=$ACCION_INICIADA,
	    resultado=$ACCION_SINRESULTADO,
	    ambito=$AMBITO_ORDENADORES,
	    idambito=$clientid[$i],
	    restrambito='$clientip[$i]',
	    idcentro=$ouid;
EOD;
					$result = $cmd->Ejecutar();
					if ($result) {
						$tmp['id'] = $clientid[$i];
						$tmp['ip'] = $clientip[$i];
						$tmp['mac'] = $clientmac[$i];
						array_push($response['sendto'], $tmp);
						$boot = 1;
					}
				}
			}
		}
		jsonResponse(200, $response);
	}
    }
);
// Alternativa como método GET.
//$app->get('/ous/:id1/images/:id2/boot/:number', 'validateApiKey',
//    function($ouid, $imageid, $number) {
//
//   }
//);

?>