-
Notifications
You must be signed in to change notification settings - Fork 1
/
IRC.php
947 lines (834 loc) · 32 KB
/
IRC.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
<?php
/********************************************
** An IRC connecion for Tin Irc Node **
** (c) 202x ian & ksynet.fr **
** [email protected] **
*********************************************/
/**********
** V1.2c **
***********/
namespace bot;
require_once 'Bot.php';
require_once 'functions.php';
require_once 'partyline.php';
const END="\r\n";
const chanPattern="(?P<chan>(#|&)[a-zA-Z0-9\-\+_\.]+)";
class IRC {
private string $shortname;
/* Server */
private string $hostname;
private int $port;
private bool $ssl;
private $socket; /* resource ... */
private string|null $password;
private string $defaultChan="";
private string $quitMsg=\bot\quitMsg;
/* User used for this connection */
private string $nickname, $username, $realname, $userpass;
private bool $hasNickSuffix=false;
private string $nickSuffixSep="|";
private string $nickServ="NickServ";
private string $userMode="+iB";
private bool $runningCmd=false;
/* CHANS */
private array $channels;
public array $channelsUsers;
/* Debug */
private bool $DEBUG = true;
/* Handlers & event */
private array $events = array ();
/* capabilities IRCv3*/
private array $caps = array();
/* For control connexion */
private int $userPort;
private int $maxUsers = 5;
private $usersListeningSocket = NULL; /* resource ... */
private array $usersConnected = array();
private int $userTokenCounter = 0;
private bool $mustStop = false;
public bool $connected = false;
private int $MAX_RECONNECT = 5;
private int $reconnections = 0;
private array $performs = array();
/* Linked Chans */
public array $linkedChannels;
private \bot\Bot|NULL $owner; /* In case the connection is owned by a bot -- see RunBot.sh for sample */
private $ownersNicks = array(); /* used by \bot\restrictedLink */
protected array $eventHandlers = array(
'userslist' => array(),
'nickslist' => array(),
'join' => array(),
'ejoin' => array(),
'part' => array(),
'quit' => array(),
'kick' => array(),
'ban' => array(),
'unban' => array(),
'server_unban'=> array(),
'voice' => array(),
'devoice' => array(),
'nick' => array(),
'nick2' => array(),
'privmsg' => array(),
'notice' => array(),
'servmsg' => array(),
'other_servmsg' => array(),
'other_modes' => array()
);
public function __construct(string $hostname, string $port, bool $ssl = true, string $short = "", int $uport = 1807, string $password = NULL, $ownersNicks = "") {
/* ATTENTION : this password is the server's one, not the nick's one !! */
$this->hostname = $hostname;
$this->port = intval($port);
$this->ssl = $ssl;
$this->password = $password;
if ($ownersNicks != "") {
if (is_array($ownersNicks)) {
foreach ($ownersNicks as $n) {
$this->ownersNicks[]=strtolower($n);
}
$this->ownersNicks=$ownersNicks;
} else {
$this->ownersNicks=array(strtolower($ownersNicks));
}
}
$this->channels = array();
$this->channelsUsers = array();
if ($short=="") {
if (($i1=strpos($hostname,"."))!==false && ($i2=strrpos($hostname,"."))!=false && $i2!=$i) {
$this->shortname=substr($short,$i1,$i2-$i1);
} else {
$this->shortname=$hostname;
}
} else {
$this->shortname=$short;
}
$this->userPort=$uport;
$this->linkedChannels=array();
}
public function debug(string $entry, string $type = 'raw') {
if ($this->DEBUG && trim($entry)!="") {
$time=(new \DateTime())->format("[d-m-y_H:i:s]");
echo "(".$this->getShortName().") ".$time.' ['.$type.'] '.$entry.END;
}
}
public function setDebug(bool $value) {
$this->DEBUG=$value;
}
public function isCmdRunning():bool {
return $this->runningCmd;
}
public function setCmdRunning(bool $run) {
$this->runningCmd=$run;
}
public function setNickName(string $nick) {
$this->nickname=$nick;
}
public function getNickName():string {
return $this->nickname;
}
public function setNickSuffixSep(string $sep) {
$this->nickSuffixSep=$sep;
}
public function setHasNickSuffix(bool $hs=true) {
$this->hasNickSuffix=$hs;
}
public function setUserMode(string $mode_s) {
$this->userMode=$mode_s;
}
public function setOwner(\bot\Bot $owner) {
$this->owner=$owner;
}
public function getOwner():\bot\Bot {
return $this->owner;
}
public function getHostname():string {
return $this->hostname;
}
public function getShortname():string {
return $this->shortname;
}
public function isOwnerNick($nick):bool {
return in_array(strtolower($nick), $this->ownersNicks);
}
public function addOwnerNick(string $nick="") {
if ($nick != "" && !isOwnerNick($nick))
$this->ownersNicks[]=strtoLower($nick);
}
public function getChannels():array {
return $this->channels;
}
public function isConnected():bool {
return $this->connected;
}
public function getDefaultChan():string {
return $this->defaultChan;
}
public function addCapability(string $cap):void {
$cap=trim($cap);
if ($cap!="")
$this->caps[]=$cap;
}
public function addPerforms(...$performs):void {
$this->performs=array_merge($this-performs,$performs);
}
private function initEventsPatterns() {
$key='/:(?P<server>.+) 353 '.$this->nickname.' . '.chanPattern.' :(?P<list>.*)/';
$this->events['userslist']=$key;
/* Some servers do not send server name nor bot nick first ... */
$this->events['nickslist']='/353 . '.chanPattern.' :(?P<list>.+)/';
$this->events['join']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) JOIN :'.chanPattern.'/';
$this->events['ejoin']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) JOIN '.chanPattern.' (?P<extjoin>.*)/';
$this->events['part']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) PART '.chanPattern.'/';
$this->events['quit']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) QUIT :(?P<reason>.*)/';
$this->events['nick']='/:(?P<userHandler>.+) NICK :(?P<newnick>.+)/';
$this->events['privmsg']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) PRIVMSG (?P<to>[^ :]+) :(?P<msg>.+)/';
$this->events['notice']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) NOTICE (?P<to>[^ :]+) :(?P<msg>.+)/'; /* TODO does not yet handle channels notice */
$this->events['versionmsg']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) PRIVMSG (?P<to>[^ :]+) :\001VERSION(.*)\001/';
$this->events['versiononly']='/\001VERSION(.*)\001/';
$this->events['kick']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) KICK '.chanPattern.' (?P<to>[^ :]+) :(?P<msg>.+)/';
$this->events['ban']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) MODE '.chanPattern.' (?P<btype>\+([b]+)) (?P<to>.+)/';
$this->events['unban']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) MODE '.chanPattern.' (?P<btype>\-([b]+)) (?P<to>.+)/';
$this->events['server_unban']='/:(?P<nick>.+) MODE '.chanPattern.' (?P<btype>\-([b]+)) (?P<to>.+)/';
$this->events['voice']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) MODE '.chanPattern.' (?P<voice>\+([v]+)) (?P<to>.+)/';
$this->events['devoice']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) MODE '.chanPattern.' (?P<devoice>\-([v]+)) (?P<to>.+)/';
$this->events['action']='/\001ACTION (.*)\001/'; /* only used in links, see reformatLinkedMessage */
/* must be the last one !! */
$this->events['servmsg']='/:(?P<serv>[^ ]+) (?P<code>[0-9]+) (?P<to>[^ :]+) (?P<msg>.*)/'; /* message from server with RPL_CODE, must be added AFTER 'userslist' */
$this->events['other_servmsg']='/:(?P<serv>.+) (?P<name>[a-zA-Z]+) (?P<to>[^ ]+) (?P<cmd_rpl>[a-zA-Z]+) :(?P<msg>.*)/'; /* message from server with RPL_CODE, must be added AFTER 'userslist' */
$this->events['other_modes']='/:(?P<nick>.+)!(?P<name>.+)@(?P<host>.+) MODE '.chanPattern.' (?P<mode>([+|\-])([a-zA-Z]+)) (?P<user>.+)/';
}
public function setPattern(string $name, string $pattern):bool {
$name=trim($name);
$pattern=trim($attern);
if ($name=="" || $pattern=="") {
$this->debug("Name and pattern cannot be empty");
return false;
}
$this->events[$name]=$pattern;
return true;
}
public function getEventHandlers():array {
return $this->eventHandlers;
}
public function testPattern(string $name, string $msg):array|false {
$pattern=$this->events[$name]??"";
if ($pattern!="") {
$result=preg_match($pattern,$msg,$matches);
if ($result)
return $matches;
}
return false;
}
public function setIdentity(string $nickname, string $username, string $realname, string $pass = "", string $nickserv="NickServ") {
list($this->nickname, $this->username, $this->realname, $this->userpass, $this->nickServ) = array($nickname, $username, $realname, $pass, $nickserv);
/* Maintenant on peut initialiser les handlers, car une des clés est calculée */
$this->initEventsPatterns();
}
public function identify():bool {
$this->debug("**** Trying to identify ****","NOTICE");
if (!$this->connected) {
echo $this->shortname." is not connected".PHP_EOL;
return false;
}
$this->send("PRIVMSG ".$this->nickServ." identify ".$this->userpass);
$this->debug("Sent identify with ".$this->userpass,"NOTICE");
$this->identified=true;
return true;
}
/* Channel Users */
public function getChannelUsers(string $channel):array {
if (!isset($this->channelsUsers[$channel])) {
return array("The channel $channel does not exist...");
}
$users=$this->channelsUsers[$channel];
if ($users==NULL)
$users=array();
return $users;
}
/* JOIN channel{,channel} [key{,key}] */
public function join($channels,$keys=""):bool {
if (!$this->connected) {
echo $this->shortname." is not connected".PHP_EOL;
return false;
}
if (!is_array($channels)) { /* Simple format */
$channel=strtolower($channels);
if ($channel[0]!="#" && $channel[0]!="&") {
echo "** bad JOIN channel : $channels **".PHP_EOL;
\bot\partyline\sendReplyAll("** bad JOIN channel : $channels **",$this);
return false;
}
if (is_array($keys)) {
echo "** multiple keys for joining a single channel **".PHP_EOL;
\bot\partyline\sendReplyAll("** multiple keys for joining a single channel **",$this);
return false;
}
$cmd_line="JOIN $channel $keys";
$this->channelsUsers[$channel]=array();
$this->channels[]=$channel;
$this->send($cmd_line);
} else {
if (is_array($keys) && count($keys)>count($channels)) {
echo "** more keys than channels for JOIN **".PHP_EOL;
\bot\partyline\sendReplyAll("** more keys than channels for JOIN **",$this);
return false;
}
foreach ($channels as $chan) {
$chan=strtolower($chan);
$this->channelsUsers[$chan]=array();
$this->channels[]=$chan;
}
$channels=strtolower(implode(",",$channels));
if (is_array($keys)) {
$keys=implode(",",$keys);
}
$cmd_line="JOIN $channels $keys";
$this->send($cmd_line);
}
$this->channels=array_unique($this->channels);
return true;
}
/* PART channel{,channel} */
public function part(array $channels):bool {
if (!$this->connected) {
echo $this->shortname." is not connected".PHP_EOL;
return false;
}
$chans2del=array();
foreach ($channels as $chan) {
$chan=strtolower($chan);
if (array_search($chan,$this->channels)===false) {
echo "** not connected to $chan **".PHP_EOL;
\bot\partyline\sendReplyAll("** not connected to $chan **",$this);
} else {
$this->channelsUsers[$chan]=array();
$chans2del[]=$chan;
}
}
$channels_str=strtolower(implode(",",$channels));
$cmd_line="PART $channels_str";
$this->send($cmd_line);
$tmp=array_diff($this->channels,$chans2del);
sort($tmp); /* re-index chans */
$this->channels=$tmp;
\bot\partyline\sendReplyAll("** left $channels_str **",$this);
return true;
}
public function setDefaultChan(string $dchan) {
$this->defaultChan=strtolower($dchan);
$this->channels[]=$this->defaultChan;
$this->channels=array_unique($this->channels);
}
public function connect(string $defaultChan="", float $timeout = 5.0):bool {
if ($this->connected) {
echo $this->shortname." is already connected...".PHP_EOL;
return true;
}
if ($defaultChan!="")
$this->setDefaultChan($defaultChan);
/* Suppression de la vérification du certificat SSL (http://i.justrealized.com/2009/allowing-self-signed-certificates-for-pfsockopen-and-fsockopen/) */
if ($this->ssl) {
$context = stream_context_create();
stream_context_set_option($context, 'ssl', 'allow_self_signed', true);
stream_context_set_option($context, 'ssl', 'verify_peer', false);
/* Doesn't seem to work ... */
stream_context_set_option($context, 'ssl', 'local_cert', "./tin.pem");
stream_context_set_option($context, 'ssl', 'verify_peer_name', false);
$this->socket = stream_socket_client('ssl://'.$this->hostname.':'.$this->port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context);
} else {
$this->socket = fsockopen($this->hostname, $this->port, $errno, $errstr, $timeout);
}
if (!$this->socket) {
throw new \Exception('Impossible de se connecter à '.$this->hostname.':'.$this->port.' ("'.$errstr.'", code '.$errno.').');
}
/*... THEN continue to IRC */
stream_set_blocking($this->socket,false); /* non blocking */
/* PASS ? */
if ($this->password != NULL) {
$this->send('PASS '.$this->password);
/* TODO: exception */
}
/* NICK */
/* avoid suffix in nickname */
if ($this->hasNickSuffix && $this->nickSuffixSep!="") {
$indexSuffix=strpos($this->nickname,$this->nickSuffixSep);
if ($indexSuffix!==false) {
echo "*********************************".PHP_EOL;
$newNickname=substr($this->nickname,0,$indexSuffix);
echo "Change nickname from ".$this->nickname." to $newNickname".PHP_EOL;
echo "*********************************".PHP_EOL;
$this->setNickName($newNickname);
$this->initEventsPatterns();
}
}
$this->send('NICK :'. $this->nickname);
/* TODO: si nick déjà pris ... ??? */
/* USER */
$this->send('USER '. implode(' ', array($this->username, $this->defaultChan, '.', $this->realname)));
/* TODO: si erreur ?? */
/* Post-connection messages */
$flag=false;
while (!$flag) {
$content = $this->read();
foreach($content as $c) {
$this->debug($c);
/* PING */
if (preg_match('/^PING :(.+)$/', $c, $matches)) {
$this->send('PONG :'. $matches[1]);
$this->debug("*** ".$this->getShortname()." : PING PONG");
continue;
}
/* AUTOJOIN may have been sent while initializing */
if (($matches=$this->testPattern('join', $c))!==false) {
$channel=strtolower($matches['chan']);
$this->channelsUsers[$channel]=array();
$this->channels[]=$channel;
}
/* subsequently, a userslist may have been sent... */
if (($matches=$this->testPattern('userslist', $c))!==false || ($matches=$this->testPattern('nickslist', $c))!==false) {
\bot\events\userslist($matches,$this);
}
/* Connection closed */
if (preg_match('/^ERROR :Closing Link: ([^\ ]+) (.*)$/', $c, $matches)) {
echo "*** /!\\ ***".$this->getShortname()." Connexion closed, reason : ".$matches[2].PHP_EOL;
fclose($this->socket);
$this->connected=false;
return false;
}
/* MODE : tout est OK */
if (preg_match('/^:'.$this->nickname.' MODE/', $c)) {
echo $this->getShortname()." : Ready to listen".PHP_EOL;
$flag=true;
}
}
}
/* Capabilities */
foreach ($this->caps as $cap) {
$this->send("CAP REQ $cap");
$this->debug("Requesting CAP $cap");
}
/* Finally THE USERS SOCKET */
$this->setUsersListeningSocket();
/* set IRC Connected ! */
$this->connected=true;
/* Try to identify */
if ($this->userpass !== "") {
$this->identify();
}
/* MODES */
$this->send('MODE '.$this->nickname.' '.$this->userMode);
/* PERFORMS */
foreach ($this->performs as $p_line) {
$this->send($p_line);
}
return true;
}
/*******************************
** MAIN LOOP
*******************************/
public function listen(bool $loop=true):bool {
if (!$this->connected) {
echo $this->shortname." is not connected".PHP_EOL;
return false;
}
while (!$this->mustStop) { /* Partylines over telnet */
$this->acceptUser();
if ($this->hasUsers()) {
$read=$this->usersConnected;
$write=array();
$except=array();
$result=socket_select($read,$write,$except,0); /* non blocking, timeout = 0 */
} else {
$result=true;
}
if ($result===false) {
echo "*** ".socket_strerror((socket_last_error()))." ***".PHP_EOL;
} elseif ($this->hasUsers() && $result>0) {
foreach ($this->usersConnected as $token => $userSocket) {
$userInput=$this->readUser($token);
if (is_array($userInput) && count($userInput)>0) {
if (trim($userInput[0])!="") {
foreach ($userInput as $line) {
echo $this->shortname." : ".$line.PHP_EOL;
\bot\partyline\parseUserInput($token,$line,$this);
}
}
} else {
if ($userInput=="ERROR") {
echo "*** Read error : try to close the socket, and remove the user.".PHP_EOL;
}
socket_close($this->usersConnected[$token]);
unset($this->usersConnected[$token]);
}
}
}
$this->readIRC();
if (!$loop) break;
}
if ($loop || $this->mustStop) { /* Terminated */
$this->coreQuit();
$this->connected=false;
echo "*** ".$this->getShortname()." is now disconnected ***".PHP_EOL;
return false;
}
return true;
}
public function stop($quitMsg=\bot\quitMsg) {
if ($quitMsg=="") $quitMsg=$this->quitMsg;
$this->mustStop=true;
$this->quitMsg=$quitMsg;
}
private function coreQuit() {
$this->send("QUIT :".$this->quitMsg);
fclose($this->socket);
}
public function exit($quitMsg=\bot\quitMsg) { /* terminates all connections [/die] */
if ($this->owner != NULL) {
foreach ($this->owner->getConnections() as $other) {
$other->stop($quitMsg);
}
} else {
$this->stop($quitMsg);
}
}
public function hasUsers():bool {
return count($this->usersConnected)>0;
}
public function disconnectUser(int $token) {
socket_close($this->usersConnected[$token]);
unset($this->usersConnected[$token]);
}
public function disconnectUsers() {
foreach ($this->usersConnected as $token => $userSocket) {
socket_close($userSocket);
unset($this->usersConnected[$token]);
}
}
public function getUserSocket(int $token) {
$s=$this->usersConnected[$token]??null;
if (!$s) {
$this->debug("Token no more valid : $token","ERROR");
}
return $s;
}
public function getUsersSockets() {
return $this->usersConnected;
}
private function readIRC() {
$content = $this->read();
foreach($content as $c) {
/* PING */
if (preg_match('/^PING :(.+)$/', $c, $data)) {
$this->send('PONG :'. $data[1]);
$this->debug("*** ".$this->getShortname()." : PING PONG");
continue;
}
$this->debug($c);
/* Connection closed */ /* DEBUGTHIS ! */
if (preg_match('/^ERROR :Closing Link: ([^\ ]+) (.*)$/', $c, $matches)) {
echo "*** /!\\ ***".$this->getShortname()." Connexion closed, reason : ".$matches[2].PHP_EOL;
fclose($this->socket);
$this->connected=false;
$this->debug("*** Trying to reconnect... ***");
while (($this->reconnections++) < $this->MAX_RECONNECT && $this->connect()===false) {
$this->debug("*** reconnect, attempt ".$this->reconnections);
}
if (!$this->connected) {
$this->debug("Reconnection failed, ending up");
} else {
$this->reconnections=0;
}
break;
}
/* VERSION */
if (preg_match($this->events['versionmsg'],$c,$data)) {
if ($this->getOwner())
$version=$this->getOwner()->getVersionReply();
else
$version=\bot\version_reply;
$reply="NOTICE ".$data['nick']." :VERSION :".$version;
$this->send($reply);
continue;
}
/* CALL HANDLERS */
foreach($this->events as $event => $pattern) {
if (preg_match($pattern, $c, $data)) {
// $this->debug("matched ".$event,"DEBUG");
foreach($this->eventHandlers[$event] as $f) {
$f($data, $this);
}
continue 2;
}
}
}
}
/* Link to mirror a chan to another (to use with events) */
public function addLink(string $from, \bot\IRC $link, string $to) {
$from=strtolower($from);
if (!isset($this->linkedChannels[$from])) { /* create */
$this->linkedChannels[$from]=array();
}
$this->linkedChannels[$from][$link->getShortname()]=array("connection" => $link, "channel" => strtolower($to));
}
public function reformatLinkedMessage(array $data, string $chan, bool $asMe = false):string {
$nick=$data['nick'];
if ($matches=$this->testPattern("action",$data['msg'])) {
if (!$asMe) {
$data['msg']="\00302\002$nick\002\003 ".$matches[1];
$message="(".$chan.")"." ".$data['msg'];
/* $message="(".$chan.")".$this->getShortName()." ".$nick." ".$data['msg']; /* sample */
} else {
$message=$data['msg']; /* ELSE if sent asMe ($this->ownerNick ==> $this->nickname ==> $otherConn->nickname, message kept the same */
}
} else {
$message="";
if (!$asMe) {
$message="(".$chan.")"." \002\x1F".$nick."\x1F\002 ".$data['msg'];
} else {
$message.=$data['msg']; /* ELSE same as above */
}
}
return $message;
}
public function sendLinkedPrivate(string $chan, string $to, string $msg) {
foreach ($this->linkedChannels[$chan] as $name => $conn) {
if ($this->owner && !$this->owner->botSent($name)) {
$conn['connection']->sendto($to,$msg);
$this->owner->setBotSent($conn['channel']);
}
}
}
public function reflectToLink(string $to, array $data, bool $asMe = false) { /* to do what the function name says ;op */
/* PRIVMSG must use \bot\events\link or \bot\events\restrictedLink explicitely, otherwise we discard mirroring */
if ((array_search('\bot\events\link',$this->eventHandlers["privmsg"])===FALSE && !$asMe) || ($asMe && array_search('\bot\events\restrictedLink',$this->eventHandlers["privmsg"])===FALSE) )
return;
/* VERSION is discarded too */
if ($this->testPattern("versiononly",$data['msg'])) {
return;
}
/***********************************************
* To avoid ping pong !!
************************************************/
/* /!\ This depends on reformatLinkedMessage settings !! */
$regex="/^\(".chanPattern."\) \002\x1F(?P<nick>[^ ]*)\x1F\002/U";
if (preg_match($regex,$data['msg'],$m)) {
echo "** avoiding pink pong **".PHP_EOL;
return;
}
/***********************************************/
$nick=$data['nick'];
if (isset($this->linkedChannels[$to])) { /* Message for a channel */
/* reformat for message or action */
$message=$this->reformatLinkedMessage($data,$to,$asMe);
/* SEND ONE TIME ONLY */
foreach ($this->linkedChannels[$to] as $name => $conn) {
if ($this->owner && !$this->owner->botSent($name)) {
if ($conn['connection']->isConnected()) {
$conn['connection']->sendto($conn['channel'],$message);
$this->owner->setBotSent($conn['channel']);
}
}
}
} elseif ($to==$this->nickname) { /* PRIVATE MSG for this connection */
$msg_words=preg_split("@ @",$data['msg']);
$msg_to=\bot\stripControlCodes($msg_words[0]);
unset($msg_words[0]);
/* reformat for message or action */
$mpnochan=false; /* if a PM is allowed even if the users is not on a channel */
if ($msg_to[0]=="@") {
$message=\join(" ",$msg_words);
$data['msg']=$message;
$msg_to=substr($msg_to,1); /* messages must be prefixed by @ => @To_nick */
$data['to']=$msg_to;
/* Send to all linked connections */
$message=$this->reformatLinkedMessage($data,$to,true); /* as Me */
/*if (!\bot\events\isChan($msg_to)) {
$message="(".$data['nick'].") ".$message;
}*/
foreach ($this->channels as $chan) {
if (array_key_exists($chan,$this->linkedChannels)) {
foreach ($this->linkedChannels[$chan] as $name => $conn) {
if (!$this->owner->botSent($name)) {
$conn['connection']->sendTo($msg_to,$message);
echo "Sent message to $msg_to on ".$conn['connection']->getShortname().PHP_EOL;
$this->owner->setBotSent($name); /* to avoid further PM to $conn['connection'] */
}
}
}
}
} else {
/* search linked channel */
foreach ($this->channels as $chan) {
if (array_key_exists($chan,$this->linkedChannels)) {
foreach ($this->linkedChannels[$chan] as $name => $conn) {
if (!$this->owner->botSent($name)) {
$data['to']=$chan;
if ($matches=$this->testPattern("action",$data['msg'])) {
$message="\x0303\x02--\x0302".$data['nick']."\x0303--\x03\x02 ".$matches[1];
} else {
$message="\x0303\x02--".$data['nick']."--\x03\x02 ".$data['msg'];
}
$conn['connection']->sendTo($conn['channel'],$message);
echo "Sent message to ".$conn['channel']." on ".$conn['connection']->getShortname().PHP_EOL;
$this->owner->setBotSent($name); /* to avoid further PM to $conn['connection'] */
}
}
}
}
}
}
}
public function addEventHandler(string $event,string $f="") {
if ($f=="")
$f="\\".__NAMESPACE__."\\events\\".$event;
array_push($this->eventHandlers[$event], $f);
}
public function send(string $content):bool {
if (preg_replace("@[\r|\n]@","",$content)=="") return false;
try {
fputs($this->socket, $content . (!preg_match('/[\n]$/', $content)?END:''));
} catch (\Exception $ex) {
$this->debug("Not sent to ".$this-getShortName()." -> exit","ERROR");
\bot\partyline\sendReplyAll("** ERROR ** content not sent : ".$content,$this);
$this->exit();
return false;
}
return true;
}
public function sendTo(string $to, string $line, $conn=false, $notice=false):bool {
if ($to[0]=="#" || $to[0]=="&") {
$to=strtolower($to);
if (array_search($to,$this->channels)===false) {
echo "** not connected to $to **".PHP_EOL;
\bot\partyline\sendReplyAll("** not connected to $to **",($conn===false?$this:$conn));
return false;
}
}
if (!$notice) {
$content="PRIVMSG $to :$line";
} else {
$content="NOTICE $to :$line";
}
fputs($this->socket, $content . (!preg_match('/[\n]$/', $content)?END:''));
$data=array("to" => $to, "msg" => $line, "nick" => $this->getNickname());
\bot\saveMessage($data, $this);
\bot\events\link($data, $this);
return true;
}
/* Other connection */
public function sendToOther(string $other, string $to, string $line, $notice=false):bool {
if ($this->owner==NULL) {
echo "** no other connection available **".PHP_EOL;
\bot\partyline\sendReplyAll("** no other connection available **",$this);
return false;
}
$conn=$this->owner->getConnection($other);
if ($conn===false) {
echo "** this connection is not available : $other **".PHP_EOL;
\bot\partyline\sendReplyAll("** this connection is not available : $other **",$this);
return false;
}
return $conn->sendTo($to, $line, $this, $notice);
}
public function getConnections():array { /* get available other connections */
if ($this->owner==NULL) return array();
$result=array();
foreach ($this->owner->getConnections() as $name => $co) {
if ($co->isConnected())
$result[]=$name;
}
return $result;
}
private function read($bufferSize = 65535):array {
$content = fgets($this->socket, $bufferSize);
if (!preg_match('/[\n]$/', $content)) {
$content .= fgets($this->socket, $bufferSize);
}
return explode(END, trim($content));
}
public function addChanUser(string $chan, string $user) {
$chan=strtolower($chan);
/* $this->debug("Adding $user to $chan"); */
if (!isset($this->channelsUsers[$chan])) {
$this->debug("Creating users list for $chan while adding $user","Notice");
$this->channelsUsers[$chan]=array();
}
if (isset($this->channelsUsers[$chan]) && !$this->chanUserExists($chan,$user)) {
$this->channelsUsers[$chan][]=$user;
natcasesort($this->channelsUsers[$chan]);
}
}
public function removeChanUser(string $chan, string $user) {
if (isset($this->channelsUsers[$chan])) {
$this->channelsUsers[$chan]=array_diff($this->channelsUsers[$chan],array($user));
if (count($this->channelsUsers[$chan])==0)
$this->debug("Users list for $chan has been emptied","ERROR");
} else
$this->debug("$chan users list does not exist","ERROR");
$this->debug("$user removed from $chan users list","Notice");
}
public function changeUserNick(string $user, string $newnick):array { /* returns impacted channels */
$chans=array();
foreach ($this->channelsUsers as $chan => $users) {
if (($index=array_search($user,$users))!==false) {
$this->channelsUsers[$chan][$index]=$newnick;
$chans[]=$chan;
}
}
$this->debug("Changement $user -> $newnick","Notice");
return $chans;
}
public function chanUserExists($chan,$user):bool {
if (isset($this->channelsUsers[$chan])) {
return (array_search($user,$this->channelsUsers[$chan])!==false);
} else
return false;
}
private function setUsersListeningSocket() {
$s=socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
if ($s!==false) {
socket_set_nonblock($s); /* non-blocking */
socket_set_option($s, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($s,"127.0.0.1",$this->userPort);
if (socket_listen($s,$this->maxUsers)===false) { /* max 5 connections */
$this->debug(socket_strerror(socket_last_error()),"ERROR");
die();
}
$this->usersListeningSocket=$s;
echo $this->shortname." : NOW waiting for connections on port ".$this->userPort.PHP_EOL;
} else {
$this->debug("Impossible de créer une socket d'écoute pour un user...","ERROR");
echo socket_strerror(socket_last_error()).PHP_EOL;
die();
}
}
public function getPrompt():string {
return $this->defaultChan."(".$this->shortname.")> ";
}
private function acceptUser() {
if (count($this->usersConnected)<$this->maxUsers && ($s=socket_accept($this->usersListeningSocket))!==false) {
$token=++$this->userTokenCounter;
echo $this->shortname." : user connected, id=".$this->userTokenCounter.PHP_EOL;
$this->usersConnected[$token]=$s;
socket_write($this->usersConnected[$token],$this->getPrompt());
}
}
private function readUser($token, $bufferSize = 8192):array {
if (!$this->hasUsers()) {
return array("");
}
try {
$buf = socket_read($this->getUserSocket($token), $bufferSize);
if ($buf!==false) {
if (!preg_match('/[\r\n]$/', $buf)) {
$buf .= socket_read($this->getUserSocket($token), $bufferSize);
}
return explode(END, trim($buf));
}
} catch (\Exception $ex) {
return "ERROR";
echo "****** ERROR ******".PHP_EOL;
}
return array("");
}
}