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