]> jfr.im git - irc/unrealircd/unrealircd-webpanel.git/blob - inc/connection.php
Make API pages return empty data / die when server is not available.
[irc/unrealircd/unrealircd-webpanel.git] / inc / connection.php
1 <?php
2
3 if (!defined('UPATH'))
4 die("Access denied");
5
6 function connect_to_ircd()
7 {
8 GLOBAL $rpc;
9 GLOBAL $config;
10
11 $is_api_page = str_contains($_SERVER['SCRIPT_FILENAME'], "/api/") ? true : false;
12
13 $rpc = null; /* Initialize, mostly for API page failures */
14
15 $server = get_active_rpc_server();
16 if (!$server)
17 {
18 if ($is_api_page)
19 return;
20 Message::Fail("No RPC server configured. Go to Settings - RPC Servers.");
21 die;
22 }
23 $host = $config["unrealircd"][$server]["host"];
24 $port = $config["unrealircd"][$server]["port"];
25 $rpc_user = $config["unrealircd"][$server]["rpc_user"];
26 $rpc_password = $config["unrealircd"][$server]["rpc_password"];
27 if (str_starts_with($rpc_password, "secret:"))
28 $rpc_password = secret_decrypt($rpc_password);
29 $tls_verify = $config["unrealircd"][$server]["tls_verify_cert"];
30
31 if (!$host || !$port || !$rpc_user)
32 {
33 if ($is_api_page)
34 return;
35 die("RPC Server is missing credentials");
36 }
37
38 if ($rpc_password === null)
39 {
40 if ($is_api_page)
41 return;
42 Message::Fail("Your RPC password in the DB was encrypted with a different key than config/config.php contains.<br>\n".
43 "Either restore your previous config/config.php or start with a fresh database.<br>\n");
44 die;
45 }
46
47 /* Connect now */
48 try {
49 $rpc = new UnrealIRCd\Connection
50 (
51 "wss://$host:$port",
52 "$rpc_user:$rpc_password",
53 ["tls_verify" => $tls_verify]
54 );
55 }
56 catch (Exception $e)
57 {
58 if ($is_api_page)
59 return;
60 Message::Fail("Unable to connect to UnrealIRCd: ".$e->getMessage() . "<br>".
61 "Verify that the connection details from Settings - RPC Servers match the ones in UnrealIRCd ".
62 "and that UnrealIRCd is up and running");
63 throw $e;
64 }
65
66 $user = unreal_get_current_user();
67 if ($user)
68 {
69 /* Set issuer for all the RPC commands */
70 $rpc->rpc()->set_issuer($user->username);
71 }
72 }
73
74 connect_to_ircd();