]> jfr.im git - irc/unrealircd/unrealircd-rpc-php.git/blob - lib/Connection.php
User: add optional $object_detail_level argument to getAll() and get().
[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 /* Start the connection now */
33 $this->connection->ping();
34 }
35
36 /**
37 * Encode and send a query to the RPC server.
38 *
39 * @note I'm not sure on the response type except that it may be either an object or array.
40 *
41 * @param string $method
42 * @param array|null $params
43 *
44 * @return object|array|bool
45 * @throws Exception
46 */
47 public function query(string $method, array|null $params = null): object|array|bool
48 {
49 $id = random_int(1, 99999);
50
51 $rpc = [
52 "jsonrpc" => "2.0",
53 "method" => $method,
54 "params" => $params,
55 "id" => $id
56 ];
57
58 $json_rpc = json_encode($rpc);
59
60 $this->connection->text($json_rpc);
61 $reply = $this->connection->receive();
62
63 $reply = json_decode($reply);
64
65 if (property_exists($reply, 'result')) {
66 if($id !== $reply->id) {
67 throw new Exception('Invalid ID. This is not the expected reply.');
68 }
69 $this->errno = 0;
70 $this->error = NULL;
71 return $reply->result;
72 }
73
74 if (property_exists($reply, 'error')) {
75 $this->errno = $reply->error->code;
76 $this->error = $reply->error->message;
77 return false;
78 }
79
80 /* This should never happen */
81 throw new Exception('Invalid JSON-RPC response from UnrealIRCd: not an error and not a result.');
82 }
83
84 public function user(): User
85 {
86 return new User($this);
87 }
88
89 public function channel(): Channel
90 {
91 return new Channel($this);
92 }
93
94 public function serverban(): ServerBan
95 {
96 return new ServerBan($this);
97 }
98
99 public function spamfilter(): Spamfilter
100 {
101 return new Spamfilter($this);
102 }
103 public function nameban(): NameBan
104 {
105 return new NameBan($this);
106 }
107 public function server(): Server
108 {
109 return new Server($this);
110 }
111 public function serverbanexception(): ServerBanException
112 {
113 return new ServerBanException($this);
114 }
115 }