8af22098e1e5d6f878b89b3fc129590410fb9842
[m6w6/btr] / lib / btr / irc.php
1 <?php
2
3 function fatal() {
4 if (func_num_args()) {
5 $args = func_get_args();
6 } elseif (($error = error_get_last())) {
7 $args = ["%s", $error["message"]];
8 }
9
10 if (!empty($args)) {
11 if (count($args) === 1 && is_numeric($args[0])) {
12 array_unshift($args, "Got signal %d");
13 }
14 trigger_error(call_user_func_array("sprintf", $args), E_USER_ERROR);
15 }
16
17 exit;
18 }
19
20 function mkfifo($path) {
21 if (!isfifo($path, $stat)) {
22 $stat and unlink($path);
23 if (!posix_mkfifo($path, 0660)) {
24 return false;
25 }
26 }
27 return fopen($path, "r+");
28 }
29
30 function isfifo($path, &$stat = null) {
31 return ($stat = @stat($path)) && ($stat["mode"] & POSIX_S_IFIFO);
32 }
33
34 class Client
35 {
36 protected $session;
37 protected $channel;
38 protected $keyword;
39 protected $joined;
40 protected $queue = array();
41
42 function __construct($url, callable $onJoin) {
43 if (!$url = parse_url($url)) {
44 fatal("could not parse url: '%s'", $url);
45 }
46
47 $this->session = $session = new irc\client\Session(
48 $url["user"],
49 $url["user"],
50 $url["user"]
51 );
52
53 @list($this->channel, $this->keyword) =
54 explode(" ", $url["fragment"]);
55
56 $session->onConnect = $session->onPart = function($origin, array $args) {
57 $this->joined = false;
58 $this->session->doJoin("#".$this->channel, $this->keyword);
59 };
60 $session->onJoin = function($origin, array $args) use ($onJoin) {
61 $this->joined = true;
62 $onJoin($this, $origin, $args);
63 };
64 $session->doConnect(false, $url["host"], @$url["port"]?:6667, @$url["pass"]);
65 }
66
67 function send($message = null) {
68 if (isset($message)) {
69 $this->queue[] = $message;
70 }
71
72 if ($this->joined) {
73 while ($this->queue) {
74 $this->session->doMsg("#".$this->channel, array_shift($this->queue));
75 }
76 }
77 }
78
79 function getSession() {
80 return $this->session;
81 }
82 }
83
84 if (!extension_loaded("ircclient")) {
85 fatal("ext/ircclient not loaded");
86 }
87
88 # vim: noet