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