source: admin/WebConsole/rest/remotepc.php @ bb992f9

Last change on this file since bb992f9 was c607df7, checked in by Ramón M. Gómez <ramongomez@…>, 5 years ago

#992: Set/unset URL to release a client for remote access.

  • Property mode set to 100644
File size: 20.7 KB
Line 
1<?php
2/**
3 * @file    remotepc.php
4 * @brief   OpenGnsys Server REST API consumed by UDS Server for Remote PC implementation.
5 * @warning All input and output messages are formatted in JSON.
6 * @note    Some ideas are based on article "How to create REST API for Android app using PHP, Slim and MySQL" by Ravi Tamada, thanx.
7 * @license GNU GPLv3+
8 * @author  Ramón M. Gómez, ETSII Univ. Sevilla
9 * @version 1.1.0 - First version
10 * @date    2017-02-01
11 */
12
13// OGAgent sessions log file.
14define('REMOTEPC_LOGFILE', '/opt/opengnsys/log/remotepc.log');
15
16// Function to write a line into log file.
17function writeRemotepcLog($message = "") {
18        file_put_contents(REMOTEPC_LOGFILE, date(DATE_ISO8601).": $message\n", FILE_APPEND);
19}
20
21
22// REST routes.
23
24/**
25 * @brief    Reserve a client with an installed image and the older reservation time, then send a boot/reboot operation depending on its status.
26 * @warning  If "lab" parameter is specified, then choose a client from this lab.
27 * @note     Route: /ous/:ouid/images/:imageid/reserve, Method: POST
28 * @param    integer ouid      OU identificator
29 * @param    integer imageid   image identificator
30 * @note     Input JSON message: {"labid":int_labid,"maxtime":int_hours}
31 */
32$app->post('/ous/:ouid/images/:imageid/reserve(/)', 'validateApiKey',
33    function($ouid, $imageid) use ($app) {
34        global $cmd;
35        global $AMBITO_ORDENADORES;
36        global $EJECUCION_COMANDO;
37        global $ACCION_INICIADA;
38        global $ACCION_FINALIZADA;
39        global $ACCION_SINRESULTADO;
40        global $ACCION_FALLIDA;
41        global $userid;
42        $response = Array();
43        $ogagent = Array();
44        $repo = Array();
45
46        if ($app->settings['debug'])
47                writeRemotepcLog($app->request()->getResourceUri(). ": Init.");
48        // Checking parameters.
49        try {
50                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
51                        throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
52                }
53                if (!checkIds($ouid, $imageid)) {
54                        throw new Exception("Ids. must be positive integers");
55                }
56                // Reading POST parameters in JSON format.
57                $input = json_decode($app->request()->getBody());
58                // Default: no lab. filter.
59                if (isset($input->labid)) {
60                        $labid = $input->labid != "0" ? $input->labid : '%';
61                } else {
62                        $labid = '%';
63                }
64                $maxtime = isset($input->maxtime) ? $input->maxtime : 24;       // Default: 24 h.
65                $opts = Array('options' => Array('min_range' => 1));    // Check for int>0
66                if (filter_var($labid, FILTER_VALIDATE_INT, $opts) === false and $labid !== '%') {
67                        throw new Exception("Lab id. must be positive integer");
68                }
69                if (filter_var($maxtime, FILTER_VALIDATE_INT, $opts) === false) {
70                        throw new Exception("Time must be positive integer (in hours)");
71                }
72        } catch (Exception $e) {
73                // Communication error.
74                $response["message"] = $e->getMessage();
75                if ($app->settings['debug'])
76                        writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
77                jsonResponse(400, $response);
78                $app->stop();
79        }
80
81        if ($app->settings['debug'])
82                writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: labid=$labid, maxtime=$maxtime");
83        // Choose older not-reserved client with image installed and get ogAdmServer data.
84        $cmd->texto = <<<EOD
85SELECT adm.idusuario, ordenadores.idordenador, ordenadores.nombreordenador, ordenadores.ip,
86       ordenadores.mac, ordenadores.agentkey, par.numdisk, par.numpar,
87       aulas.idaula, aulas.idcentro, repo.ip AS repoip, repo.apikey AS repokey
88  FROM ordenadores
89  JOIN aulas USING(idaula)
90 RIGHT JOIN administradores_centros AS adm USING(idcentro)
91 RIGHT JOIN usuarios USING(idusuario)
92 RIGHT JOIN ordenadores_particiones AS par USING(idordenador)
93 RIGHT JOIN imagenes USING(idimagen)
94 RIGHT JOIN repositorios AS repo ON repo.idrepositorio = ordenadores.idrepositorio
95  LEFT JOIN remotepc ON remotepc.id=ordenadores.idordenador
96 WHERE adm.idusuario = '$userid'
97   AND aulas.idcentro = '$ouid' AND aulas.idaula LIKE '$labid' AND aulas.inremotepc = 1
98   AND ordenadores.maintenance = 0
99   AND imagenes.idimagen = '$imageid' AND imagenes.inremotepc = 1
100   AND (remotepc.reserved < NOW() OR ISNULL(reserved))
101 ORDER BY remotepc.reserved ASC LIMIT 1;
102EOD;
103        $rs=new Recordset;
104        $rs->Comando=&$cmd;
105        if (!$rs->Abrir()) return(false);       // Error opening recordset.
106        // Check if user is admin and client exists.
107        $rs->Primero();
108        if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
109                // Read query data.
110                $clntid = $rs->campos["idordenador"];
111                $clntname = $rs->campos["nombreordenador"];
112                $clntip = $rs->campos["ip"];
113                $clntmac = $rs->campos["mac"];
114                $agentkey = $rs->campos["agentkey"];
115                $disk = $rs->campos["numdisk"];
116                $part = $rs->campos["numpar"];
117                $labid = $rs->campos["idaula"];
118                $ouid = $rs->campos["idcentro"];
119                $repoip = $rs->campos["repoip"];
120                $repokey = $rs->campos["repokey"];
121                // Check client's status.
122                $ogagent[$clntip]['url'] = "https://$clntip:8000/opengnsys/status";
123                if ($app->settings['debug'])
124                        writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent status, url=".$ogagent[$clntip]['url'].".");
125                $result = multiRequest($ogagent);
126                if (empty($result[$clntip]['data'])) {
127                        // Client is off, send WOL command to ogAdmServer.
128                        // TODO: if client is busy?????
129                        if ($app->settings['debug'])
130                                writeRemotepcLog($app->request()->getResourceUri(). ": Send boot command through ogAdmServer: iph=$clntip,mac=$clntmac.");
131                        wol(1, [$clntmac], [$clntip]);
132                        // Send WOL command to client repository.
133                        $repo[$repoip]['url'] = "https://$repoip/opengnsys/rest/repository/poweron";
134                        $repo[$repoip]['header'] = Array("Authorization: ".$repokey);
135                        $repo[$repoip]['post'] = '{"macs": ["'.$clntmac.'"], "ips": ["'.$clntip.'"]}';
136                        if ($app->settings['debug'])
137                                writeRemotepcLog($app->request()->getResourceUri(). ": Send Boot command through repo: repo=$repoip, ip=$clntip,mac=$clntmac.");
138                        $result = multiRequest($repo);
139                        // ... (check response)
140                        //if ($result[$repoip]['code'] != 200) {
141                        // ...
142                } else {
143                        // Client is on, send a rieboot command to its OGAgent.
144                        $ogagent[$clntip]['url'] = "https://$clntip:8000/opengnsys/reboot";
145                        $ogagent[$clntip]['header'] = Array("Authorization: ".$agentkey);
146                        if ($app->settings['debug'])
147                                writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent reboot, url=".$ogagent[$clntip]['url'].".");
148                        $result = multiRequest($ogagent);
149                        // ... (check response)
150                        //if ($result[$clntip]['code'] != 200) {
151                        // ...
152                }
153                // DB Transaction: mark choosed client as reserved and
154                // create an init session command into client's actions queue.
155                $cmd->texto = "START TRANSACTION;";
156                $cmd->Ejecutar();
157                $timestamp = time();
158                $cmd->texto = <<<EOD
159INSERT INTO remotepc
160   SET id = '$clntid', reserved = NOW() + INTERVAL $maxtime HOUR,
161       urllogin = NULL, urllogout = NULL, urlrelease = NULL
162    ON DUPLICATE KEY UPDATE
163       id = VALUES(id), reserved = VALUES(reserved),
164       urllogin = VALUES(urllogin), urllogout = VALUES(urllogout),
165       urlrelease = VALUES(urlrelease);
166EOD;
167                $t1 = $cmd->Ejecutar();
168                $cmd->texto = <<<EOD
169INSERT INTO acciones
170   SET tipoaccion=$EJECUCION_COMANDO,
171       idtipoaccion=9,
172       idcomando=9,
173       parametros='nfn=IniciarSesion\rdsk=$disk\rpar=$part',
174       descriaccion='RemotePC Session',
175       idordenador=$clntid,
176       ip='$clntip',
177       sesion=$timestamp,
178       fechahorareg=NOW(),
179       estado=$ACCION_INICIADA,
180       resultado=$ACCION_SINRESULTADO,
181       ambito=$AMBITO_ORDENADORES,
182       idambito=$clntid,
183       restrambito='$clntip',
184       idcentro=$ouid;
185EOD;
186                $t2 = $cmd->Ejecutar();
187                // Create event to remove reservation on timeout (15 min.).
188                $timeout = "15 MINUTE";
189                $cmd->texto = <<<EOD
190CREATE EVENT e_timeout_$clntid
191       ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL $timeout DO
192       BEGIN
193            SET @action_id = NULL;
194            UPDATE acciones
195               SET estado = $ACCION_FINALIZADA, resultado = $ACCION_FALLIDA,
196                   descrinotificacion = 'Timeout'
197             WHERE descriaccion = 'RemotePC Session' AND estado = $ACCION_INICIADA
198               AND idordenador = '$clntid'
199               AND (SELECT @action_id := idaccion);
200            IF @action_id IS NOT NULL THEN
201               UPDATE remotepc
202                  SET reserved = NOW() - INTERVAL 1 SECOND,
203                      urllogin = NULL, urllogout = NULL, urlrelease = NULL
204                WHERE id = '$clntid';
205               DELETE FROM acciones
206                WHERE idaccion = @action_id;
207            END IF;
208       END
209EOD;
210                $t3 = $cmd->Ejecutar();
211                if ($t1 and $t2 and $t3) {
212                        // Commit transaction on success.
213                        $cmd->texto = "COMMIT;";
214                        $cmd->Ejecutar();
215                        if ($app->settings['debug'])
216                                writeRemotepcLog($app->request()->getResourceUri(). ": DB tables and events updated, clntid=$clntid.");
217                        // Send init session command if client is booted on ogLive.
218                        if ($app->settings['debug'])
219                                writeRemotepcLog($app->request()->getResourceUri(). ": Send Init Session command to ogAdmClient, ido=$clntid,iph=$clntip,dsk=$disk,par=$part.");
220                        session($clntip, "$disk\r$part");
221                        // Compose JSON response.
222                        $response['id'] = (int)$clntid;
223                        $response['name'] = $clntname;
224                        $response['ip'] = $clntip;
225                        $response['mac'] = $clntmac;
226                        $response['lab']['id'] = $labid;
227                        $response['ou']['id'] = (int)$ouid;
228                        if ($app->settings['debug'])
229                                writeRemotepcLog($app->request()->getResourceUri(). ": Response, ".var_export($response,true).".");
230                        jsonResponse(200, $response);
231                } else {
232                        // Roll-back transaction on DB error.
233                        $cmd->texto = "ROLLBACK;";
234                        $cmd->Ejecutar();
235                        // Error message.
236                        $response["message"] = "Database error: $t1, $t2, $t3";
237                        if ($app->settings['debug'])
238                                writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
239                        jsonResponse(400, $response);
240                }
241        } else {
242                if ($app->settings['debug'])
243                        writeRemotepcLog($app->request()->getResourceUri(). ": UNASSIGNED");
244        }
245        $rs->Cerrar();
246        $app->stop();
247    }
248);
249
250
251/**
252 * @brief    Store UDS server URLs to resend some events recieved from OGAgent.
253 * @note     Route: /ous/:ouid/labs/:labid/clients/:clntid/events, Method: POST
254 * @param    string urlLogin   URL to redirect login notification.
255 * @param    string urlLogout  URL to redirect logout notification.
256 * @param    string urlRelease URL to release a session
257 * @warning  Events parameters will be stored in a new "remotepc" table.
258 */
259$app->post('/ous/:ouid/labs/:labid/clients/:clntid/events', 'validateApiKey',
260    function($ouid, $labid, $clntid) use ($app) {
261        global $cmd;
262        global $userid;
263        $response = Array();
264
265        if ($app->settings['debug'])
266                writeRemotepcLog($app->request()->getResourceUri(). ": Init.");
267        // Checking parameters.
268        try {
269                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
270                        throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
271                }
272                if (!checkIds($ouid, $labid, $clntid)) {
273                        throw new Exception("Ids. must be positive integers");
274                }
275                // Reading JSON parameters.
276                $input = json_decode($app->request()->getBody());
277                $urlLogin = htmlspecialchars($input->urlLogin);
278                $urlLogout = htmlspecialchars($input->urlLogout);
279                $urlRelease = htmlspecialchars($input->urlRelease ?? "");
280                if (filter_var($urlLogin, FILTER_VALIDATE_URL) === false) {
281                        throw new Exception("Must be a valid URL for login notification");
282                }
283                if (filter_var($urlLogout, FILTER_VALIDATE_URL) === false) {
284                        throw new Exception("Must be a valid URL for logout notification");
285                }
286        } catch (Exception $e) {
287                // Error message.
288                $response["message"] = $e->getMessage();
289                if ($app->settings['debug'])
290                        writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
291                jsonResponse(400, $response);
292                $app->stop();
293        }
294
295        if ($app->settings['debug'])
296                writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: urlLogin=$urlLogin, urlLogout=$urlLogout");
297        // Select client data for UDS compatibility.
298        $cmd->texto = <<<EOD
299SELECT adm.idusuario, ordenadores.idordenador, remotepc.*
300  FROM remotepc
301 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
302  JOIN aulas USING(idaula)
303 RIGHT JOIN administradores_centros AS adm USING(idcentro)
304 RIGHT JOIN usuarios USING(idusuario)
305 WHERE adm.idusuario = '$userid'
306   AND idcentro = '$ouid' AND aulas.idaula ='$labid'
307   AND ordenadores.idordenador = '$clntid';
308EOD;
309        $rs=new Recordset;
310        $rs->Comando=&$cmd;
311        if (!$rs->Abrir()) return(false);       // Error opening recordset.
312        // Check if user is admin and client exists.
313        $rs->Primero();
314        if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
315                // Check if client is reserved.
316                if (! is_null($rs->campos["reserved"])) {
317                        // Updating DB if client is reserved.
318                        $cmd->CreaParametro("@urllogin", $urlLogin, 0);
319                        $cmd->CreaParametro("@urllogout", $urlLogout, 0);
320                        $cmd->CreaParametro("@urlrelease", $urlRelease, 0);
321                        $cmd->texto = <<<EOD
322UPDATE remotepc
323   SET urllogin = @urllogin, urllogout = @urllogout, urlrelease = NULLIF(@urlrelease, '')
324 WHERE id='$clntid';
325EOD;
326                        if ($cmd->Ejecutar()) {
327                                // Confirm operation.
328                                $response = "";
329                                jsonResponse(200, $response);
330                        } else {
331                                // Error message.
332                                $response["message"] = "Database error";
333                                jsonResponse(400, $response);
334                        }
335                } else {
336                        // Error message.
337                        $response["message"] = "Client is not reserved";
338                        jsonResponse(400, $response);
339                }
340        }
341        $rs->Cerrar();
342        $app->stop();
343    }
344);
345
346
347/*
348 * @brief    Store session time (in sec).
349 * @note     Route: /ous/:ouid/labs/:labid/clients/:clntid/session, Method: POST
350 * @param    int    deadLine   maximum session time, in seconds (0 for unlimited)
351 * @warning  Parameters will be stored in a new "remotepc" table.
352 */
353$app->post('/ous/:ouid/labs/:labid/clients/:clntid/session', 'validateApiKey',
354    function($ouid, $labid, $clntid) use ($app) {
355        global $cmd;
356        global $userid;
357        $response = Array();
358
359        if ($app->settings['debug'])
360                writeRemotepcLog($app->request()->getResourceUri(). ": Init.");
361        // Checking parameters.
362        try {
363                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
364                        throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
365                }
366                if (!checkIds($ouid, $labid, $clntid)) {
367                        throw new Exception("Ids. must be positive integers");
368                }
369                // Reading JSON parameters.
370                $input = json_decode($app->request()->getBody());
371                $deadLine = $input->deadLine;
372                if (filter_var($deadLine, FILTER_VALIDATE_INT) === false) {
373                        throw new Exception("Deadline must be integer");
374                }
375                if ($deadLine < 0) {
376                        throw new Exception("Resource unavailable");
377                }
378        } catch (Exception $e) {
379                // Error message.
380                $response["message"] = $e->getMessage();
381                if ($app->settings['debug'])
382                        writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
383                jsonResponse(400, $response);
384                $app->stop();
385        }
386
387        if ($app->settings['debug'])
388                writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: deadLine=$deadLine");
389        // Get client's data.
390        $cmd->texto = <<<EOD
391SELECT adm.idusuario, ordenadores.idordenador, remotepc.*
392  FROM remotepc
393 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
394  JOIN aulas USING(idaula)
395 RIGHT JOIN administradores_centros AS adm USING(idcentro)
396 WHERE adm.idusuario = '$userid'
397   AND aulas.idcentro = '$ouid' AND aulas.idaula = '$labid'
398   AND ordenadores.idordenador = '$clntid';
399EOD;
400        $rs=new Recordset;
401        $rs->Comando=&$cmd;
402        if (!$rs->Abrir()) return(false);       // Error opening recordset.
403        // Check if user is admin and client exists.
404        $rs->Primero();
405        if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
406                // Check if client is reserved.
407                if (! is_null($rs->campos["urllogin"])) {
408                        // Read query data.
409                        $clntid = $rs->campos["idordenador"];
410                        # Removing previous commands from OGAgent operations queue.
411                        if ($app->settings['debug'])
412                                writeRemotepcLog($app->request()->getResourceUri(). ": Updating database.");
413                        $cmd->texto = <<<EOD
414DELETE FROM ogagent_queue
415 WHERE clientid = '$clntid' AND operation IN ('popup-10', 'popup-5', 'poweroff');
416EOD;
417                        $cmd->Ejecutar();
418                        # Add new commands to OGAgent operations queue.
419                        $cmd->texto = "INSERT INTO ogagent_queue (clientid, exectime, operation) VALUES";
420                        if ($deadLine > 600) {
421                                # Add reminder 10 min. before deadline.
422                                $cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND - INTERVAL 10 MINUTE, 'popup-10'),";
423                        }
424                        if ($deadLine > 300) {
425                                # Add reminder 5 min. before deadline.
426                                $cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND - INTERVAL 5 MINUTE, 'popup-5'),";
427                        }
428                        # Add power off command at deadline time.
429                        $cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND, 'poweroff');";
430                        if ($deadLine == 0 or $cmd->Ejecutar()) {
431                                // Confirm operation.
432                                $cmd->texto = "";
433                                $response = "";
434                                jsonResponse(200, $response);
435                        } else {
436                                // Error message.
437                                $response["message"] = "Database error";
438                                jsonResponse(400, $response);
439                        }
440                } else {
441                        // Error message.
442                        $response["message"] = "Client is not reserved";
443                        jsonResponse(400, $response);
444                }
445        } else {
446                // Error message.
447                $response["message"] = "Client does not exist";
448                jsonResponse(404, $response);
449        }
450        $rs->Cerrar();
451    }
452);
453
454
455/**
456 * @brief    Store UDS server URLs to resend some events recieved from OGAgent.
457 * @brief    Unreserve a client and send a poweroff operation.
458 * @note     Route: /ous/:ouid/labs/:labid/clients/:clntid/unreserve, Method: DELETE
459 */
460$app->delete('/ous/:ouid/labs/:labid/clients/:clntid/unreserve', 'validateApiKey',
461    function($ouid, $labid, $clntid) use ($app) {
462        global $cmd;
463        global $userid;
464        global $ACCION_INICIADA;
465        $response = Array();
466        $ogagent = Array();
467
468        if ($app->settings['debug'])
469                writeRemotepcLog($app->request()->getResourceUri(). ": Init.");
470        // Checking parameters.
471        try {
472                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
473                        throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
474                }
475                if (!checkIds($ouid, $labid, $clntid)) {
476                        throw new Exception("Ids. must be positive integers");
477                }
478        } catch (Exception $e) {
479                // Error message.
480                $response["message"] = $e->getMessage();
481                if ($app->settings['debug'])
482                        writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
483                jsonResponse(400, $response);
484                $app->stop();
485        }
486
487        // Select client data for UDS compatibility.
488        $cmd->texto = <<<EOD
489SELECT adm.idusuario, ordenadores.idordenador, ordenadores.ip, ordenadores.agentkey, remotepc.reserved
490  FROM remotepc
491 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
492  JOIN aulas USING(idaula)
493 RIGHT JOIN administradores_centros AS adm USING(idcentro)
494 RIGHT JOIN usuarios USING(idusuario)
495 WHERE adm.idusuario = '$userid'
496   AND idcentro = '$ouid' AND aulas.idaula ='$labid'
497   AND ordenadores.idordenador = '$clntid';
498EOD;
499        $rs=new Recordset;
500        $rs->Comando=&$cmd;
501        if (!$rs->Abrir()) return(false);       // Error opening recordset.
502        // Check if user is admin and client exists.
503        $rs->Primero();
504        if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
505                // Check if client is reserved.
506                if (! is_null($rs->campos["reserved"])) {
507                        // Read query data.
508                        $clntip = $rs->campos["ip"];
509                        $agentkey = $rs->campos["agentkey"];
510                        // DB Transaction: set reservation time to the past, remove pending
511                        // boot commands from client's and agent's queues, and drop its event.
512                        if ($app->settings['debug'])
513                                writeRemotepcLog($app->request()->getResourceUri(). ": Updating database.");
514                        $cmd->texto = "START TRANSACTION;";
515                        $cmd->Ejecutar();
516                        $cmd->texto = <<<EOD
517UPDATE remotepc
518   SET reserved = NOW() - INTERVAL 1 SECOND,
519       urllogin = NULL, urllogout = NULL, urlrelease = NULL
520 WHERE id = '$clntid';
521EOD;
522                        $cmd->Ejecutar();
523                        $cmd->texto = <<<EOD
524DELETE FROM acciones
525 WHERE idordenador = '$clntid'
526   AND descriaccion = 'RemotePC Session';
527EOD;
528                        $cmd->Ejecutar();
529                        $cmd->texto = <<<EOD
530DELETE FROM ogagent_queue
531 WHERE clientid = '$clntid' AND command IN ('popup-10', 'popup-5', 'poweroff');
532EOD;
533                        $cmd->Ejecutar();
534                        $cmd->texto = "DROP EVENT IF EXISTS e_timeout_$clntid;";
535                        $cmd->Ejecutar();
536                        $cmd->texto = "COMMIT;";
537                        $cmd->Ejecutar();
538                        // Send a poweroff command to client's OGAgent.
539                        $ogagent[$clntip]['url'] = "https://$clntip:8000/opengnsys/poweroff";
540                        $ogagent[$clntip]['header'] = Array("Authorization: ".$agentkey);
541                        if ($app->settings['debug'])
542                                writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent poweroff, url=".$ogagent[$clntip]['url'].".");
543                        $result = multiRequest($ogagent);
544                        // ... (check response)
545                        //if ($result[$clntip]['code'] != 200) {
546                        // ...
547                        // Confirm operation.
548                        $response = "";
549                        jsonResponse(200, $response);
550                } else {
551                        // Error message.
552                        $response["message"] = "Client is not reserved";
553                        jsonResponse(400, $response);
554                }
555        } else {
556                // Error message.
557                $response["message"] = "Client does not exist";
558                jsonResponse(404, $response);
559        }
560        $rs->Cerrar();
561    }
562);
563
Note: See TracBrowser for help on using the repository browser.