implemented EventHandler
[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 setEventHandler(EventHandler $event_handler)
51  *     sets the EventHandlder
52  */
53 require_once("Client.class.php");
54 require_once("Numerics.class.php");
55 require_once("P10Formatter.class.php");
56 require_once("P10_Server.class.php");
57 require_once("P10_User.class.php");
58 require_once("P10_Channel.class.php");
59 require_once("P10_ModeSets.class.php");
60 require_once("EventHandler.interface.php");
61
62 class Uplink {
63         private $client;
64         private $settings = array();
65         private $server;
66         private $eventHandler = null;
67         
68         const FLAG_P10SESSION      = 0x0001; //connection is in P10 mode (server is connected)
69         const FLAG_SECURITY_QUIT   = 0x0002; //local connection abort because of security issues
70         const FLAG_NOT_CONNECTABLE = 0x0004; //remote server is not connectable
71         const FLAG_BURST_PENDING   = 0x0008; //we still have to burst
72         const FLAG_CONNECTED       = 0x0010; //connected and synced (ready)
73         const FLAG_GOT_PASS        = 0x0020; //got PASS from the remote Server
74         private $flags = 0;
75         
76         public function __construct() {
77                 $this->client = new Client();
78                 $this->setSetting("recv_timeout", 1000);
79         }
80         
81         public function initialize() {
82                 if($this->server) {
83                         trigger_error("Uplink already initialized.", E_USER_ERROR);
84                         return;
85                 }
86                 $self_numeric = $this->getSetting("numeric");
87                 $self_name = $this->getSetting("name");
88                 $self_description = $this->getSetting("description");
89                 if(!$self_numeric || !$self_name) {
90                         trigger_error("Server Settings missing.", E_USER_ERROR);
91                         return;
92                 }
93                 $this->server = new P10_Server($self_name, $self_numeric, null, time(), time(), $self_description);
94         }
95         
96         public function loop() {
97                 if($this->server == null) {
98                         trigger_error("Uplink not initialized.", E_USER_ERROR);
99                         return;
100                 }
101                 if(!$this->client->connected()) {
102                         if(($this->flags & self::FLAG_P10SESSION)) {
103                                 //Server got disconnected
104                                 $this->server->disconnectServer($this->eventHandler, true);
105                                 $this->flags &= ~self::FLAG_P10SESSION;
106                         }
107                         $host = $this->getSetting("host");
108                         $port = $this->getSetting("port");
109                         if($host == null || $port == null) {
110                                 trigger_error("Uplink Settings missing.", E_USER_ERROR);
111                                 return;
112                         }
113                         if(($this->flags & self::FLAG_SECURITY_QUIT) || ($this->flags & self::FLAG_NOT_CONNECTABLE)) {
114                                 sleep(1);
115                         }
116                         $state = $this->client->connect($host, $port, $this->getSetting("bind"), $this->getSetting("ssl"), $this->getSetting("recv_timeout"));
117                         if(!$state) {
118                                 usleep($this->getSetting("recv_timeout") / 1000);
119                                 $this->flags |= self::FLAG_NOT_CONNECTABLE;
120                                 return;
121                         }
122                         $this->flags = 0;
123                         $this->loginServer();
124                 }
125                 //try to receive new data from the Uplink
126                 $lines = $this->client->recv();
127                 if($lines == null) return;
128                 foreach($lines as $line) {
129                         $this->parseLine($line);
130                 }
131         }
132         
133         public function setUplinkHost($host, $port, $ssl = false, $bind = null) {
134                 $this->setSetting("host", $host);
135                 $this->setSetting("port", $port);
136                 $this->setSetting("ssl", $ssl);
137                 $this->setSetting("bind", $bind);
138         }
139         
140         public function setLoopTimeout($timeout) {
141                 $this->setSetting("recv_timeout", $timeout);
142         }
143         
144         public function setUplinkServer($numeric, $name, $password, $description) {
145                 $this->setSetting("numeric", Numerics::intToNum($numeric, 2));
146                 $this->setSetting("name", $name);
147                 $this->setSetting("password", $password);
148                 $this->setSetting("description", $description);
149         }
150         
151         public function setValidateServer($name, $password) {
152                 $this->setSetting("their_name", $name);
153                 $this->setSetting("their_password", $password);
154         }
155         
156         public function setEventHandler($event_handler) {
157                 if(!is_a($event_handler, "EventHandler")) {
158                         trigger_error((is_object($event_handler) ? get_class($event_handler) : gettype($event_handler))." is NOT a valid EventHandler.", E_USER_ERROR);
159                         return;
160                 }
161                 $this->eventHandler = $event_handler;
162         }
163         
164         private function setSetting($setting, $value) {
165                 $this->settings[$setting] = $value;
166         }
167         
168         private function getSetting($setting) {
169                 if(array_key_exists($setting, $this->settings)) {
170                         return $this->settings[$setting];
171                 } else {
172                         return null;
173                 }
174         }
175         
176         private function loginServer() {
177                 $password = $this->getSetting("password");
178                 $this->send("PASS", $password);
179                 $this->send("SERVER", $this->server->getName(), $this->server->getStartTime(), $this->server->getLinkTime(), $this->server->getNumeric(), $this->server->getDescription());
180         }
181         
182         private function parseLine($line) {
183                 $highExplode = explode(" :", $line, 2);
184                 $tokens = explode(" ", $highExplode[0]);
185                 if(count($highExplode) > 1)
186                         $tokens[] = $highExplode[1];
187                 $cmdPos = (($this->flags & self::FLAG_P10SESSION) ? 1 : 0);
188                 if($cmdPos == 1) $from = $tokens[0];
189                 else $from = null;
190                 $arguments = array_slice($tokens, $cmdPos + 1);
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                 //default
235                         default:
236                                 //unknown cmd
237                                 break;
238                 }
239         }
240         
241         private function send($command) {
242                 if(func_num_args() > 1) {
243                         $args = array_slice(func_get_args(), 1);
244                         $command = P10Formatter::formatCMD($this->getSetting("numeric"), $command, $args);
245                 } else {
246                         $command = P10Formatter::formatCMD($this->getSetting("numeric"), $command, array());
247                 }
248                 $this->client->send($command);
249         }
250         
251         /********************************************************************************************
252          *                                     INCOMING COMMANDS                                    *
253          ********************************************************************************************/
254         
255         private function recv_pass($from, $args) {
256                 $their_pass = $this->getSetting("their_password");
257                 if($their_pass) {
258                         if($args[0] != $their_pass) {
259                                 //security QUIT
260                                 $this->flags |= self::FLAG_SECURITY_QUIT;
261                                 $this->send("ERROR", "Incorrect password received.");
262                                 $this->client->disconnect();
263                                 return;
264                         }
265                         $this->flags |= self::FLAG_GOT_PASS;
266                 }
267         }
268         
269         private function recv_error($from, $args) {
270                 //we received an error - the socket is dead for us, now
271                 //maybe we want to log this, later
272                 $this->client->disconnect();
273         }
274         
275         private function recv_server($from, $args) {
276                 if($from == null) {
277                         //our uplink Server
278                         $their_name = $this->getSetting("their_name");
279                         if($their_name && $args[0] != $their_name) {
280                                 $this->flags |= self::FLAG_SECURITY_QUIT;
281                                 $this->send("ERROR", "Invalid Server name");
282                                 $this->client->disconnect();
283                                 return;
284                         }
285                         if($this->getSetting("their_password") && !($this->flags & self::FLAG_GOT_PASS)) {
286                                 $this->flags |= self::FLAG_SECURITY_QUIT;
287                                 $this->send("ERROR", "PASS missing.");
288                                 $this->client->disconnect();
289                                 return;
290                         }
291                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $this->server, $args[2], $args[3], $args[7]);
292                         $this->server->addServer($new_server);
293                         $this->flags |= self::FLAG_P10SESSION | self::FLAG_BURST_PENDING;
294                         if($this->eventHandler)
295                                 $this->eventHandler->event_server($new_server, !($this->flags & self::FLAG_CONNECTED));
296                 } else {
297                         //another server got a new slave server ^^
298                         $server = P10_Server::getServerByNum($from);
299                         if($server == null) {
300                                 trigger_error("Parent Server (".$from.") does not exist or was not found on recv_server.", E_USER_ERROR);
301                                 return;
302                         }
303                         $new_server = new P10_Server($args[0], substr($args[5],0,2), $server, $args[2], $args[3], $args[7]);
304                         $server->addServer($new_server);
305                         if($this->eventHandler)
306                                 $this->eventHandler->event_server($new_server, !($this->flags & self::FLAG_CONNECTED));
307                 }
308         }
309         
310         private function recv_ping($from, $args) {
311                 $this->send("Z", $args[0]); //simply PONG
312         }
313         
314         private function recv_nick($from, $args) {
315                 if(count($args) <= 2) {
316                         //Nick change
317                         $user = P10_User::getUserByNum($from);
318                         if($user == null) {
319                                 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);
320                                 return;
321                         }
322                         if($this->eventHandler)
323                                 $this->eventHandler->event_nick($user, $args[0]);
324                         $user->setNick($args[0]);
325                 } else {
326                         //New User
327                         $numeric = $args[count($args)-2];
328                         $nick = $args[0];
329                         $server = P10_Server::getServerByNum($from);
330                         if($server == null) {
331                                 trigger_error("Server (".$from.") the User (".$nick.") is coming from does not exist or was not found on recv_nick.", E_USER_ERROR);
332                                 return;
333                         }
334                         if(substr($numeric,0,2) != $from) {
335                                 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);
336                         }
337                         $connect_time = $args[2];
338                         $ident = $args[3];
339                         $host = $args[4];
340                         $modes = implode(" ",array_slice($args, 5, count($args)-8));
341                         $modes = new P10_UserModeSet($modes);
342                         $ip = Numerics::parseIP($args[count($args)-3]);
343                         $realname = $args[count($args)-1];
344                         $user = new P10_User($nick, $numeric, $server, $connect_time, $ident, $host, $ip, $realname, $modes);
345                         if($this->eventHandler)
346                                 $this->eventHandler->event_connect($user, !($this->flags & self::FLAG_CONNECTED));
347                 }
348         }
349         
350         private function recv_end_of_burst($from, $args) {
351                 if(($this->flags & self::FLAG_BURST_PENDING)) {
352                         $this->burst();
353                         $this->send("EA");
354                         $this->flags &= ~self::FLAG_BURST_PENDING;
355                 }
356         }
357         
358         private function recv_end_of_burst_ack($from, $args) {
359                 $this->flags |= self::FLAG_CONNECTED;
360         }
361         
362         private function recv_server_quit($from, $args) {
363                 $server = P10_Server::getServerByName($args[0]);
364                 if($server == null) {
365                         trigger_error("Server (".$args[0].") not found.", E_USER_ERROR);
366                         return;
367                 }
368                 $server->disconnectServer($this->eventHandler);
369         }
370         
371         private function recv_quit($from, $args) {
372                 $user = P10_User::getUserByNum($from);
373                 if($user == null) {
374                         trigger_error("Server tries to quit an user that does not exist or was not found on recv_quit.", E_USER_ERROR);
375                         return;
376                 }
377                 if($this->eventHandler)
378                         $this->eventHandler->event_quit($user, $args[1]);
379                 $user->quit($args[0]);
380         }
381         
382         private function recv_burst($from, $args) {
383                 $name = $args[0];
384                 $create_time = $args[1];
385                 $channel = P10_Channel::getChannelByName($name);
386                 if($channel == null)
387                         $channel = new P10_Channel($name);
388                 $channel->setCreateTime($create_time);
389                 $modes = $channel->getModes();
390                 $userstr = $args[count($args)-1];
391                 $modeparamcount = count($args)-3;
392                 if($userstr[0] == "%") {
393                         //ban list
394                         $banlist = explode(" ", substr($userstr, 1));
395                         foreach($banlist as $ban) {
396                                 //TODO: save bans
397                         }
398                         $userstr = $args[count($args)-2];
399                         $modeparamcount--;
400                 }
401                 if($userstr[0] == "+") { //MODE String
402                         $modeparamcount++;
403                         $userstr = "";
404                 }
405                 $users = explode(",",$userstr);
406                 $isop = false; $isvoice = false;
407                 foreach($users as $user) {
408                         $uexp = explode(":", $user);
409                         if(strlen($uexp[0]) != 5) {
410                                 trigger_error("burst parse error: '".$uexp[0]."' is not an user numeric.", E_USER_ERROR);
411                                 return;
412                         }
413                         if(count($uexp) > 1) {
414                                 $isop = false;
415                                 $isvoice = false;
416                                 for($i = 0; $i < strlen($uexp[1]); $i++) {
417                                         if($uexp[1][0] == "@") $isop = true;
418                                         if($uexp[1][0] == "+") $isvoice = true;
419                                 }
420                         }
421                         $user = P10_User::getUserByNum($uexp[0]);
422                         if($user == null) {
423                                 trigger_error("burst parse error: cant find User '".$uexp[0]."'.", E_USER_ERROR);
424                                 return;
425                         }
426                         $channel->burstUser($user, $isop, $isvoice);
427                         if($this->eventHandler)
428                                 $this->eventHandler->event_join($user, $channel, true);
429                 }
430                 $modes->parseModes(implode(array_slice($args, 2, $modeparamcount)));
431         }
432         
433         private function recv_join($from, $args) {
434                 $user = P10_User::getUserByNum($from);
435                 if($user == null) {
436                         trigger_error("Server tries to join an user that does not exist or was not found on recv_join.", E_USER_ERROR);
437                         return;
438                 }
439                 $channel = P10_Channel::getChannelByName($args[0]);
440                 if($channel == null)
441                         $channel = new P10_Channel($args[0]);
442                 $channel->joinUser($user);
443                 if($this->eventHandler)
444                         $this->eventHandler->event_join($user, $channel, false);
445         }
446         
447         private function recv_part($from, $args) {
448                 $user = P10_User::getUserByNum($from);
449                 if($user == null) {
450                         trigger_error("Server tries to part an user that does not exist or was not found on recv_join.", E_USER_ERROR);
451                         return;
452                 }
453                 $channel = P10_Channel::getChannelByName($args[0]);
454                 if($channel == null)
455                         $channel = new P10_Channel($args[0]);
456                 if($this->eventHandler)
457                         $this->eventHandler->event_part($user, $channel, $args[1]);
458                 $channel->partUser($user);
459         }
460         
461         /********************************************************************************************
462          *                                     SERVER FUNCTIONS                                     *
463          ********************************************************************************************/
464         
465         private function burst() {
466                 foreach($this->server->getUsers() as $user) {
467                         $nick = $user->getNick();
468                         $connect_time = $user->getConnectTime();
469                         $ident = $user->getIdent();
470                         $host = $user->getHost();
471                         $modes = $user->getModes()->getModeString();
472                         $ip = Numerics::numericFromIP($user->getIP());
473                         $numeric = $user->getNumeric();
474                         $realname = $user->getRealname();
475                         $this->send("N", $nick, $connect_time, $ident, $host, $modes, $ip, $numeric, $realname);
476                 }
477                 foreach(P10_Channel::getChannels() as $channel) {
478                         $sorted_users = array('ov' => array(), 'o' => array(), 'v' => array(), '-' => array());
479                         $local_users = false;
480                         foreach($channel->getUsers() as $user) {
481                                 if(substr($user->getNumeric(), 0, 2) != $this->server->getNumeric()) continue; //skip users that are not on the local server
482                                 $privs = $channel->getUserPrivs($user);
483                                 $strPrivs = "";
484                                 if(($privs & P10_Channel::USERPRIV_OPED)) $strPrivs .= "o";
485                                 if(($privs & P10_Channel::USERPRIV_VOICE)) $strPrivs .= "v";
486                                 if($strPrivs == "") $strPrivs = "-";
487                                 $local_users = true;
488                                 $sorted_users[$strPrivs][] = $user;
489                         }
490                         if(!$local_users) continue;
491                         $userStr = "";
492                         foreach($sorted_users['-'] as $user) {
493                                 if($userStr != "") $userStr.=",";
494                                 $userStr .= $user->getNumeric();
495                         }
496                         foreach($sorted_users['ov'] as $i => $user) {
497                                 if($userStr != "") $userStr.=",";
498                                 $userStr .= $user->getNumeric();
499                                 if($i == 0) $userStr .= ":ov";
500                         }
501                         foreach($sorted_users['o'] as $i => $user) {
502                                 if($userStr != "") $userStr.=",";
503                                 $userStr .= $user->getNumeric();
504                                 if($i == 0) $userStr .= ":o";
505                         }
506                         foreach($sorted_users['v'] as $i => $user) {
507                                 if($userStr != "") $userStr.=",";
508                                 $userStr .= $user->getNumeric();
509                                 if($i == 0) $userStr .= ":v";
510                         }
511                         $banString = "";
512                         //TODO: Build ban String
513                         $burstString = "";
514                         $modeString = $channel->getModes()->getModeString();
515                         if($modeString != "+") {
516                                 $burstString .= $modeString;
517                         }
518                         if($userStr != "") {
519                                 if($burstString != "") $burstString .= " ";
520                                 $burstString .= $userStr;
521                         }
522                         if($banString != "") {
523                                 if($burstString != "") $burstString .= " ";
524                                 $burstString .= ":%".$banString;
525                         }
526                         $this->send("B", $channel->getName(), $channel->getCreateTime(), $burstString);
527                 }
528                 $this->send("EB");
529         }
530         
531 }
532
533 ?>