source: admin/WebConsole/rest/remotepc.php @ 363defe

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

#991: Computers in maintenance mode will not be chosen for remote access.

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