]> jfr.im git - irc/unrealircd/unrealircd-webpanel.git/blob - api/common_api.php
Probably good idea not to hammer older UnrealIRCd's (adds a usleep..)
[irc/unrealircd/unrealircd-webpanel.git] / api / common_api.php
1 <?php
2 include "../common.php";
3
4 if(session_status() !== PHP_SESSION_ACTIVE) session_start();
5
6 if (!isset($_SESSION['id']))
7 die("Access denied");
8
9 // Close the session now, otherwise other pages block
10 session_write_close();
11
12 // Only now make the connection (this can take a short while)
13 include "../connection.php";
14
15 // Server Side Events
16 header('Content-Type: text/event-stream');
17
18 // Explicitly disable caching so Varnish and other upstreams won't cache.
19 header("Cache-Control: no-cache, must-revalidate");
20
21 // Setting this header instructs Nginx to disable fastcgi_buffering and disable
22 // gzip for this request.
23 header('X-Accel-Buffering: no');
24
25 // No time limit
26 set_time_limit(0);
27
28 // Send content immediately
29 ob_implicit_flush(1);
30
31 // Eh.. yeah...
32 ob_end_flush();
33
34 // If we use fastcgi, then finish the request now (UNTESTED)
35 if (function_exists('fastcgi_finish_request'))
36 fastcgi_finish_request();
37
38 /* Send server-sent events (SSE) message */
39 function send_sse($json)
40 {
41 echo "data: ".json_encode($json)."\n\n";
42 }
43
44 function api_log_loop($sources)
45 {
46 GLOBAL $rpc;
47
48 $rpc->log()->subscribe($sources);
49 if ($rpc->error)
50 {
51 echo $rpc->error;
52 die;
53 }
54
55 for(;;)
56 {
57 $res = $rpc->eventloop();
58 if (!$res)
59 {
60 /* Output at least something every timeout (10) seconds,
61 * otherwise PHP may not
62 * notice when the webclient is gone.
63 */
64 echo "\n";
65 continue;
66 }
67 send_sse($res);
68 }
69 }
70
71 function api_timer_loop(int $every_msec, string $method, array|null $params = null)
72 {
73 GLOBAL $rpc;
74
75 $rpc->rpc()->add_timer("timer", $every_msec, $method, $params);
76 if ($rpc->error)
77 {
78 /* Have to resort to old style: client-side timer */
79 while(1)
80 {
81 $res = $rpc->query($method, $params);
82 if (!$res)
83 die;
84 send_sse($res);
85 usleep($every_msec * 1000);
86 }
87 }
88
89 /* New style: use server-side timers */
90 for(;;)
91 {
92 $res = $rpc->eventloop();
93 if (!$res)
94 {
95 /* Output at least something every timeout (10) seconds,
96 * otherwise PHP may not
97 * notice when the webclient is gone.
98 */
99 echo "\n";
100 continue;
101 }
102 send_sse($res);
103 }
104 }