fixed possible empty channel bursts
[PHP-P10.git] / Uplink / Uplink.class.php
1 <?php
2 /******************************* PHP-P10 v2 *****************************
3  * Copyright (C) 2011  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                 //default
257                         default:
258                                 //unknown cmd
259                                 if($this->eventHandler)
260                                         $this->eventHandler->event_unknown_cmd($from, strtoupper($tokens[$cmdPos]), $arguments);
261                                 break;
262                 }
263         }
264         
265         private function send($command) {
266                 if(func_num_args() > 1) {
267                         $args = array_slice(func_get_args(), 1);
268                         $command = P10Formatter::formatCMD($this->getSetting("numeric"), $command, $args);
269                 } else {
270                         $command = P10Formatter::formatCMD($this->getSetting("numeric"), $command, array());
271                 }
272                 $this->client->send($command);
273         }
274         
275         /********************************************************************************************
276          *                                     INCOMING COMMANDS                                    *
277          ********************************************************************************************/
278         
279         private function recv_pass($from, $args) {
280                 $their_pass = $this->getSetting("their_password");
281                 if($their_pass) {
282                         if($args[0] != $their_pass) {
283                                 //security QUIT
284                                 $this->flags |= self::FLAG_SECURITY_QUIT;
285                                 $this->send("ERROR", "Incorrect password received.");
286                                 $this->client->disconnect();
287                                 return;
288                         }
289                         $this->flags |= self::FLAG_GOT_PASS;
290                 }
291         }
292         
293         private function recv_error($from, $args) {
294                 //we received an error - the socket is dead for us, now
295                 //maybe we want to log this, later
296                 $this->client->disconnect();
297         }
298         
299         private function recv_server($from, $args) {
300                 if($from == null) {
301                         //our uplink Server
302                         $their_name = $this->getSetting("their_name");
303                         if($their_name && $args[0] != $their_name) {
304                                 $this->flags |= self::FLAG_SECURITY_QUIT;
305                                 $this->send("ERROR", "Invalid Server name");
306                                 $this->client->disconnect();
307                                 return;
308                         }
309                         if($this->getSetting("their_password") && !($this->flags & self::FLAG_GOT_PASS)) {
310                                 $this->flags |= self::FLAG_SECURITY_QUIT;
311                                 $this->send("ERROR", "PASS missing.");
312                                 $this->client->disconnect();
313                                 return;
314                         }
315                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $this->server, $args[2], $args[3], $args[7]);
316                         $this->server->addServer($new_server);
317                         $this->flags |= self::FLAG_P10SESSION | self::FLAG_BURST_PENDING;
318                         if($this->eventHandler)
319                                 $this->eventHandler->event_newserver($new_server, !($this->flags & self::FLAG_CONNECTED));
320                 } else {
321                         //another server got a new slave server ^^
322                         $server = P10_Server::getServerByNum($from);
323                         if($server == null) {
324                                 trigger_error("Parent Server (".$from.") does not exist or was not found on recv_server.", E_USER_ERROR);
325                                 return;
326                         }
327                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $server, $args[2], $args[3], $args[7]);
328                         $server->addServer($new_server);
329                         if($this->eventHandler)
330                                 $this->eventHandler->event_newserver($new_server, !($this->flags & self::FLAG_CONNECTED));
331                 }
332         }
333         
334         private function recv_ping($from, $args) {
335                 $this->send("Z", $args[0]); //simply PONG
336                 P10_Channel::recheckAllChannels();
337         }
338         
339         private function recv_nick($from, $args) {
340                 if(count($args) <= 2) {
341                         //Nick change
342                         $user = P10_User::getUserByNum($from);
343                         if($user == null) {
344                                 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);
345                                 return;
346                         }
347                         if($this->eventHandler)
348                                 $this->eventHandler->event_nick($user, $args[0]);
349                         $user->setNick($args[0]);
350                 } else {
351                         //New User
352                         $numeric = $args[count($args)-2];
353                         $nick = $args[0];
354                         $server = P10_Server::getServerByNum($from);
355                         if($server == null) {
356                                 trigger_error("Server (".$from.") the User (".$nick.") is coming from does not exist or was not found on recv_nick.", E_USER_ERROR);
357                                 return;
358                         }
359                         if(substr($numeric,0,2) != $from) {
360                                 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);
361                         }
362                         $connect_time = $args[2];
363                         $ident = $args[3];
364                         $host = $args[4];
365                         $modes = implode(" ",array_slice($args, 5, count($args)-8));
366                         $modes = new P10_UserModeSet($modes);
367                         $ip = new IPAddr($args[count($args)-3]);
368                         $realname = $args[count($args)-1];
369                         $user = new P10_User($nick, $numeric, $server, $connect_time, $ident, $host, $ip, $realname, $modes);
370                         if($this->eventHandler)
371                                 $this->eventHandler->event_connect($user, !($this->flags & self::FLAG_CONNECTED));
372                 }
373         }
374         
375         private function recv_end_of_burst($from, $args) {
376                 if(($this->flags & self::FLAG_BURST_PENDING)) {
377                         $this->burst();
378                         $this->send("EA");
379                         $this->flags &= ~self::FLAG_BURST_PENDING;
380                 }
381         }
382         
383         private function recv_end_of_burst_ack($from, $args) {
384                 $this->flags |= self::FLAG_CONNECTED;
385         }
386         
387         private function recv_server_quit($from, $args) {
388                 $server = P10_Server::getServerByName($args[0]);
389                 if($server == null) {
390                         trigger_error("Server (".$args[0].") not found.", E_USER_ERROR);
391                         return;
392                 }
393                 $server->disconnectServer($this->eventHandler);
394         }
395         
396         private function recv_quit($from, $args) {
397                 $user = P10_User::getUserByNum($from);
398                 if($user == null) {
399                         trigger_error("Server tries to quit an user that does not exist or was not found on recv_quit.", E_USER_ERROR);
400                         return;
401                 }
402                 if($this->eventHandler)
403                         $this->eventHandler->event_quit($user, $args[0]);
404                 $user->quit($args[0]);
405         }
406         
407         private function recv_burst($from, $args) {
408                 $name = $args[0];
409                 $create_time = $args[1];
410         if(count($args) == 2) {
411             //we've got an empty channel without any modes set???  dead channel!
412             return;
413         }
414                 $channel = P10_Channel::getChannelByName($name);
415                 if($channel == null)
416                         $channel = new P10_Channel($name);
417                 $channel->setCreateTime($create_time);
418                 $modes = $channel->getModes();
419                 $userstr = $args[count($args)-1];
420                 if($userstr[0] == "%") {
421                         //ban list
422                         $banlist = explode(" ", substr($userstr, 1));
423                         foreach($banlist as $ban) {
424                                 //TODO: save bans
425                         }
426                         $userstr = $args[count($args)-2];
427                 }
428                 if($userstr[0] == "+") { //MODE String
429                         $userstr = "";
430                 }
431                 $users = explode(",",$userstr);
432                 $isop = false; $isvoice = false;
433                 foreach($users as $user) {
434                         if($user == "") continue;
435                         $uexp = explode(":", $user);
436                         if(strlen($uexp[0]) != 5) {
437                                 trigger_error("burst parse error: '".$uexp[0]."' is not an user numeric.", E_USER_WARNING);
438                                 break;
439                         }
440                         if(count($uexp) > 1) {
441                                 $isop = false;
442                                 $isvoice = false;
443                                 for($i = 0; $i < strlen($uexp[1]); $i++) {
444                                         if($uexp[1][0] == "@") $isop = true;
445                                         if($uexp[1][0] == "+") $isvoice = true;
446                                 }
447                         }
448                         $user = P10_User::getUserByNum($uexp[0]);
449                         if($user == null) {
450                                 trigger_error("burst parse error: cant find User '".$uexp[0]."'.", E_USER_ERROR);
451                                 return;
452                         }
453                         $channel->burstUser($user, $isop, $isvoice);
454                         if($this->eventHandler)
455                                 $this->eventHandler->event_join($user, $channel, true);
456                 }
457                 $modes->parseModes(implode(" ", array_slice($args, 2)));
458         }
459         
460         private function recv_join($from, $args) {
461                 $user = P10_User::getUserByNum($from);
462                 if($user == null) {
463                         trigger_error("Server tries to join an user that does not exist or was not found on recv_join.", E_USER_ERROR);
464                         return;
465                 }
466                 $channel = P10_Channel::getChannelByName($args[0]);
467                 if($channel == null)
468                         $channel = new P10_Channel($args[0]);
469                 $channel->joinUser($user);
470                 if($this->eventHandler)
471                         $this->eventHandler->event_join($user, $channel, false);
472         }
473         
474         private function recv_part($from, $args) {
475                 $user = P10_User::getUserByNum($from);
476                 if($user == null) {
477                         trigger_error("Server tries to part an user that does not exist or was not found on recv_join.", E_USER_ERROR);
478                         return;
479                 }
480                 $channel = P10_Channel::getChannelByName($args[0]);
481                 if($channel == null)
482                         $channel = new P10_Channel($args[0]);
483                 if($this->eventHandler)
484                         $this->eventHandler->event_part($user, $channel, $args[1]);
485                 $channel->partUser($user);
486         }
487         
488         private function recv_kick($from, $args) {
489                 $user = P10_User::getUserByNum($from);
490                 if($user == null) {
491                         trigger_error("An unknown user tries to kick another user on recv_kick.", E_USER_ERROR);
492                         return;
493                 }
494                 $channel = P10_Channel::getChannelByName($args[0]);
495                 if($channel == null)
496                         $channel = new P10_Channel($args[0]);
497                 $target = P10_User::getUserByNum($args[1]);
498                 if($target == null) {
499                         trigger_error("Someone tries to kick an user that does not exist or was not found on recv_kick.", E_USER_ERROR);
500                         return;
501                 }
502                 if($this->eventHandler)
503                         $this->eventHandler->event_kick($user, $target, $channel, $args[1]);
504                 $channel->partUser($user);
505         }
506         
507         private function recv_kill($from, $args) {
508                 $user = P10_User::getUserByNum($args[0]);
509                 if($user == null) {
510                         trigger_error("Server tries to kill an user that does not exist or was not found on recv_quit.", E_USER_ERROR);
511                         return;
512                 }
513                 if($this->eventHandler)
514                         $this->eventHandler->event_quit($user, "Killed (".$args[1].")");
515                 $user->quit($args[1]);
516         }
517         
518         private function recv_privmsg($from, $args) {
519                 $user = P10_User::getUserByNum($from);
520                 if($user == null) {
521                         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);
522                         return;
523                 }
524                 if($this->eventHandler) {
525                         if($args[0][0] == "#") {
526                                 $channel = P10_Channel::getChannelByName($args[0]);
527                                 if($channel == null)
528                                         $channel = new P10_Channel($args[0]);
529                                 if(strlen($args[1]) > 0 && $args[1][0] == "\001") {
530                                         //ctcp
531                                         $args[1] = substr($args[1],1);
532                                         if($args[1][strlen($args[1])-1] == "\001")
533                                                 $args[1] = substr($args[1],0,-1);
534                                         $ctcpexp = explode(" ",$args[1],2);
535                                         $this->eventHandler->event_chanctcp($user, $channel, strtoupper($ctcpexp[0]), (count($ctcpexp) > 1 ? $ctcpexp[1] : null));
536                                 } else
537                                         $this->eventHandler->event_chanmessage($user, $channel, $args[1]);
538                         } else if($args[0][0] == "$") {
539                                 //"multicast"
540                                 $this->eventHandler->event_privmessage($user, NULL, $args[1]);
541                         } else {
542                                 $targetUser = P10_User::getUserByNum($args[0]);
543                                 if($targetUser == null) {
544                                         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);
545                                         return;
546                                 }
547                                 if(strlen($args[1]) > 0 && $args[1][0] == "\001") {
548                                         //ctcp
549                                         $args[1] = substr($args[1],1);
550                                         if($args[1][strlen($args[1])-1] == "\001")
551                                                 $args[1] = substr($args[1],0,-1);
552                                         $ctcpexp = explode(" ",$args[1],2);
553                                         $this->eventHandler->event_privctcp($user, $targetUser, strtoupper($ctcpexp[0]), (count($ctcpexp) > 1 ? $ctcpexp[1] : null));
554                                 } else
555                                         $this->eventHandler->event_privmessage($user, $targetUser, $args[1]);
556                         }
557                 }
558         }
559         
560         private function recv_notice($from, $args) {
561                 $user = P10_User::getUserByNum($from);
562                 if($user == null) {
563                         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);
564                         return;
565                 }
566                 if($this->eventHandler) {
567                         if($args[0][0] == "#") {
568                                 $channel = P10_Channel::getChannelByName($args[0]);
569                                 if($channel == null)
570                                         $channel = new P10_Channel($args[0]);
571                                 if(strlen($args[1]) > 0 && $args[1][0] == "\001") {
572                                         //ctcp
573                                         $args[1] = substr($args[1],1);
574                                         if($args[1][strlen($args[1])-1] == "\001")
575                                                 $args[1] = substr($args[1],0,-1);
576                                         $ctcpexp = explode(" ",$args[1],2);
577                                         $this->eventHandler->event_chanctcpreply($user, $channel, strtoupper($ctcpexp[0]), (count($ctcpexp) > 1 ? $ctcpexp[1] : null));
578                                 } else
579                                         $this->eventHandler->event_channotice($user, $channel, $args[1]);
580                         } else if($args[0][0] == "$") {
581                                 //"multicast"
582                                 $this->eventHandler->event_privnotice($user, NULL, $args[1]);
583                         } else {
584                                 $targetUser = P10_User::getUserByNum($args[0]);
585                                 if($targetUser == null) {
586                                         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);
587                                         return;
588                                 }
589                                 if(strlen($args[1]) > 0 && $args[1][0] == "\001") {
590                                         //ctcp
591                                         $args[1] = substr($args[1],1);
592                                         if($args[1][strlen($args[1])-1] == "\001")
593                                                 $args[1] = substr($args[1],0,-1);
594                                         $ctcpexp = explode(" ",$args[1],2);
595                                         $this->eventHandler->event_privctcpreply($user, $targetUser, strtoupper($ctcpexp[0]), (count($ctcpexp) > 1 ? $ctcpexp[1] : null));
596                                 } else
597                                         $this->eventHandler->event_privnotice($user, $targetUser, $args[1]);
598                         }
599                 }
600         }
601         
602         private function recv_whois($from, $args) {
603                 /* [get] ACAAF W AX :NetworkServ */
604                 $fromUser = P10_User::getUserByNum($from);
605                 if($fromUser == null) {
606                         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);
607                         return;
608                 }
609                 $users=explode(",",$args[1]);
610                 foreach($users as $nick) {
611                         $user = P10_User::getUserByNick($nick);
612                         if(!$user) {
613                                 $this->send("401", $from, $nick);
614                                 continue;
615                         }
616                         $nick = $user->getNick();
617                         $ident = $user->getIdent();
618                         $hostmask = $user->getHost();
619                         $modes = $user->getModes();
620                         if($modes->hasMode('x')) {
621                                 if(($fakehost = $modes->hasMode('f'))) {
622                                         $hostmask = $fakehost;
623                                 } elseif(($account = $modes->hasMode('r'))) {
624                                         $hostmask = $account.".".$this->getSetting("his_usermask");
625                                 }
626                         }
627                         $realname = $user->getRealname();
628                         $this->send("311", $from , $nick, $ident, $hostmask, $realname);
629                         if(((!$modes->hasMode('n') && !$modes->hasMode('k')) || $from == $user->getNumeric()) && count($user->getChannels()) != 0) {
630                                 $channels = "";
631                                 foreach($user->getChannels() as $channel) {
632                                         $cmodes = $channel->getModes();
633                                         $privs = $channel->getUserPrivs($user);
634                                         if($cmodes->hasMode("s") && !$fromUser->isOnChannel($channel) && $from != $user->getNumeric()) continue;
635                                         if($cmodes->hasMode("u") && ($privs & (P10_Channel::USERPRIV_OPED | P10_Channel::USERPRIV_VOICE)) == 0 && $from != $user->getNumeric()) continue;
636                                         $chanstr = ($channels == "" ? "" : " ");
637                                         $prefix = "";
638                                         if(($privs & P10_Channel::USERPRIV_OPED)) {
639                                                 $prefix = "@";
640                                         } else if(($privs & P10_Channel::USERPRIV_VOICE)) {
641                                                 $prefix = "+";
642                                         }
643                                         $chanstr .= $prefix.$channel->getName();
644                                         if(strlen($channels) + strlen($chanstr) > 450) {
645                                                 $this->send("319", $from, $nick, $channels);
646                                                 $channels = $prefix.$channel->getName();
647                                         }
648                                 }
649                                 if($channels != "") {
650                                         $this->send("319", $from, $nick, $channels);
651                                 }
652                         }
653                         if($fromUser->getModes()->hasMode("o") || $from == $user->getNumeric() || !$this->getSetting("his_name")) {
654                                 $this->send("312", $from, $nick, $user->getServer()->getName(), $user->getServer()->getDescription());
655                         } else {
656                                 $this->send("312", $from, $nick, $this->getSetting("his_name"), $this->getSetting("his_desc"));
657                         }
658                         if($modes->hasMode("o") && (!$modes->hasMode("H") || $fromUser->getModes()->hasMode("o"))) {
659                                 if($modes->hasMode("S")) {
660                                         if($modes->hasMode("D"))
661                                                 $this->send("313", $from, $nick, "is a Network Service");
662                                         else
663                                                 $this->send("313", $from, $nick, "is an illegal Network Service - HACKER!");
664                                 } else
665                                         $this->send("313", $from, $nick, "is an IRC Operator");
666                         }
667                         if(($auth = $modes->hasMode("r"))) {
668                                 $this->send("330", $from, $nick, $auth);
669                         }
670                 }
671                 $this->send("318", $from, $args[1]);
672         }
673         
674         private function recv_away($from, $args) {
675                 $user = P10_User::getUserByNum($from);
676                 if($user == null) {
677                         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);
678                         return;
679                 }
680                 if(count($args) > 0) {
681                         $user->setAway($args[0]);
682                         if($this->eventHandler)
683                                 $this->eventHandler->event_away($user, $args[0]);
684                 } else {
685                         $user->setAway(null);
686                         if($this->eventHandler)
687                                 $this->eventHandler->event_away($user, null);
688                 }
689         }
690         
691         private function recv_mode($from, $args) {
692                 $user = P10_User::getUserByNum($from);
693                 if($user == null) {
694                         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);
695                         return;
696                 }
697                 $modes = implode(" ",array_slice($args,1));
698                 if($args[0][0] == "#") {
699                         $channel = P10_Channel::getChannelByName($args[0]);
700                         if($channel == null)
701                                 $channel = new P10_Channel($args[0]);
702                         $channel->getModes()->setModes($modes);
703                         if($this->eventHandler)
704                                 $this->eventHandler->event_chanmode($user, $channel, $modes);
705                 } else {
706                         $targetUser = P10_User::getUserByNick($args[0]);
707                         if($targetUser == null) {
708                                 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);
709                                 return;
710                         }
711                         $targetUser->getModes()->setModes($modes);
712                         if($this->eventHandler)
713                                 $this->eventHandler->event_usermode($targetUser, $modes);
714                 }
715         }
716         
717         /********************************************************************************************
718          *                                     SERVER FUNCTIONS                                     *
719          ********************************************************************************************/
720         
721         private function burst() {
722                 foreach($this->server->getUsers() as $user) {
723                         $nick = $user->getNick();
724                         $connect_time = $user->getConnectTime();
725                         $ident = $user->getIdent();
726                         $host = $user->getHost();
727                         $modes = $user->getModes()->getModeString();
728                         $ip = $user->getIP()->getNumeric();
729                         $numeric = $user->getNumeric();
730                         $realname = $user->getRealname();
731                         $this->send("N", $nick, $connect_time, $ident, $host, $modes, $ip, $numeric, $realname);
732                 }
733                 foreach(P10_Channel::getChannels() as $channel) {
734                         $sorted_users = array('ov' => array(), 'o' => array(), 'v' => array(), '-' => array());
735                         $local_users = false;
736                         foreach($channel->getUsers() as $user) {
737                                 if(substr($user->getNumeric(), 0, 2) != $this->server->getNumeric()) continue; //skip users that are not on the local server
738                                 $privs = $channel->getUserPrivs($user);
739                                 $strPrivs = "";
740                                 if(($privs & P10_Channel::USERPRIV_OPED)) $strPrivs .= "o";
741                                 if(($privs & P10_Channel::USERPRIV_VOICE)) $strPrivs .= "v";
742                                 if($strPrivs == "") $strPrivs = "-";
743                                 $local_users = true;
744                                 $sorted_users[$strPrivs][] = $user;
745                         }
746                         if(!$local_users) continue;
747                         $userStr = "";
748                         foreach($sorted_users['-'] as $user) {
749                                 if($userStr != "") $userStr.=",";
750                                 $userStr .= $user->getNumeric();
751                         }
752                         foreach($sorted_users['ov'] as $i => $user) {
753                                 if($userStr != "") $userStr.=",";
754                                 $userStr .= $user->getNumeric();
755                                 if($i == 0) $userStr .= ":ov";
756                         }
757                         foreach($sorted_users['o'] as $i => $user) {
758                                 if($userStr != "") $userStr.=",";
759                                 $userStr .= $user->getNumeric();
760                                 if($i == 0) $userStr .= ":o";
761                         }
762                         foreach($sorted_users['v'] as $i => $user) {
763                                 if($userStr != "") $userStr.=",";
764                                 $userStr .= $user->getNumeric();
765                                 if($i == 0) $userStr .= ":v";
766                         }
767                         $banString = "";
768                         //TODO: Build ban String
769                         $burstString = "";
770                         $modeString = $channel->getModes()->getModeString();
771                         if($modeString != "+") {
772                                 $burstString .= $modeString;
773                         }
774                         if($userStr != "") {
775                                 if($burstString != "") $burstString .= " ";
776                                 $burstString .= $userStr;
777                         }
778                         if($banString != "") {
779                                 if($burstString != "") $burstString .= " ";
780                                 $burstString .= ":%".$banString;
781                         }
782                         $this->send("B", $channel->getName(), $channel->getCreateTime(), $burstString);
783                 }
784                 $this->send("EB");
785         }
786         
787         /********************************************************************************************
788          *                                    LOCAL USER FUNCTIONS                                  *
789          ********************************************************************************************/
790         
791         public function addUser($nick, $ident, $host, $ip, $modes, $realname) {
792                 $user = P10_User::getUserByNick($nick);
793                 if($user != null) return ERR_NICK_IN_USE;
794                 $numeric = substr($this->server->getNumeric(),0,2).Numerics::intToNum($this->last_local_numeric, 3);
795                 while(P10_User::getUserByNum($numeric)) {
796                         $this->last_local_numeric++;
797                         $numeric = substr($this->server->getNumeric(),0,2).Numerics::intToNum($this->last_local_numeric, 3);
798                 }
799                 $this->last_local_numeric++;
800                 $modes = new P10_UserModeSet($modes);
801                 $ip = new IPAddr($ip);
802                 $user = new P10_User($nick, $numeric, $this->server, time(), $ident, $host, $ip, $realname, $modes);
803                 if(($this->flags & self::FLAG_CONNECTED)) {
804                         $ip = $user->getIP()->getNumeric();
805                         $this->send("N", $nick, $user->getConnectTime(), $ident, $host, $user->getModes()->getModeString(), $ip, $numeric, $realname);
806                 }
807                 return $user;
808         }
809         
810         public function delUser($user, $reason) {
811                 if(!is_a($user, "P10_User")) return ERR_INVALID_USER;
812                 if($user->getServer() === $this->server) {
813                         //local user (QUIT)
814                         $user->quit($reason);
815                         if(($this->flags & self::FLAG_CONNECTED)) 
816                                 $this->send("Q", $user->getNumeric(), $reason);
817                 } else {
818                         //remote user (KILL)
819                         if(!($this->flags & self::FLAG_CONNECTED)) 
820                                 return ERR_NOT_CONNECTED;
821                         if($this->eventHandler)
822                                 $this->eventHandler->event_quit($user, "Killed (".$reason.")");
823                         $user->quit("Killed (".$reason.")");
824                         $name = ($this->getSetting('his_name') ? $this->getSetting('his_name') : $this->getSetting('name'));
825
826                         $this->send("D", $user->getNumeric(), $name, $reason);
827                 }
828         }
829         
830         public function join($user, $chanName, $privs = 0) {
831                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
832                         return ERR_INVALID_USER;
833                 if($chanName[0] != "#")
834                         return ERR_INVALID_CHANNAME;
835                 $channel = P10_Channel::getChannelByName($chanName);
836                 if($channel == null)
837                         $channel = new P10_Channel($chanName);
838                 $channel->joinUser($user);
839                 if(($this->flags & self::FLAG_CONNECTED))
840                         $this->send("J", $user->getNumeric(), $chanName, time(), 0);
841                 if($privs != 0) {
842                         $channel->setUserPrivs($user, $privs);
843                         if(($this->flags & self::FLAG_CONNECTED)) {
844                                 $modestr = "+".(($privs & P10_Channel::USERPRIV_OPED) ? "o" : "").(($privs & P10_Channel::USERPRIV_VOICE) ? "v" : "");
845                                 $modestr .= (($privs & P10_Channel::USERPRIV_OPED) ? " ".$user->getNumeric() : "");
846                                 $modestr .= (($privs & P10_Channel::USERPRIV_VOICE) ? " ".$user->getNumeric() : "");
847                                 $this->send("OM", $user->getNumeric(), $chanName, $modestr);
848                         }
849                 }
850                 if($this->eventHandler)
851                         $this->eventHandler->event_join($user, $channel, false);
852         }
853         
854         public function part($user, $chanName, $reason) {
855                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
856                         return ERR_INVALID_USER;
857                 if(!((is_string($chanName) && $chanName[0] == "#") || is_a($chanName, "P10_Channel")))
858                         return ERR_INVALID_CHANNAME;
859                 if(is_a($chanName, "P10_Channel"))
860                         $channel = $chanName;
861                 else
862                         $channel = P10_Channel::getChannelByName($chanName);
863                 if($channel == null)
864                         $channel = new P10_Channel($chanName);
865                 if(!$user->isOnChannel($channel)) 
866                         return ERR_NOT_ON_CHANNEL;
867                 if($this->eventHandler)
868                         $this->eventHandler->event_part($user, $channel, $reason);
869                 $channel->partUser($user, $reason);
870                 if(($this->flags & self::FLAG_CONNECTED))
871                         $this->send("L", $user->getNumeric(), $chanName, $reason);
872         }
873         
874         public function kick($user, $target, $chanName, $reason) {
875                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
876                         return ERR_INVALID_USER;
877                 if(!is_a($target, "P10_User"))
878                         return ERR_INVALID_USER;
879                 if(!((is_string($chanName) && $chanName[0] == "#") || is_a($chanName, "P10_Channel")))
880                         return ERR_INVALID_CHANNAME;
881                 if(is_a($chanName, "P10_Channel"))
882                         $channel = $chanName;
883                 else
884                         $channel = P10_Channel::getChannelByName($chanName);
885                 if($channel == null)
886                         $channel = new P10_Channel($chanName);
887                 if(!$target->isOnChannel($channel)) 
888                         return ERR_NOT_ON_CHANNEL;
889                 if($this->eventHandler)
890                         $this->eventHandler->event_kick($user, $target, $channel, $reason);
891                 $channel->partUser($target, $reason);
892                 if(($this->flags & self::FLAG_CONNECTED))
893                         $this->send("K", $user->getNumeric(), $chanName, $target->getNumeric(), $reason);
894         }
895         
896         public function privmsg($user, $target, $message) {
897                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
898                         return ERR_INVALID_USER;
899                 if(!is_a($target, "P10_User") && !is_a($target, "P10_Channel") && !(is_string($target) && ($target[0] == "#" || P10_User::getUserByNick($target))))
900                         return ERR_INVALID_USER;
901                 if(is_a($target, "P10_Channel"))
902                         $targetStr = $target->getName();
903                 else if(is_a($target, "P10_User"))
904                         $targetStr = $target->getNumeric();
905                 else if($target[0] == "#")
906                         $targetStr = $target;
907                 else
908                         $targetStr = P10_User::getUserByNick($target)->getNumeric();
909                 
910                 if($this->eventHandler) {
911                         if($targetStr[0] == "#") {
912                                 $channel = P10_Channel::getChannelByName($targetStr);
913                                 if($channel == null)
914                                         $channel = new P10_Channel($targetStr);
915                                 $this->eventHandler->event_chanmessage($user, $channel, $message);
916                         } else {
917                                 $targetUser = P10_User::getUserByNum($targetStr);
918                                 $this->eventHandler->event_privmessage($user, $targetUser, $message);
919                         }
920                 }
921                 if(($this->flags & self::FLAG_CONNECTED))
922                         $this->send("P", $user->getNumeric(), $targetStr, $message);
923         }
924         
925         public function notice($user, $target, $message) {
926                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
927                         return ERR_INVALID_USER;
928                 if(!is_a($target, "P10_User") && !is_a($target, "P10_Channel") && !(is_string($target) && ($target[0] == "#" || P10_User::getUserByNick($target))))
929                         return ERR_INVALID_USER;
930                 if(is_a($target, "P10_Channel"))
931                         $targetStr = $target->getName();
932                 else if(is_a($target, "P10_User"))
933                         $targetStr = $target->getNumeric();
934                 else if($target[0] == "#")
935                         $targetStr = $target;
936                 else
937                         $targetStr = P10_User::getUserByNick($target)->getNumeric();
938                 
939                 if($this->eventHandler) {
940                         if($targetStr[0] == "#") {
941                                 $channel = P10_Channel::getChannelByName($targetStr);
942                                 if($channel == null)
943                                         $channel = new P10_Channel($targetStr);
944                                 $this->eventHandler->event_channotice($user, $channel, $message);
945                         } else {
946                                 $targetUser = P10_User::getUserByNum($targetStr);
947                                 $this->eventHandler->event_privnotice($user, $targetUser, $message);
948                         }
949                 }
950                 if(($this->flags & self::FLAG_CONNECTED))
951                         $this->send("O", $user->getNumeric(), $targetStr, $message);
952         }
953         
954         public function mode($user, $target, $modes, $force = false) {
955                 if(!is_a($user, "P10_User") || !($user->getServer() === $this->server))
956                         return ERR_INVALID_USER;
957                 if(!is_a($target, "P10_User") && !is_a($target, "P10_Channel") && !(is_string($target) && ($target[0] == "#" || P10_User::getUserByNick($target))))
958                         return ERR_INVALID_USER;
959                 if(is_a($target, "P10_Channel"))
960                         $targetStr = $target->getName();
961                 else if(is_a($target, "P10_User"))
962                         $targetStr = $target->getNumeric();
963                 else if($target[0] == "#")
964                         $targetStr = $target;
965                 else
966                         $targetStr = P10_User::getUserByNick($target)->getNumeric();
967                 
968                 if($targetStr[0] == "#") {
969                         $channel = P10_Channel::getChannelByName($targetStr);
970                         if($channel == null)
971                                 $channel = new P10_Channel($targetStr);
972                         $modes = $channel->getModes()->setModes($modes, true);
973                         if(($this->flags & self::FLAG_CONNECTED))
974                                 $this->send(($force ? "OM" : "M"), $user->getNumeric(), $targetStr, $modes);
975                         if($this->eventHandler)
976                                 $this->eventHandler->event_chanmode(($force ? $this->server : $user), $channel, $modes);
977                 } else {
978                         $targetUser = P10_User::getUserByNum($targetStr);
979                         if($targetUser->getServer() === $this->server) {
980                                 //just do it :D
981                                 $modes = $targetUser->getModes()->setModes($modes, true);
982                                 if(($this->flags & self::FLAG_CONNECTED))
983                                         $this->send("M", $targetUser->getNumeric(), $targetUser->getNick(), $modes);
984                                 if($this->eventHandler)
985                                         $this->eventHandler->event_usermode($targetUser, $modes);
986                         } else {
987                                 //SVSMODE
988                                 if(($this->flags & self::FLAG_CONNECTED))
989                                         $this->send("SM", $user->getNumeric(), $targetUser->getNumeric(), $modes);
990                         }
991                 }
992         }
993         
994         public function ctcp($user, $target, $command, $text) {
995                 return $this->privmsg($user, $target, "\001".strtoupper($command)." ".$text."\001");
996         }
997         
998         public function ctcp_reply($user, $target, $command, $text) {
999                 return $this->notice($user, $target, "\001".strtoupper($command)." ".$text."\001");
1000         }
1001         
1002 }
1003
1004 ?>