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

Last change on this file since b1ef135 was fe3a254, checked in by OpenGnSys Support Team <soporte-og@…>, 5 years ago

#990 Fix WOL call for RemotePC

This patch fixes the call to the WOL rest function by adapting it to the
new API.

  • Property mode set to 100644
File size: 20.8 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.mascara, 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                $clntnetmask = $rs->campos["mascara"];
115                $agentkey = $rs->campos["agentkey"];
116                $disk = $rs->campos["numdisk"];
117                $part = $rs->campos["numpar"];
118                $labid = $rs->campos["idaula"];
119                $ouid = $rs->campos["idcentro"];
120                $repoip = $rs->campos["repoip"];
121                $repokey = $rs->campos["repokey"];
122                // Check client's status.
123                $ogagent[$clntip]['url'] = "https://$clntip:8000/opengnsys/status";
124                if ($app->settings['debug'])
125                        writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent status, url=".$ogagent[$clntip]['url'].".");
126                $result = multiRequest($ogagent);
127                if (empty($result[$clntip]['data'])) {
128                        // Client is off, send WOL command to ogAdmServer.
129                        // TODO: if client is busy?????
130                        if ($app->settings['debug'])
131                                writeRemotepcLog($app->request()->getResourceUri(). ": Send boot command through ogAdmServer: iph=$clntip,mac=$clntmac.");
132                        wol(1, [$clntmac], [$clntip], [$clntnetmask]);
133                        // Send WOL command to client repository.
134                        $repo[$repoip]['url'] = "https://$repoip/opengnsys/rest/repository/poweron";
135                        $repo[$repoip]['header'] = Array("Authorization: ".$repokey);
136                        $repo[$repoip]['post'] = '{"macs": ["'.$clntmac.'"], "ips": ["'.$clntip.'"]}';
137                        if ($app->settings['debug'])
138                                writeRemotepcLog($app->request()->getResourceUri(). ": Send Boot command through repo: repo=$repoip, ip=$clntip,mac=$clntmac.");
139                        $result = multiRequest($repo);
140                        // ... (check response)
141                        //if ($result[$repoip]['code'] != 200) {
142                        // ...
143                } else {
144                        // Client is on, send a rieboot command to its OGAgent.
145                        $ogagent[$clntip]['url'] = "https://$clntip:8000/opengnsys/reboot";
146                        $ogagent[$clntip]['header'] = Array("Authorization: ".$agentkey);
147                        if ($app->settings['debug'])
148                                writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent reboot, url=".$ogagent[$clntip]['url'].".");
149                        $result = multiRequest($ogagent);
150                        // ... (check response)
151                        //if ($result[$clntip]['code'] != 200) {
152                        // ...
153                }
154                // DB Transaction: mark choosed client as reserved and
155                // create an init session command into client's actions queue.
156                $cmd->texto = "START TRANSACTION;";
157                $cmd->Ejecutar();
158                $timestamp = time();
159                $cmd->texto = <<<EOD
160INSERT INTO remotepc
161   SET id = '$clntid', reserved = NOW() + INTERVAL $maxtime HOUR,
162       urllogin = NULL, urllogout = NULL, urlrelease = NULL
163    ON DUPLICATE KEY UPDATE
164       id = VALUES(id), reserved = VALUES(reserved),
165       urllogin = VALUES(urllogin), urllogout = VALUES(urllogout),
166       urlrelease = VALUES(urlrelease);
167EOD;
168                $t1 = $cmd->Ejecutar();
169                $cmd->texto = <<<EOD
170INSERT INTO acciones
171   SET tipoaccion=$EJECUCION_COMANDO,
172       idtipoaccion=9,
173       idcomando=9,
174       parametros='nfn=IniciarSesion\rdsk=$disk\rpar=$part',
175       descriaccion='RemotePC Session',
176       idordenador=$clntid,
177       ip='$clntip',
178       sesion=$timestamp,
179       fechahorareg=NOW(),
180       estado=$ACCION_INICIADA,
181       resultado=$ACCION_SINRESULTADO,
182       ambito=$AMBITO_ORDENADORES,
183       idambito=$clntid,
184       restrambito='$clntip',
185       idcentro=$ouid;
186EOD;
187                $t2 = $cmd->Ejecutar();
188                // Create event to remove reservation on timeout (15 min.).
189                $timeout = "15 MINUTE";
190                $cmd->texto = <<<EOD
191CREATE EVENT e_timeout_$clntid
192       ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL $timeout DO
193       BEGIN
194            SET @action_id = NULL;
195            UPDATE acciones
196               SET estado = $ACCION_FINALIZADA, resultado = $ACCION_FALLIDA,
197                   descrinotificacion = 'Timeout'
198             WHERE descriaccion = 'RemotePC Session' AND estado = $ACCION_INICIADA
199               AND idordenador = '$clntid'
200               AND (SELECT @action_id := idaccion);
201            IF @action_id IS NOT NULL THEN
202               UPDATE remotepc
203                  SET reserved = NOW() - INTERVAL 1 SECOND,
204                      urllogin = NULL, urllogout = NULL, urlrelease = NULL
205                WHERE id = '$clntid';
206               DELETE FROM acciones
207                WHERE idaccion = @action_id;
208            END IF;
209       END
210EOD;
211                $t3 = $cmd->Ejecutar();
212                if ($t1 and $t2 and $t3) {
213                        // Commit transaction on success.
214                        $cmd->texto = "COMMIT;";
215                        $cmd->Ejecutar();
216                        if ($app->settings['debug'])
217                                writeRemotepcLog($app->request()->getResourceUri(). ": DB tables and events updated, clntid=$clntid.");
218                        // Send init session command if client is booted on ogLive.
219                        if ($app->settings['debug'])
220                                writeRemotepcLog($app->request()->getResourceUri(). ": Send Init Session command to ogAdmClient, ido=$clntid,iph=$clntip,dsk=$disk,par=$part.");
221                        session($clntip, "$disk\r$part");
222                        // Compose JSON response.
223                        $response['id'] = (int)$clntid;
224                        $response['name'] = $clntname;
225                        $response['ip'] = $clntip;
226                        $response['mac'] = $clntmac;
227                        $response['lab']['id'] = $labid;
228                        $response['ou']['id'] = (int)$ouid;
229                        if ($app->settings['debug'])
230                                writeRemotepcLog($app->request()->getResourceUri(). ": Response, ".var_export($response,true).".");
231                        jsonResponse(200, $response);
232                } else {
233                        // Roll-back transaction on DB error.
234                        $cmd->texto = "ROLLBACK;";
235                        $cmd->Ejecutar();
236                        // Error message.
237                        $response["message"] = "Database error: $t1, $t2, $t3";
238                        if ($app->settings['debug'])
239                                writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
240                        jsonResponse(400, $response);
241                }
242        } else {
243                if ($app->settings['debug'])
244                        writeRemotepcLog($app->request()->getResourceUri(). ": UNASSIGNED");
245        }
246        $rs->Cerrar();
247        $app->stop();
248    }
249);
250
251
252/**
253 * @brief    Store UDS server URLs to resend some events recieved from OGAgent.
254 * @note     Route: /ous/:ouid/labs/:labid/clients/:clntid/events, Method: POST
255 * @param    string urlLogin   URL to redirect login notification.
256 * @param    string urlLogout  URL to redirect logout notification.
257 * @param    string urlRelease URL to release a session
258 * @warning  Events parameters will be stored in a new "remotepc" table.
259 */
260$app->post('/ous/:ouid/labs/:labid/clients/:clntid/events', 'validateApiKey',
261    function($ouid, $labid, $clntid) use ($app) {
262        global $cmd;
263        global $userid;
264        $response = Array();
265
266        if ($app->settings['debug'])
267                writeRemotepcLog($app->request()->getResourceUri(). ": Init.");
268        // Checking parameters.
269        try {
270                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
271                        throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
272                }
273                if (!checkIds($ouid, $labid, $clntid)) {
274                        throw new Exception("Ids. must be positive integers");
275                }
276                // Reading JSON parameters.
277                $input = json_decode($app->request()->getBody());
278                $urlLogin = htmlspecialchars($input->urlLogin);
279                $urlLogout = htmlspecialchars($input->urlLogout);
280                $urlRelease = htmlspecialchars($input->urlRelease ?? "");
281                if (filter_var($urlLogin, FILTER_VALIDATE_URL) === false) {
282                        throw new Exception("Must be a valid URL for login notification");
283                }
284                if (filter_var($urlLogout, FILTER_VALIDATE_URL) === false) {
285                        throw new Exception("Must be a valid URL for logout notification");
286                }
287        } catch (Exception $e) {
288                // Error message.
289                $response["message"] = $e->getMessage();
290                if ($app->settings['debug'])
291                        writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
292                jsonResponse(400, $response);
293                $app->stop();
294        }
295
296        if ($app->settings['debug'])
297                writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: urlLogin=$urlLogin, urlLogout=$urlLogout");
298        // Select client data for UDS compatibility.
299        $cmd->texto = <<<EOD
300SELECT adm.idusuario, ordenadores.idordenador, remotepc.*
301  FROM remotepc
302 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
303  JOIN aulas USING(idaula)
304 RIGHT JOIN administradores_centros AS adm USING(idcentro)
305 RIGHT JOIN usuarios USING(idusuario)
306 WHERE adm.idusuario = '$userid'
307   AND idcentro = '$ouid' AND aulas.idaula ='$labid'
308   AND ordenadores.idordenador = '$clntid';
309EOD;
310        $rs=new Recordset;
311        $rs->Comando=&$cmd;
312        if (!$rs->Abrir()) return(false);       // Error opening recordset.
313        // Check if user is admin and client exists.
314        $rs->Primero();
315        if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
316                // Check if client is reserved.
317                if (! is_null($rs->campos["reserved"])) {
318                        // Updating DB if client is reserved.
319                        $cmd->CreaParametro("@urllogin", $urlLogin, 0);
320                        $cmd->CreaParametro("@urllogout", $urlLogout, 0);
321                        $cmd->CreaParametro("@urlrelease", $urlRelease, 0);
322                        $cmd->texto = <<<EOD
323UPDATE remotepc
324   SET urllogin = @urllogin, urllogout = @urllogout, urlrelease = NULLIF(@urlrelease, '')
325 WHERE id='$clntid';
326EOD;
327                        if ($cmd->Ejecutar()) {
328                                // Confirm operation.
329                                $response = "";
330                                jsonResponse(200, $response);
331                        } else {
332                                // Error message.
333                                $response["message"] = "Database error";
334                                jsonResponse(400, $response);
335                        }
336                } else {
337                        // Error message.
338                        $response["message"] = "Client is not reserved";
339                        jsonResponse(400, $response);
340                }
341        }
342        $rs->Cerrar();
343        $app->stop();
344    }
345);
346
347
348/*
349 * @brief    Store session time (in sec).
350 * @note     Route: /ous/:ouid/labs/:labid/clients/:clntid/session, Method: POST
351 * @param    int    deadLine   maximum session time, in seconds (0 for unlimited)
352 * @warning  Parameters will be stored in a new "remotepc" table.
353 */
354$app->post('/ous/:ouid/labs/:labid/clients/:clntid/session', 'validateApiKey',
355    function($ouid, $labid, $clntid) use ($app) {
356        global $cmd;
357        global $userid;
358        $response = Array();
359
360        if ($app->settings['debug'])
361                writeRemotepcLog($app->request()->getResourceUri(). ": Init.");
362        // Checking parameters.
363        try {
364                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
365                        throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
366                }
367                if (!checkIds($ouid, $labid, $clntid)) {
368                        throw new Exception("Ids. must be positive integers");
369                }
370                // Reading JSON parameters.
371                $input = json_decode($app->request()->getBody());
372                $deadLine = $input->deadLine;
373                if (filter_var($deadLine, FILTER_VALIDATE_INT) === false) {
374                        throw new Exception("Deadline must be integer");
375                }
376                if ($deadLine < 0) {
377                        throw new Exception("Resource unavailable");
378                }
379        } catch (Exception $e) {
380                // Error message.
381                $response["message"] = $e->getMessage();
382                if ($app->settings['debug'])
383                        writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
384                jsonResponse(400, $response);
385                $app->stop();
386        }
387
388        if ($app->settings['debug'])
389                writeRemotepcLog($app->request()->getResourceUri(). ": Parameters: deadLine=$deadLine");
390        // Get client's data.
391        $cmd->texto = <<<EOD
392SELECT adm.idusuario, ordenadores.idordenador, remotepc.*
393  FROM remotepc
394 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
395  JOIN aulas USING(idaula)
396 RIGHT JOIN administradores_centros AS adm USING(idcentro)
397 WHERE adm.idusuario = '$userid'
398   AND aulas.idcentro = '$ouid' AND aulas.idaula = '$labid'
399   AND ordenadores.idordenador = '$clntid';
400EOD;
401        $rs=new Recordset;
402        $rs->Comando=&$cmd;
403        if (!$rs->Abrir()) return(false);       // Error opening recordset.
404        // Check if user is admin and client exists.
405        $rs->Primero();
406        if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
407                // Check if client is reserved.
408                if (! is_null($rs->campos["urllogin"])) {
409                        // Read query data.
410                        $clntid = $rs->campos["idordenador"];
411                        # Removing previous commands from OGAgent operations queue.
412                        if ($app->settings['debug'])
413                                writeRemotepcLog($app->request()->getResourceUri(). ": Updating database.");
414                        $cmd->texto = <<<EOD
415DELETE FROM ogagent_queue
416 WHERE clientid = '$clntid' AND operation IN ('popup-10', 'popup-5', 'poweroff');
417EOD;
418                        $cmd->Ejecutar();
419                        # Add new commands to OGAgent operations queue.
420                        $cmd->texto = "INSERT INTO ogagent_queue (clientid, exectime, operation) VALUES";
421                        if ($deadLine > 600) {
422                                # Add reminder 10 min. before deadline.
423                                $cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND - INTERVAL 10 MINUTE, 'popup-10'),";
424                        }
425                        if ($deadLine > 300) {
426                                # Add reminder 5 min. before deadline.
427                                $cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND - INTERVAL 5 MINUTE, 'popup-5'),";
428                        }
429                        # Add power off command at deadline time.
430                        $cmd->texto .= " ($clntid, NOW() + INTERVAL $deadLine SECOND, 'poweroff');";
431                        if ($deadLine == 0 or $cmd->Ejecutar()) {
432                                // Confirm operation.
433                                $cmd->texto = "";
434                                $response = "";
435                                jsonResponse(200, $response);
436                        } else {
437                                // Error message.
438                                $response["message"] = "Database error";
439                                jsonResponse(400, $response);
440                        }
441                } else {
442                        // Error message.
443                        $response["message"] = "Client is not reserved";
444                        jsonResponse(400, $response);
445                }
446        } else {
447                // Error message.
448                $response["message"] = "Client does not exist";
449                jsonResponse(404, $response);
450        }
451        $rs->Cerrar();
452    }
453);
454
455
456/**
457 * @brief    Store UDS server URLs to resend some events recieved from OGAgent.
458 * @brief    Unreserve a client and send a poweroff operation.
459 * @note     Route: /ous/:ouid/labs/:labid/clients/:clntid/unreserve, Method: DELETE
460 */
461$app->delete('/ous/:ouid/labs/:labid/clients/:clntid/unreserve', 'validateApiKey',
462    function($ouid, $labid, $clntid) use ($app) {
463        global $cmd;
464        global $userid;
465        global $ACCION_INICIADA;
466        $response = Array();
467        $ogagent = Array();
468
469        if ($app->settings['debug'])
470                writeRemotepcLog($app->request()->getResourceUri(). ": Init.");
471        // Checking parameters.
472        try {
473                if (empty(preg_match('/^python-requests\//', $_SERVER['HTTP_USER_AGENT']))) {
474                        throw new Exception("Bad agent: sender=".$_SERVER['REMOTE_ADDR'].", agent=".$_SERVER['HTTP_USER_AGENT']);
475                }
476                if (!checkIds($ouid, $labid, $clntid)) {
477                        throw new Exception("Ids. must be positive integers");
478                }
479        } catch (Exception $e) {
480                // Error message.
481                $response["message"] = $e->getMessage();
482                if ($app->settings['debug'])
483                        writeRemotepcLog($app->request()->getResourceUri(). ": ERROR: ".$response["message"].".");
484                jsonResponse(400, $response);
485                $app->stop();
486        }
487
488        // Select client data for UDS compatibility.
489        $cmd->texto = <<<EOD
490SELECT adm.idusuario, ordenadores.idordenador, ordenadores.ip, ordenadores.agentkey, remotepc.reserved
491  FROM remotepc
492 RIGHT JOIN ordenadores ON remotepc.id=ordenadores.idordenador
493  JOIN aulas USING(idaula)
494 RIGHT JOIN administradores_centros AS adm USING(idcentro)
495 RIGHT JOIN usuarios USING(idusuario)
496 WHERE adm.idusuario = '$userid'
497   AND idcentro = '$ouid' AND aulas.idaula ='$labid'
498   AND ordenadores.idordenador = '$clntid';
499EOD;
500        $rs=new Recordset;
501        $rs->Comando=&$cmd;
502        if (!$rs->Abrir()) return(false);       // Error opening recordset.
503        // Check if user is admin and client exists.
504        $rs->Primero();
505        if (checkAdmin($rs->campos["idusuario"]) and checkParameter($rs->campos["idordenador"])) {
506                // Check if client is reserved.
507                if (! is_null($rs->campos["reserved"])) {
508                        // Read query data.
509                        $clntip = $rs->campos["ip"];
510                        $agentkey = $rs->campos["agentkey"];
511                        // DB Transaction: set reservation time to the past, remove pending
512                        // boot commands from client's and agent's queues, and drop its event.
513                        if ($app->settings['debug'])
514                                writeRemotepcLog($app->request()->getResourceUri(). ": Updating database.");
515                        $cmd->texto = "START TRANSACTION;";
516                        $cmd->Ejecutar();
517                        $cmd->texto = <<<EOD
518UPDATE remotepc
519   SET reserved = NOW() - INTERVAL 1 SECOND,
520       urllogin = NULL, urllogout = NULL, urlrelease = NULL
521 WHERE id = '$clntid';
522EOD;
523                        $cmd->Ejecutar();
524                        $cmd->texto = <<<EOD
525DELETE FROM acciones
526 WHERE idordenador = '$clntid'
527   AND descriaccion = 'RemotePC Session';
528EOD;
529                        $cmd->Ejecutar();
530                        $cmd->texto = <<<EOD
531DELETE FROM ogagent_queue
532 WHERE clientid = '$clntid' AND command IN ('popup-10', 'popup-5', 'poweroff');
533EOD;
534                        $cmd->Ejecutar();
535                        $cmd->texto = "DROP EVENT IF EXISTS e_timeout_$clntid;";
536                        $cmd->Ejecutar();
537                        $cmd->texto = "COMMIT;";
538                        $cmd->Ejecutar();
539                        // Send a poweroff command to client's OGAgent.
540                        $ogagent[$clntip]['url'] = "https://$clntip:8000/opengnsys/poweroff";
541                        $ogagent[$clntip]['header'] = Array("Authorization: ".$agentkey);
542                        if ($app->settings['debug'])
543                                writeRemotepcLog($app->request()->getResourceUri(). ": OGAgent poweroff, url=".$ogagent[$clntip]['url'].".");
544                        $result = multiRequest($ogagent);
545                        // ... (check response)
546                        //if ($result[$clntip]['code'] != 200) {
547                        // ...
548                        // Confirm operation.
549                        $response = "";
550                        jsonResponse(200, $response);
551                } else {
552                        // Error message.
553                        $response["message"] = "Client is not reserved";
554                        jsonResponse(400, $response);
555                }
556        } else {
557                // Error message.
558                $response["message"] = "Client does not exist";
559                jsonResponse(404, $response);
560        }
561        $rs->Cerrar();
562    }
563);
564
Note: See TracBrowser for help on using the repository browser.