fixed bug in Uplink.class.php (fixed handling of Server kicks)
[PHP-P10.git] / Uplink / Uplink.class.php
1 <?php
2 /******************************* PHP-P10 v2 *****************************
3  * Copyright (C) 2011-2012  Philipp Kreil (pk910)                       *
4  *                                                                      *
5  * This program is free software: you can redistribute it and/or modify *
6  * it under the terms of the GNU General Public License as published by *
7  * the Free Software Foundation, either version 3 of the License, or    *
8  * (at your option) any later version.                                  *
9  *                                                                      *
10  * This program is distributed in the hope that it will be useful,      *
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of       *
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        *
13  * GNU General Public License for more details.                         *
14  *                                                                      *
15  * You should have received a copy of the GNU General Public License    *
16  * along with this program. If not, see <http://www.gnu.org/licenses/>. *
17  *                                                                      *
18  ************************************************************************
19  *
20  *  Uplink/Uplink.class.php
21  *
22  * This file contains the basic P10 Protocol handler.
23  *
24  */
25 require_once("Client.class.php");
26 require_once("Numerics.class.php");
27 require_once("P10Formatter.class.php");
28 require_once("P10_Server.class.php");
29 require_once("P10_User.class.php");
30 require_once("P10_Channel.class.php");
31 require_once("P10_ModeSets.class.php");
32 require_once("EventHandler.interface.php");
33 require_once("IPAddr.class.php");
34
35 $e=1;
36 define("ERR_NICK_IN_USE", $e++);
37 define("ERR_INVALID_USER", $e++);
38 define("ERR_INVALID_CHANNAME", $e++);
39 define("ERR_NOT_CONNECTED", $e++);
40 define("ERR_NOT_ON_CHANNEL", $e++);
41
42 class Uplink {
43         private $client;
44         private $settings = array();
45         private $server;
46         private $eventHandler = null;
47         private $last_local_numeric = 0;
48
49         const FLAG_P10SESSION      = 0x0001; //connection is in P10 mode (server is connected)
50         const FLAG_SECURITY_QUIT   = 0x0002; //local connection abort because of security issues
51         const FLAG_NOT_CONNECTABLE = 0x0004; //remote server is not connectable
52         const FLAG_BURST_PENDING   = 0x0008; //we still have to burst
53         const FLAG_CONNECTED       = 0x0010; //connected and synced (ready)
54         const FLAG_GOT_PASS        = 0x0020; //got PASS from the remote Server
55         private $flags = 0;
56
57         public function __construct() {
58                 $this->client = new Client();
59                 $this->setSetting("recv_timeout", 1000);
60                 $this->setSetting("his_usermask", "user.NoMask");
61         }
62
63         public function initialize() {
64                 if($this->server) {
65                         trigger_error("Uplink already initialized.", E_USER_ERROR);
66                         return;
67                 }
68                 $self_numeric = $this->getSetting("numeric");
69                 $self_name = $this->getSetting("name");
70                 $self_description = $this->getSetting("description");
71                 if(!$self_numeric || !$self_name) {
72                         trigger_error("Server Settings missing.", E_USER_ERROR);
73                         return;
74                 }
75                 $this->server = new P10_Server($self_name, $self_numeric, null, time(), time(), $self_description);
76         }
77
78         public function loop() {
79                 if($this->server == null) {
80                         trigger_error("Uplink not initialized.", E_USER_ERROR);
81                         return;
82                 }
83                 if(!$this->client->connected()) {
84                         if(($this->flags & self::FLAG_P10SESSION)) {
85                                 //Server got disconnected
86                                 $this->server->disconnectServer($this->eventHandler, true);
87                                 $this->flags &= ~self::FLAG_P10SESSION;
88                         }
89                         $host = $this->getSetting("host");
90                         $port = $this->getSetting("port");
91                         if($host == null || $port == null) {
92                                 trigger_error("Uplink Settings missing.", E_USER_ERROR);
93                                 return;
94                         }
95                         if(($this->flags & self::FLAG_SECURITY_QUIT) || ($this->flags & self::FLAG_NOT_CONNECTABLE)) {
96                                 sleep(1);
97                         }
98                         $state = $this->client->connect($host, $port, $this->getSetting("bind"), $this->getSetting("ssl"), $this->getSetting("recv_timeout"));
99                         if(!$state) {
100                                 usleep($this->getSetting("recv_timeout") / 1000);
101                                 $this->flags |= self::FLAG_NOT_CONNECTABLE;
102                                 return;
103                         }
104                         $this->flags = 0;
105                         $this->loginServer();
106                 }
107                 //try to receive new data from the Uplink
108                 $lines = $this->client->recv();
109                 if($lines == null) return;
110                 foreach($lines as $line) {
111                         $this->parseLine($line);
112                 }
113         }
114
115         public function shutdown() {
116                 if($this->client->connected()) {
117                         if(($this->flags & self::FLAG_P10SESSION)) {
118                                 $this->send("SQ", "Shutdown requested.");
119                         }
120                         $this->client->disconnect();
121                 }
122         }
123
124         public function setUplinkHost($host, $port, $ssl = false, $bind = null) {
125                 $this->setSetting("host", $host);
126                 $this->setSetting("port", $port);
127                 $this->setSetting("ssl", $ssl);
128                 $this->setSetting("bind", $bind);
129         }
130
131         public function setLoopTimeout($timeout) {
132                 $this->setSetting("recv_timeout", $timeout);
133         }
134
135         public function setUplinkServer($numeric, $name, $password, $description) {
136                 $this->setSetting("numeric", Numerics::intToNum($numeric, 2));
137                 $this->setSetting("name", $name);
138                 $this->setSetting("password", $password);
139                 $this->setSetting("description", $description);
140         }
141
142         public function setValidateServer($name, $password) {
143                 $this->setSetting("their_name", $name);
144                 $this->setSetting("their_password", $password);
145         }
146
147         public function setHISOptions($servername, $serverdesc, $usermask) {
148                 $this->setSetting("his_name", $servername);
149                 $this->setSetting("his_desc", $serverdesc);
150                 $this->setSetting("his_usermask", $usermask);
151         }
152
153         public function setEventHandler($event_handler) {
154                 if(!is_a($event_handler, "EventHandler")) {
155                         trigger_error((is_object($event_handler) ? get_class($event_handler) : gettype($event_handler))." is NOT a valid EventHandler.", E_USER_ERROR);
156                         return;
157                 }
158                 $this->eventHandler = $event_handler;
159         }
160
161         private function setSetting($setting, $value) {
162                 $this->settings[$setting] = $value;
163         }
164
165         private function getSetting($setting) {
166                 if(array_key_exists($setting, $this->settings)) {
167                         return $this->settings[$setting];
168                 } else {
169                         return null;
170                 }
171         }
172
173         private function loginServer() {
174                 $password = $this->getSetting("password");
175                 $this->send("PASS", $password);
176                 $this->send("SERVER", $this->server->getName(), $this->server->getStartTime(), $this->server->getLinkTime(), $this->server->getNumeric(), $this->server->getDescription());
177         }
178
179         private function parseLine($line) {
180                 $highExplode = explode(" :", $line, 2);
181                 $tokens = explode(" ", $highExplode[0]);
182                 if(count($highExplode) > 1)
183                 $tokens[] = $highExplode[1];
184                 $cmdPos = (($this->flags & self::FLAG_P10SESSION) ? 1 : 0);
185                 if($cmdPos == 1) $from = $tokens[0];
186                 else $from = null;
187                 $arguments = array_slice($tokens, $cmdPos + 1);
188                 if(($this->flags & self::FLAG_P10SESSION) && $this->eventHandler) {
189                         $this->eventHandler->event_preparse($from, strtoupper($tokens[$cmdPos]), $arguments);
190                 }
191                 switch(strtoupper($tokens[$cmdPos])) {
192                         //pre P10 Session
193                         case "PASS":
194                                 $this->recv_pass($from, $arguments);
195                                 break;
196                         case "SERVER":
197                                 $this->recv_server($from, $arguments);
198                                 break;
199                         case "ERROR":
200                                 $this->recv_error($from, $arguments);
201                                 break;
202                                 //P10 Session
203                         case "S":
204                                 $this->recv_server($from, $arguments);
205                                 break;
206                         case "G":
207                                 $this->recv_ping($from, $arguments);
208                                 break;
209                         case "N":
210                                 $this->recv_nick($from, $arguments);
211                                 break;
212                         case "EB":
213                                 $this->recv_end_of_burst($from, $arguments);
214                                 break;
215                         case "EA":
216                                 $this->recv_end_of_burst_ack($from, $arguments);
217                                 break;
218                         case "SQ":
219                                 $this->recv_server_quit($from, $arguments);
220                                 break;
221                         case "Q":
222                                 $this->recv_quit($from, $arguments);
223                                 break;
224                         case "B":
225                                 $this->recv_burst($from, $arguments);
226                                 break;
227                         case "J":
228                         case "C":
229                                 $this->recv_join($from, $arguments);
230                                 break;
231                         case "L":
232                                 $this->recv_part($from, $arguments);
233                                 break;
234                         case "K":
235                                 $this->recv_kick($from, $arguments);
236                                 break;
237                         case "D":
238                                 $this->recv_kill($from, $arguments);
239                                 break;
240                         case "P":
241                                 $this->recv_privmsg($from, $arguments);
242                                 break;
243                         case "O":
244                                 $this->recv_notice($from, $arguments);
245                                 break;
246                         case "W":
247                                 $this->recv_whois($from, $arguments);
248                                 break;
249                         case "A":
250                                 $this->recv_away($from, $arguments);
251                                 break;
252                         case "M":
253                         case "OM":
254                                 $this->recv_mode($from, $arguments);
255                                 break;
256                         case "AC":
257                                 $this->recv_account($from, $arguments);
258                                 break;
259                         case "FA":
260                                 $this->recv_fakehost($from, $arguments);
261                                 break;
262                         case "NFH":
263                                 $this->recv_newfakehost($from, $arguments);
264                                 break;
265                                 //default
266                         default:
267                                 //unknown cmd
268                                 if($this->eventHandler)
269                                 $this->eventHandler->event_unknown_cmd($from, strtoupper($tokens[$cmdPos]), $arguments);
270                                 break;
271                 }
272         }
273
274         private function send($command) {
275                 if(func_num_args() > 1) {
276                         $args = array_slice(func_get_args(), 1);
277                         $command = P10Formatter::formatCMD($this->getSetting("numeric"), $command, $args);
278                 } else {
279                         $command = P10Formatter::formatCMD($this->getSetting("numeric"), $command, array());
280                 }
281                 $this->client->send($command);
282         }
283
284         /********************************************************************************************
285          *                                     INCOMING COMMANDS                                    *
286          ********************************************************************************************/
287
288         private function recv_pass($from, $args) {
289                 $their_pass = $this->getSetting("their_password");
290                 if($their_pass) {
291                         if($args[0] != $their_pass) {
292                                 //security QUIT
293                                 $this->flags |= self::FLAG_SECURITY_QUIT;
294                                 $this->send("ERROR", "Incorrect password received.");
295                                 $this->client->disconnect();
296                                 return;
297                         }
298                         $this->flags |= self::FLAG_GOT_PASS;
299                 }
300         }
301
302         private function recv_error($from, $args) {
303                 //we received an error - the socket is dead for us, now
304                 //maybe we want to log this, later
305                 $this->client->disconnect();
306         }
307
308         private function recv_server($from, $args) {
309                 if($from == null) {
310                         //our uplink Server
311                         $their_name = $this->getSetting("their_name");
312                         if($their_name && $args[0] != $their_name) {
313                                 $this->flags |= self::FLAG_SECURITY_QUIT;
314                                 $this->send("ERROR", "Invalid Server name");
315                                 $this->client->disconnect();
316                                 return;
317                         }
318                         if($this->getSetting("their_password") && !($this->flags & self::FLAG_GOT_PASS)) {
319                                 $this->flags |= self::FLAG_SECURITY_QUIT;
320                                 $this->send("ERROR", "PASS missing.");
321                                 $this->client->disconnect();
322                                 return;
323                         }
324                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $this->server, $args[2], $args[3], $args[7]);
325                         $this->server->addServer($new_server);
326                         $this->flags |= self::FLAG_P10SESSION | self::FLAG_BURST_PENDING;
327                         if($this->eventHandler)
328                         $this->eventHandler->event_newserver($new_server, !($this->flags & self::FLAG_CONNECTED));
329                 } else {
330                         //another server got a new slave server ^^
331                         $server = P10_Server::getServerByNum($from);
332                         if($server == null) {
333                                 trigger_error("Parent Server (".$from.") does not exist or was not found on recv_server.", E_USER_ERROR);
334                                 return;
335                         }
336                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $server, $args[2], $args[3], $args[7]);
337                         $server->addServer($new_server);
338                         if($this->eventHandler)
339                         $this->eventHandler->event_newserver($new_server, !($this->flags & self::FLAG_CONNECTED));
340                 }
341         }
342
343         private function recv_ping($from, $args) {
344                 $this->send("Z", $args[0]); //simply PONG
345                 P10_Channel::recheckAllChannels();
346         }
347
348         private function recv_nick($from, $args) {
349                 if(count($args) <= 2) {
350                         //Nick change
351                         $user = P10_User::getUserByNum($from);
352                         if($user == null) {
353                                 trigger_error("Server tries to change the nick of an user that does not exist or was not found on recv_nick.", E_USER_ERROR);
354                                 return;
355                         }
356                         if($this->eventHandler)
357                         $this->eventHandler->event_nick($user, $args[0]);
358                         $user->setNick($args[0]);
359                 } else {
360                         //New User
361                         $numeric = $args[count($args)-2];
362                         $nick = $args[0];
363                         $server = P10_Server::getServerByNum($from);
364                         if($server == null) {
365                                 trigger_error("Server (".$from.") the User (".$nick.") is coming from does not exist or was not found on recv_nick.", E_USER_ERROR);
366                                 return;
367                         }
368                         if(substr($numeric,0,2) != $from) {
369                                 trigger_error("A Server (".$from.") tries to connect a User with an invalid User numeric ('".$numeric."' does not belong to the Server)", E_USER_WARNING);
370                         }
371                         $connect_time = $args[2];
372                         $ident = $args[3];
373                         $host = $args[4];
374                         $modes = implode(" ",array_slice($args, 5, count($args)-8));
375                         $modes = new P10_UserModeSet($modes);
376                         $ip = new IPAddr($args[count($args)-3]);
377                         if($host == $server->getName())
378                                 $ip->setServerAddr(true);
379                         $realname = $args[count($args)-1];
380                         $user = new P10_User($nick, $numeric, $server, $connect_time, $ident, $host, $ip, $realname, $modes);
381                         if($this->eventHandler)
382                         $this->eventHandler->event_connect($user, !($this->flags & self::FLAG_CONNECTED));
383                 }
384         }
385
386         private function recv_end_of_burst($from, $args) {
387                 if(($this->flags & self::FLAG_BURST_PENDING)) {
388                         $this->burst();
389                         $this->send("EA");
390                         $this->flags &= ~self::FLAG_BURST_PENDING;
391                 }
392         }
393
394         private function recv_end_of_burst_ack($from, $args) {
395                 $this->flags |= self::FLAG_CONNECTED;
396         }
397
398         private function recv_server_quit($from, $args) {
399                 $server = P10_Server::getServerByName($args[0]);
400                 if($server == null) {
401                         trigger_error("Server (".$args[0].") not found.", E_USER_ERROR);
402                         return;
403                 }
404                 $server->disconnectServer($this->eventHandler);
405         }
406
407         private function recv_quit($from, $args) {
408                 $user = P10_User::getUserByNum($from);
409                 if($user == null) {
410                         trigger_error("Server tries to quit an user that does not exist or was not found on recv_quit.", E_USER_ERROR);
411                         return;
412                 }
413                 $user->quit($args[0]);
414                 if($this->eventHandler)
415                 $this->eventHandler->event_quit($user, $args[0]);
416         }
417
418         private function recv_burst($from, $args) {
419                 $name = $args[0];
420                 $create_time = $args[1];
421                 if(count($args) == 2) {
422                         //we've got an empty channel without any modes set???  dead channel!
423                         return;
424                 }
425                 $channel = P10_Channel::getChannelByName($name);
426                 if($channel == null)
427                 $channel = new P10_Channel($name);
428                 $channel->setCreateTime($create_time);
429                 $modes = $channel->getModes();
430                 $userstr = $args[count($args)-1];
431                 if($userstr[0] == "%") {
432                         //ban list
433                         $banlist = explode(" ", substr($userstr, 1));
434                         foreach($banlist as $ban) {
435                                 //TODO: save bans
436                         }
437                         $userstr = $args[count($args)-2];
438                 }
439                 if($userstr[0] == "+") { //MODE String
440                         $userstr = "";
441                 }
442                 $users = explode(",",$userstr);
443                 $isop = false; $ishalfop = false; $isvoice = false;
444                 foreach($users as $user) {
445                         if($user == "") continue;
446                         $uexp = explode(":", $user);
447                         if(strlen($uexp[0]) != 5) {
448                                 trigger_error("burst parse error: '".$uexp[0]."' is not an user numeric.", E_USER_WARNING);
449                                 break;
450                         }
451                         if(count($uexp) > 1) {
452                                 $isop = false;
453                                 $ishalfop = false;
454                                 $isvoice = false;
455                                 for($i = 0; $i < strlen($uexp[1]); $i++) {
456                                         if($uexp[1][0] == "@") $isop = true;
457                                         if($uexp[1][0] == "%") $ishalfop = true;
458                                         if($uexp[1][0] == "+") $isvoice = true;
459                                 }
460                         }
461                         $user = P10_User::getUserByNum($uexp[0]);
462                         if($user == null) {
463                                 trigger_error("burst parse error: cant find User '".$uexp[0]."'.", E_USER_ERROR);
464                                 return;
465                         }
466                         $channel->burstUser($user, $isop, $ishalfop, $isvoice);
467                         if($this->eventHandler)
468                         $this->eventHandler->event_join($user, $channel, true);
469                 }
470                 $modestr = array_slice($args, 2);
471                 if($modestr[0] == "+")
472                 $modes->parseModes(implode(" ", $modestr));
473         }
474
475         private function recv_join($from, $args) {
476                 $user = P10_User::getUserByNum($from);
477                 if($user == null) {
478                         trigger_error("Server tries to join an user that does not exist or was not found on recv_join.", E_USER_ERROR);
479                         return;
480                 }
481                 $channel = P10_Channel::getChannelByName($args[0]);
482                 if($channel == null)
483                 $channel = new P10_Channel($args[0]);
484                 $channel->joinUser($user);
485                 if($this->eventHandler)
486                 $this->eventHandler->event_join($user, $channel, false);
487         }
488
489         private function recv_part($from, $args) {
490                 $user = P10_User::getUserByNum($from);
491                 if($user == null) {
492                         trigger_error("Server tries to part an user that does not exist or was not found on recv_join.", E_USER_ERROR);
493                         return;
494                 }
495                 $channel = P10_Channel::getChannelByName($args[0]);
496                 if($channel == null)
497                 $channel = new P10_Channel($args[0]);
498                 if($this->eventHandler)
499                 $this->eventHandler->event_part($user, $channel, $args[1]);
500                 $channel->partUser($user);
501         }
502
503         private function recv_kick($from, $args) {
504                 $user = P10_User::getUserByNum($from);
505                 if($user == null && strlen($from) != 2) {
506                         trigger_error("An unknown user tries to kick another user on recv_kick.", E_USER_ERROR);
507                         return;
508                 }
509                 $channel = P10_Channel::getChannelByName($args[0]);
510                 if($channel == null)
511                 $channel = new P10_Channel($args[0]);
512                 $target = P10_User::getUserByNum($args[1]);
513                 if($target == null) {
514                         trigger_error("Someone tries to kick an user that does not exist or was not found on recv_kick.", E_USER_ERROR);
515                         return;
516                 }
517                 if($this->eventHandler)
518                 $this->eventHandler->event_kick($user, $target, $channel, $args[1]);
519                 $channel->partUser($target);
520         }
521
522         private function recv_kill($from, $args) {
523                 $user = P10_User::getUserByNum($args[0]);
524                 if($user == null) {
525                         trigger_error("Server tries to kill an user that does not exist or was not found on recv_quit.", E_USER_ERROR);
526                         return;
527                 }
528                 $user->quit($args[1]);
529                 if($this->eventHandler)
530                 $this->eventHandler->event_quit($user, "Killed (".$args[1].")");
531         }
532
533         private function recv_privmsg($from, $args) {
534                 $user = P10_User::getUserByNum($from);
535                 if($user == null) {
536                         trigger_error("Server tries to send a privmsg from an user that does not exist or was not found on recv_privmsg.", E_USER_WARNING);
537                         return;
538                 }
539                 if($this->eventHandler) {
540                         if($args[0][0] == "#") {
541                                 $channel = P10_Channel::getChannelByName($args[0]);
542                                 if($channel == null)
543                                 $channel = new P10_Channel($args[0]);
544                                 if(strlen($args[1]) > 0 && $args[1][0] == "\001") {
545                                         //ctcp
546                                         $args[1] = substr($args[1],1);
547                                         if($args[1][strlen($args[1])-1] == "\001")
548                                         $args[1] = substr($args[1],0,-1);
549                                         $ctcpexp = explode(" ",$args[1],2);
550                                         $this->eventHandler->event_chanctcp($user, $channel, strtoupper($ctcpexp[0]), (count($ctcpexp) > 1 ? $ctcpexp[1] : null));
551                                 } else
552                                 $this->eventHandler->event_chanmessage($user, $channel, $args[1]);
553                         } else if($args[0][0] == "$") {
554                                 //"multicast"
555                                 $this->eventHandler->event_privmessage($user, NULL, $args[1]);
556                         } else {
557                                 $targetUser = P10_User::getUserByNum($args[0]);
558                                 if($targetUser == null) {
559                                         trigger_error("Server tries to send a privmsg to an user that does not exist or was not found on recv_privmsg.", E_USER_WARNING);
560                                         return;
561                                 }
562                                 if(strlen($args[1]) > 0 && $args[1][0] == "\001") {
563                                         //ctcp
564                                         $args[1] = substr($args[1],1);
565                                         if($args[1][strlen($args[1])-1] == "\001")
566                                         $args[1] = substr($args[1],0,-1);
567                                         $ctcpexp = explode(" ",$args[1],2);
568                                         $this->eventHandler->event_privctcp($user, $targetUser, strtoupper($ctcpexp[0]), (count($ctcpexp) > 1 ? $ctcpexp[1] : null));
569                                 } else
570                                 $this->eventHandler->event_privmessage($user, $targetUser, $args[1]);
571                         }
572                 }
573         }
574
575         private function recv_notice($from, $args) {
576                 $user = P10_User::getUserByNum($from);
577                 if($user == null) {
578                         trigger_error("Server tries to send a notice from an user that does not exist or was not found on recv_notice.", E_USER_WARNING);
579                         return;
580                 }
581                 if($this->eventHandler) {
582                         if($args[0][0] == "#") {
583                                 $channel = P10_Channel::getChannelByName($args[0]);
584                                 if($channel == null)
585                                 $channel = new P10_Channel($args[0]);
586                                 if(strlen($args[1]) > 0 && $args[1][0] == "\001") {
587                                         //ctcp
588                                         $args[1] = substr($args[1],1);
589                                         if($args[1][strlen($args[1])-1] == "\001")
590                                         $args[1] = substr($args[1],0,-1);
591                                         $ctcpexp = explode(" ",$args[1],2);
592                                         $this->eventHandler->event_chanctcpreply($user, $channel, strtoupper($ctcpexp[0]), (count($ctcpexp) > 1 ? $ctcpexp[1] : null));
593                                 } else
594                                 $this->eventHandler->event_channotice($user, $channel, $args[1]);
595                         } else if($args[0][0] == "$") {
596                                 //"multicast"
597                                 $this->eventHandler->event_privnotice($user, NULL, $args[1]);
598                         } else {
599                                 $targetUser = P10_User::getUserByNum($args[0]);
600                                 if($targetUser == null) {
601                                         trigger_error("Server tries to send a notice to an user that does not exist or was not found on recv_notice.", E_USER_WARNING);
602                                         return;
603                                 }
604                                 if(strlen($args[1]) > 0 && $args[1][0] == "\001") {
605                                         //ctcp
606                                         $args[1] = substr($args[1],1);
607                                         if($args[1][strlen($args[1])-1] == "\001")
608                                         $args[1] = substr($args[1],0,-1);
609                                         $ctcpexp = explode(" ",$args[1],2);
610                                         $this->eventHandler->event_privctcpreply($user, $targetUser, strtoupper($ctcpexp[0]), (count($ctcpexp) > 1 ? $ctcpexp[1] : null));
611                                 } else
612                                 $this->eventHandler->event_privnotice($user, $targetUser, $args[1]);
613                         }
614                 }
615         }
616
617         private function recv_whois($from, $args) {
618                 /* [get] ACAAF W AX :NetworkServ */
619                 $fromUser = P10_User::getUserByNum($from);
620                 if($fromUser == null) {
621                         trigger_error("Server tries to send a whois from an user that does not exist or was not found on recv_whois.", E_USER_ERROR);
622                         return;
623                 }
624                 $users=explode(",",$args[1]);
625                 foreach($users as $nick) {
626                         $user = P10_User::getUserByNick($nick);
627                         if(!$user) {
628                                 $this->send("401", $from, $nick);
629                                 continue;
630                         }
631                         $nick = $user->getNick();
632                         $ident = $user->getIdent();
633                         $hostmask = $user->getHost();
634                         $modes = $user->getModes();
635                         if($modes->hasMode('x')) {
636                                 if(($fakehost = $modes->hasMode('f'))) {
637                                         $hostmask = $fakehost;
638                                 } elseif(($account = $modes->hasMode('r'))) {
639                                         $hostmask = $account.".".$this->getSetting("his_usermask");
640                                 }
641                         }
642                         $realname = $user->getRealname();
643                         $this->send("311", $from , $nick, $ident, $hostmask, $realname);
644                         if(((!$modes->hasMode('n') && !$modes->hasMode('k')) || $from == $user->getNumeric()) && count($user->getChannels()) != 0) {
645                                 $channels = "";
646                                 foreach($user->getChannels() as $channel) {
647                                         $cmodes = $channel->getModes();
648                                         $privs = $channel->getUserPrivs($user);
649                                         if($cmodes->hasMode("s") && !$fromUser->isOnChannel($channel) && $from != $user->getNumeric()) continue;
650                                         if($cmodes->hasMode("u") && ($privs & (P10_Channel::USERPRIV_OPED | P10_Channel::USERPRIV_VOICE)) == 0 && $from != $user->getNumeric()) continue;
651                                         $chanstr = ($channels == "" ? "" : " ");
652                                         $prefix = "";
653                                         if(($privs & P10_Channel::USERPRIV_OPED)) {
654                                                 $prefix = "@";
655                                         } else if(($privs & P10_Channel::USERPRIV_VOICE)) {
656                                                 $prefix = "+";
657                                         }
658                                         $chanstr .= $prefix.$channel->getName();
659                                         if(strlen($channels) + strlen($chanstr) > 450) {
660                                                 $this->send("319", $from, $nick, $channels);
661                                                 $channels = $prefix.$channel->getName();
662                                         }
663                                 }
664                                 if($channels != "") {
665                                         $this->send("319", $from, $nick, $channels);
666                                 }
667                         }
668                         if($fromUser->getModes()->hasMode("o") || $from == $user->getNumeric() || !$this->getSetting("his_name")) {
669                                 $this->send("312", $from, $nick, $user->getServer()->getName(), $user->getServer()->getDescription());
670                         } else {
671                                 $this->send("312", $from, $nick, $this->getSetting("his_name"), $this->getSetting("his_desc"));
672                         }
673                         if($modes->hasMode("o") && (!$modes->hasMode("H") || $fromUser->getModes()->hasMode("o"))) {
674                                 if($modes->hasMode("S")) {
675                                         if($modes->hasMode("D"))
676                                         $this->send("313", $from, $nick, "is a Network Service");
677                                         else
678                                         $this->send("313", $from, $nick, "is an illegal Network Service - HACKER!");
679                                 } else
680                                 $this->send("313", $from, $nick, "is an IRC Operator");
681                         }
682                         if(($auth = $modes->hasMode("r"))) {
683                                 $this->send("330", $from, $nick, $auth);
684                         }
685                 }
686                 $this->send("318", $from, $args[1]);
687         }
688
689         private function recv_away($from, $args) {
690                 $user = P10_User::getUserByNum($from);
691                 if($user == null) {
692                         trigger_error("Server tries to send an away command from an user that does not exist or was not found on recv_away.", E_USER_ERROR);
693                         return;
694                 }
695                 if(count($args) > 0) {
696                         $user->setAway($args[0]);
697                         if($this->eventHandler)
698                         $this->eventHandler->event_away($user, $args[0]);
699                 } else {
700                         $user->setAway(null);
701                         if($this->eventHandler)
702                         $this->eventHandler->event_away($user, null);
703                 }
704         }
705
706         private function recv_mode($from, $args) {
707                 $user = P10_User::getUserByNum($from);
708                 if($user == null && strlen($from) != 2) {
709                         trigger_error("Server tries to send a modechange from an user that does not exist or was not found on recv_mode.", E_USER_ERROR);
710                         return;
711                 }
712                 $modes = implode(" ",array_slice($args,1));
713                 if($args[0][0] == "#") {
714                         $channel = P10_Channel::getChannelByName($args[0]);
715                         if($channel == null)
716                         $channel = new P10_Channel($args[0]);
717                         $channel->getModes()->setModes($modes);
718                         if($this->eventHandler && strlen($from) != 2)
719                         $this->eventHandler->event_chanmode($user, $channel, $modes);
720                 } else {
721                         $targetUser = P10_User::getUserByNick($args[0]);
722                         if($targetUser == null) {
723                                 trigger_error("Server tries to send a mode to an user that does not exist or was not found on recv_mode.", E_USER_ERROR);
724                                 return;
725                         }
726                         $targetUser->getModes()->setModes($modes);
727                         $fakemodes = NULL;
728                         if($targetUser->getModes()->hasMode("x") && $targetUser->getModes()->hasMode("r") && !$targetUser->getModes()->hasMode("f")) {
729                                 //user is registered and has umode +x set (automatically assign default fakehost)
730                                 $fakemodes = "+f ".$targetUser->getModes()->hasMode("r").".".$this->getSetting("his_usermask");
731                                 $targetUser->getModes()->setModes($fakemodes);
732                         }
733                         if($this->eventHandler) {
734                                 $this->eventHandler->event_usermode($targetUser, $modes);
735                                 if($fakemodes)
736                                 $this->eventHandler->event_usermode($targetUser, $fakemodes);
737                         }
738                 }
739         }
740
741         private function recv_account($from, $args) {
742                 $user = P10_User::getUserByNum($args[0]);
743                 if($user == null) {
744                         trigger_error("Server tries to send an auth announce from an user that does not exist or was not found on recv_account.", E_USER_ERROR);
745                         return;
746                 }
747                 $auth = $args[1];
748                 $user->getModes()->setModes("+r ".$auth);
749                 $fakemodes = NULL;
750                 if($user->getModes()->hasMode("x") && !$user->getModes()->hasMode("f")) {
751                         //user is registered and has umode +x set (automatically assign default fakehost)
752                         $fakemodes = "+f ".$auth.".".$this->getSetting("his_usermask");
753                         $user->getModes()->setModes($fakemodes);
754                 }
755                 if($this->eventHandler) {
756                         $this->eventHandler->event_usermode($user, "+r ".$auth);
757                         if($fakemodes)
758                         $this->eventHandler->event_usermode($user, $fakemodes);
759                 }
760         }
761
762         private function recv_fakehost($from, $args) {
763                 $user = P10_User::getUserByNum($args[0]);
764                 if($user == null) {
765                         trigger_error("Server tries to send a fakehost change from an user that does not exist or was not found on recv_fakehost.", E_USER_ERROR);
766                         return;
767                 }
768                 $fakehost = $args[1];
769                 $user->getModes()->setModes("+f ".$fakehost);
770                 if($this->eventHandler)
771                 $this->eventHandler->event_usermode($user, "+f ".$fakehost);
772         }
773
774         private function recv_newfakehost($from, $args) {
775                 $user = P10_User::getUserByNum($args[0]);
776                 if($user == null) {
777                         trigger_error("Server tries to send a fakehost change from an user that does not exist or was not found on recv_fakehost.", E_USER_ERROR);
778                         return;
779                 }
780                 $fakeident = $args[1];
781                 $fakehost = $args[2];
782                 $user->setIdent($fakeident);
783                 $user->getModes()->setModes("+f ".$fakehost);
784                 if($this->eventHandler)
785                 $this->eventHandler->event_usermode($user, "+f ".$fakehost);
786         }
787
788         /********************************************************************************************
789          *                                     SERVER FUNCTIONS                                     *
790          ********************************************************************************************/
791
792         private function burst() {
793                 foreach($this->server->getUsers() as $user) {
794                         $nick = $user->getNick();
795                         $connect_time = $user->getConnectTime();
796                         $ident = $user->getIdent();
797                         $host = $user->getHost();
798                         $modes = $user->getModes()->getModeString();
799                         $ip = $user->getIP()->getNumeric();
800                         $numeric = $user->getNumeric();
801                         $realname = $user->getRealname();
802                         $this->send("N", $nick, $connect_time, $ident, $host, $modes, $ip, $numeric, $realname);
803                 }
804                 foreach(P10_Channel::getChannels() as $channel) {
805                         $privs_to_burst = array('o',                        'h',                          'v'                         );
806                         $priv_values =    array(P10_Channel::USERPRIV_OPED, P10_Channel::USERPRIV_HALFOP, P10_Channel::USERPRIV_VOICE );
807                         $priv_combinations = array();
808                         $sorted_users = array();
809                         $combinations = pow(2, count($privs_to_burst)); //binary possibilities => 2^count($privs_to_burst)
810                         for($i = 0; $i < $combinations; $i++) {
811                                 //make a binary number out of $i
812                                 $binary = decbin($i);
813                                 while(strlen($binary) < count($privs_to_burst))
814                                 $binary = '0'.$binary;
815                                 $combination_name = '';
816                                 $combination_value = 0;
817                                 for($j = 0; $j < count($privs_to_burst); $j++) {
818                                         if($binary[$j] == '1') {
819                                                 $combination_name .= $privs_to_burst[$j];
820                                                 $combination_value += $priv_values[$j];
821                                         }
822                                 }
823                                 $priv_combinations[] = array("name" => $combination_name, "value" => $combination_value);
824                                 $sorted_users[$combination_value] = array();
825                         }
826                         $local_users = false;
827                         foreach($channel->getUsers() as $user) {
828                                 if(substr($user->getNumeric(), 0, 2) != $this->server->getNumeric()) continue; //skip users that are not on the local server
829                                 $privs = $channel->getUserPrivs($user);
830                                 $local_users = true;
831                                 $sorted_users[$privs][] = $user;
832                         }
833                         if(!$local_users) continue;
834                         $userStr = "";
835                         foreach($priv_combinations as $combination) {
836                                 $i = 0;
837                                 foreach($sorted_users[$combination['value']] as $user) {
838                                         if($userStr != "") $userStr.=",";
839                                         $userStr .= $user->getNumeric();
840                                         if(($i++) == 0 && $combination['value'] > 0) {
841                                                 $userStr .= ":".$combination['name'];
842                                         }
843                                 }
844                         }
845                         $banString = "";
846                         //TODO: Build ban String
847                         $burstString = "";
848                         $modeString = $channel->getModes()->getModeString();
849                         if($modeString != "+") {
850                                 $burstString .= $modeString;
851                         }
852                         if($userStr != "") {
853                                 if($burstString != "") $burstString .= " ";
854                                 $burstString .= $userStr;
855                         }
856                         if($banString != "") {
857                                 if($burstString != "") $burstString .= " ";
858                                 $burstString .= ":%".$banString;
859                         }
860                         $this->send("B", $channel->getName(), $channel->getCreateTime(), $burstString);
861                 }
862                 $this->send("EB");
863         }
864
865         /********************************************************************************************
866          *                                    LOCAL USER FUNCTIONS                                  *
867          ********************************************************************************************/
868
869         public function addUser($nick, $ident, $host, $ip, $modes, $realname) {
870                 $user = P10_User::getUserByNick($nick);
871                 if($user != null) return ERR_NICK_IN_USE;
872                 $numeric = substr($this->server->getNumeric(),0,2).Numerics::intToNum($this->last_local_numeric, 3);
873                 while(P10_User::getUserByNum($numeric)) {
874                         $this->last_local_numeric++;
875                         $numeric = substr($this->server->getNumeric(),0,2).Numerics::intToNum($this->last_local_numeric, 3);
876                 }
877                 $this->last_local_numeric++;
878                 $modes = new P10_UserModeSet($modes);
879                 $ip = new IPAddr($ip);
880                 $user = new P10_User($nick, $numeric, $this->server, time(), $ident, $host, $ip, $realname, $modes);
881                 if(($this->flags & self::FLAG_CONNECTED)) {
882                         $ip = $user->getIP()->getNumeric();
883                         $this->send("N", $nick, $user->getConnectTime(), $ident, $host, $user->getModes()->getModeString(), $ip, $numeric, $realname);
884                 }
885                 return $user;
886         }
887
888         public function delUser($user, $reason) {
889                 if(!is_a($user, "P10_User")) return ERR_INVALID_USER;
890                 if($user->getServer() === $this->server) {
891                         //local user (QUIT)
892                         $user->quit($reason);
893                         if(($this->flags & self::FLAG_CONNECTED))
894                         $this->send("Q", $user->getNumeric(), $reason);
895                 } else {
896                         //remote user (KILL)
897                         if(!($this->flags & self::FLAG_CONNECTED))
898                         return ERR_NOT_CONNECTED;
899                         if($this->eventHandler)
900                         $this->eventHandler->event_quit($user, "Killed (".$reason.")");
901                         $user->quit("Killed (".$reason.")");
902                         $name = ($this->getSetting('his_name') ? $this->getSetting('his_name') : $this->getSetting('name'));
903
904                         $this->send("D", $user->getNumeric(), $name, $reason);
905                 }
906         }
907
908         public function join($user, $chanName, $privs = 0) {
909                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
910                 return ERR_INVALID_USER;
911                 if($chanName[0] != "#")
912                 return ERR_INVALID_CHANNAME;
913                 $channel = P10_Channel::getChannelByName($chanName);
914                 if($channel == null)
915                 $channel = new P10_Channel($chanName);
916                 $channel->joinUser($user);
917                 if(($this->flags & self::FLAG_CONNECTED))
918                 $this->send("J", $user->getNumeric(), $chanName, time(), 0);
919                 if($privs != 0) {
920                         $channel->setUserPrivs($user, $privs);
921                         if(($this->flags & self::FLAG_CONNECTED)) {
922                                 $modestr = "+".(($privs & P10_Channel::USERPRIV_OPED) ? "o" : "").(($privs & P10_Channel::USERPRIV_HALFOP) ? "h" : "").(($privs & P10_Channel::USERPRIV_VOICE) ? "v" : "");
923                                 $modestr .= (($privs & P10_Channel::USERPRIV_OPED) ? " ".$user->getNumeric() : "");
924                                 $modestr .= (($privs & P10_Channel::USERPRIV_HALFOP) ? " ".$user->getNumeric() : "");
925                                 $modestr .= (($privs & P10_Channel::USERPRIV_VOICE) ? " ".$user->getNumeric() : "");
926                                 $this->send(($user->getModes()->hasMode('k') ? "M" : "OM"), $user->getNumeric(), $chanName, $modestr);
927                         }
928                 }
929                 if($this->eventHandler)
930                 $this->eventHandler->event_join($user, $channel, false);
931         }
932
933         public function part($user, $chanName, $reason) {
934                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
935                 return ERR_INVALID_USER;
936                 if(!((is_string($chanName) && $chanName[0] == "#") || is_a($chanName, "P10_Channel")))
937                 return ERR_INVALID_CHANNAME;
938                 if(is_a($chanName, "P10_Channel"))
939                 $channel = $chanName;
940                 else
941                 $channel = P10_Channel::getChannelByName($chanName);
942                 if($channel == null)
943                 $channel = new P10_Channel($chanName);
944                 if(!$user->isOnChannel($channel))
945                 return ERR_NOT_ON_CHANNEL;
946                 if($this->eventHandler)
947                 $this->eventHandler->event_part($user, $channel, $reason);
948                 $channel->partUser($user, $reason);
949                 if(($this->flags & self::FLAG_CONNECTED))
950                 $this->send("L", $user->getNumeric(), $chanName, $reason);
951         }
952
953         public function kick($user, $target, $chanName, $reason) {
954                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
955                 return ERR_INVALID_USER;
956                 if(!is_a($target, "P10_User"))
957                 return ERR_INVALID_USER;
958                 if(!((is_string($chanName) && $chanName[0] == "#") || is_a($chanName, "P10_Channel")))
959                 return ERR_INVALID_CHANNAME;
960                 if(is_a($chanName, "P10_Channel"))
961                 $channel = $chanName;
962                 else
963                 $channel = P10_Channel::getChannelByName($chanName);
964                 if($channel == null)
965                 $channel = new P10_Channel($chanName);
966                 if(!$target->isOnChannel($channel))
967                 return ERR_NOT_ON_CHANNEL;
968                 if($this->eventHandler)
969                 $this->eventHandler->event_kick($user, $target, $channel, $reason);
970                 $channel->partUser($target, $reason);
971                 if(($this->flags & self::FLAG_CONNECTED))
972                 $this->send("K", $user->getNumeric(), $channel->getName(), $target->getNumeric(), $reason);
973         }
974
975         public function privmsg($user, $target, $message) {
976                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
977                 return ERR_INVALID_USER;
978                 if(!is_a($target, "P10_User") && !is_a($target, "P10_Channel") && !(is_string($target) && ($target[0] == "#" || P10_User::getUserByNick($target))))
979                 return ERR_INVALID_USER;
980                 if(is_a($target, "P10_Channel"))
981                 $targetStr = $target->getName();
982                 else if(is_a($target, "P10_User"))
983                 $targetStr = $target->getNumeric();
984                 else if($target[0] == "#")
985                 $targetStr = $target;
986                 else
987                 $targetStr = P10_User::getUserByNick($target)->getNumeric();
988
989                 if($this->eventHandler) {
990                         if($targetStr[0] == "#") {
991                                 $channel = P10_Channel::getChannelByName($targetStr);
992                                 if($channel == null)
993                                 $channel = new P10_Channel($targetStr);
994                                 $this->eventHandler->event_chanmessage($user, $channel, $message);
995                         } else {
996                                 $targetUser = P10_User::getUserByNum($targetStr);
997                                 $this->eventHandler->event_privmessage($user, $targetUser, $message);
998                         }
999                 }
1000                 if(($this->flags & self::FLAG_CONNECTED))
1001                 $this->send("P", $user->getNumeric(), $targetStr, $message);
1002         }
1003
1004         public function notice($user, $target, $message) {
1005                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
1006                 return ERR_INVALID_USER;
1007                 if(!is_a($target, "P10_User") && !is_a($target, "P10_Channel") && !(is_string($target) && ($target[0] == "#" || P10_User::getUserByNick($target))))
1008                 return ERR_INVALID_USER;
1009                 if(is_a($target, "P10_Channel"))
1010                 $targetStr = $target->getName();
1011                 else if(is_a($target, "P10_User"))
1012                 $targetStr = $target->getNumeric();
1013                 else if($target[0] == "#")
1014                 $targetStr = $target;
1015                 else
1016                 $targetStr = P10_User::getUserByNick($target)->getNumeric();
1017
1018                 if($this->eventHandler) {
1019                         if($targetStr[0] == "#") {
1020                                 $channel = P10_Channel::getChannelByName($targetStr);
1021                                 if($channel == null)
1022                                 $channel = new P10_Channel($targetStr);
1023                                 $this->eventHandler->event_channotice($user, $channel, $message);
1024                         } else {
1025                                 $targetUser = P10_User::getUserByNum($targetStr);
1026                                 $this->eventHandler->event_privnotice($user, $targetUser, $message);
1027                         }
1028                 }
1029                 if(($this->flags & self::FLAG_CONNECTED))
1030                 $this->send("O", $user->getNumeric(), $targetStr, $message);
1031         }
1032
1033         public function mode($user, $target, $modes, $force = false) {
1034                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
1035                 return ERR_INVALID_USER;
1036                 if(!is_a($target, "P10_User") && !is_a($target, "P10_Channel") && !(is_string($target) && ($target[0] == "#" || P10_User::getUserByNick($target))))
1037                 return ERR_INVALID_USER;
1038                 if(is_a($target, "P10_Channel"))
1039                 $targetStr = $target->getName();
1040                 else if(is_a($target, "P10_User"))
1041                 $targetStr = $target->getNumeric();
1042                 else if($target[0] == "#")
1043                 $targetStr = $target;
1044                 else
1045                 $targetStr = P10_User::getUserByNick($target)->getNumeric();
1046
1047                 if($targetStr[0] == "#") {
1048                         $channel = P10_Channel::getChannelByName($targetStr);
1049                         if($channel == null)
1050                         $channel = new P10_Channel($targetStr);
1051                         $modes = $channel->getModes()->setModes($modes, true);
1052                         if(($this->flags & self::FLAG_CONNECTED))
1053                         $this->send(($force ? "OM" : "M"), $user->getNumeric(), $targetStr, $modes);
1054                         if($this->eventHandler)
1055                         $this->eventHandler->event_chanmode(($force ? $this->server : $user), $channel, $modes);
1056                 } else {
1057                         $targetUser = P10_User::getUserByNum($targetStr);
1058                         if($targetUser->getServer() === $this->server) {
1059                                 //just do it :D
1060                                 $modes = $targetUser->getModes()->setModes($modes, true);
1061                                 if(($this->flags & self::FLAG_CONNECTED))
1062                                 $this->send("M", $targetUser->getNumeric(), $targetUser->getNick(), $modes);
1063                                 if($this->eventHandler)
1064                                 $this->eventHandler->event_usermode($targetUser, $modes);
1065                         } else {
1066                                 //SVSMODE
1067                                 if(($this->flags & self::FLAG_CONNECTED))
1068                                 $this->send("SM", $user->getNumeric(), $targetUser->getNumeric(), $modes);
1069                         }
1070                 }
1071         }
1072
1073         public function ctcp($user, $target, $command, $text) {
1074                 return $this->privmsg($user, $target, "\001".strtoupper($command)." ".$text."\001");
1075         }
1076
1077         public function ctcp_reply($user, $target, $command, $text) {
1078                 return $this->notice($user, $target, "\001".strtoupper($command)." ".$text."\001");
1079         }
1080
1081 }
1082
1083 ?>