]> jfr.im git - irc/unrealircd/unrealircd-rpc-php.git/blob - lib/Connection.php
1b8b01b9bb29a1e3a6f17d0be8892d5d191763f0
[irc/unrealircd/unrealircd-rpc-php.git] / lib / Connection.php
1 <?php
2
3 namespace UnrealIRCd;
4
5 use Exception;
6 use WebSocket;
7
8 class Connection
9 {
10 protected WebSocket\Client $connection;
11
12 public $errno = 0;
13 public $error = NULL;
14
15 public function __construct(string $uri, string $api_login, array $options = null)
16 {
17 $context = $options["context"] ?? stream_context_create();
18
19 if (isset($options["tls_verify"]) && !$options["tls_verify"]) {
20 stream_context_set_option($context, 'ssl', 'verify_peer', false);
21 stream_context_set_option($context, 'ssl', 'verify_peer_name', false);
22 }
23
24 $this->connection = new WebSocket\Client($uri, [
25 'context' => $context,
26 'headers' => [
27 'Authorization' => sprintf('Basic %s', base64_encode($api_login)),
28 ],
29 'timeout' => 10,
30 ]);
31
32 }
33
34 /**
35 * Encode and send a query to the RPC server.
36 *
37 * @note I'm not sure on the response type except that it may be either an object or array.
38 *
39 * @param string $method
40 * @param array|null $params
41 *
42 * @return object|array|bool
43 * @throws Exception
44 */
45 public function query(string $method, array|null $params = null): object|array|bool
46 {
47 $id = random_int(1, 99999);
48
49 $rpc = [
50 "jsonrpc" => "2.0",
51 "method" => $method,
52 "params" => $params,
53 "id" => $id
54 ];
55
56 $json_rpc = json_encode($rpc);
57
58 $this->connection->text($json_rpc);
59 $reply = $this->connection->receive();
60
61 $reply = json_decode($reply);
62
63 if (property_exists($reply, 'result')) {
64 if($id !== $reply->id) {
65 throw new Exception('Invalid ID. This is not the expected reply.');
66 }
67 $this->errno = 0;
68 $this->error = NULL;
69 return $reply->result;
70 }
71
72 if (property_exists($reply, 'error')) {
73 $this->errno = $reply->error->code;
74 $this->error = $reply->error->message;
75 return false;
76 }
77
78 /* This should never happen */
79 throw new Exception('Invalid JSON-RPC response from UnrealIRCd: not an error and not a result.');
80 }
81
82 public function user(): User
83 {
84 return new User($this);
85 }
86
87 public function channel(): Channel
88 {
89 return new Channel($this);
90 }
91
92 public function serverban(): ServerBan
93 {
94 return new ServerBan($this);
95 }
96
97 public function spamfilter(): Spamfilter
98 {
99 return new Spamfilter($this);
100 }
101 public function nameban(): NameBan
102 {
103 return new NameBan($this);
104 }
105 public function server(): Server
106 {
107 return new Server($this);
108 }
109 public function serverbanexception(): BanException
110 {
111 return new ServerBanException($this);
112 }
113 }