From ca43ae48638d5aabf11915281e1101876ad52800 Mon Sep 17 00:00:00 2001 From: xrogaan Date: Wed, 9 Jul 2008 09:37:43 +0200 Subject: [PATCH] Add some comments and the disconnect stuff. Remove old lib. --- sources/IRCMain/Adapter.php | 84 ++++++- sources/main-class.inc.php | 559 -------------------------------------------- 2 files changed, 78 insertions(+), 565 deletions(-) delete mode 100644 sources/main-class.inc.php diff --git a/sources/IRCMain/Adapter.php b/sources/IRCMain/Adapter.php index 98f6f85..5d85cb3 100644 --- a/sources/IRCMain/Adapter.php +++ b/sources/IRCMain/Adapter.php @@ -141,6 +141,14 @@ abstract class IRCMain_Adapter { $this->put('JOIN '.$channel); echo "Join channel $channel ...\n"; } + + final protected function nick_change() { + echo "New nick : ".self::$myBotName."\n"; + if ($this->put('NICK :'.self::$myBotName)) { + return true; + } + return false; + } public function newNick($new=false) { switch ($new) { @@ -188,7 +196,14 @@ abstract class IRCMain_Adapter { self::put('PRIVMSG '.$to.' :'.$message."\n"); } - public function mprivmsg($to,$messages,$interval=650000) { + /** + * Multi message to send. + * + * @param string $to The reveiver + * @param array $messages The messages + * @param int $interval Delay execution in microseconds + */ + public function mprivmsg($to,array $messages,$interval=650000) { if (is_array($messages)) { foreach ($messages as $msg) { $this->privmsg($to,$msg); @@ -197,6 +212,13 @@ abstract class IRCMain_Adapter { } } + /** + * Send data to server. + * Return false if it fail + * + * @param string $data Raw data to send + * @return boolean + */ public function put($data) { if (!is_resource($this->_socket)) { throw new Exception('Connection lost...',1); @@ -205,7 +227,7 @@ abstract class IRCMain_Adapter { echo debug() ? 'core::put() -> ' . $data . "\n" : ''; - $ok = socket_write($this->_socket, $data ."\n"); + $ok = socket_write($this->_socket, $data . "\n"); if ($ok) { return true; } else { @@ -215,10 +237,10 @@ abstract class IRCMain_Adapter { return true; } - public function colors($msg,$text,$background=false) { - $color_tag = chr(3); - $first = ($background)?$color_tag.$text.','.$background:$color_tag.$text; - return $first.$msg.$color_tag; + public function colors($msg,$colorText,$colorBackground=false) { + $colorTag = chr(3); + $first = ($background) ? $colorTag . $colorText . ',' . $colorBackground : $colorTag . $colorText; + return $first.$msg.$colorTag; } public function bold($msg) { @@ -237,19 +259,69 @@ abstract class IRCMain_Adapter { return chr(31).$msg.chr(31); } + /** + * Return an array for multilines paragraphe + * + * @param string $msg Message + * @return array + */ public function paragraphe($msg) { return explode("\n",$msg); } + /** + * Return the nickname of the bot + * + * @return string + */ public function getBotName() { return self::getConfig('nick'); } + public function restart() { + if ($this->auth) { + echo 'Restart...'."\n"; + $this->disconnect('Restarting, please wait ...'); + sleep(5); + throw new Exception('Restart...',1); + } else { + $this->privmsg($this->msg_info['from'],"Vous n'etes pas authentifie."); + } + } + + public function quit() { + if ($this->auth) { + $this->disconnect(); + throw new Exception('Quit from',3); + } else { + $this->privmsg($this->msg_info['from'],"Vous n'etes pas authentifie."); + } + } + + public function disconnect($msg='EOL ;') { + //$this->plugins->unload_plugin('_all'); + echo "core::disconnect() -> Closing Link..."; + if (is_resource($this->_socket)) { + if ($this->put('QUIT :'.$msg)) { + $this->connected = false; + socket_close($this->_socket); + } + echo "\t\t\tdone.\n"; + } else { + echo "\t\t\tError.\n"; + echo "core::disconnect() -> Connection already breack down.\n"; + } + return true; + } + function __destruct() { if (is_resource($this->_socket)) { + echo "Error occured."; if ($this->put('QUIT :Error occured')) { socket_close($this->_socket); } + } else { + echo "\n\nAll process shut down, bye."; } } } diff --git a/sources/main-class.inc.php b/sources/main-class.inc.php deleted file mode 100644 index a64f93c..0000000 --- a/sources/main-class.inc.php +++ /dev/null @@ -1,559 +0,0 @@ -. - * - * $Id: main-class.inc.php 28 2008-01-19 17:17:01Z xrogaan $ - */ - -final class bot { - - const CTCP_CLIENTINFO = 'CLIENTINFO'; - const CTCP_VERSION = 'VERSION'; - const CTCP_USERINFO = 'USERINFO'; - const CTCP_TIME = 'TIME'; - const CTCP_PING = 'PING'; - - - // Timeout avant une reconnexion - public $socketTimeout = 180; - - // Variables privèes - static public $instance = FALSE; - static public $plugins = false; - - protected $C; - - static $botVersion = '1.0'; - static $server; - static $port; - static $channel; - static $myBotName; - static $ip; - static $domain; - static $connection_password; - - public $irc; - public $tick; -// public $plugins; - public $formater; - public $base; - public $msg; - public $connected = false; - - private $core_commands; - private $users_list; - private $msg_info; - private $lastData; - - public static function GetInstance() { - if (!self::$instance) { - self::$instance = new bot(); - //self::$instance->plugins = new plugins(); - self::$instance->irc = new irc; - self::$instance->tick = tick::GetInstance(); - } - return self::$instance; - } - - private function __construct() { - // load config and other things echo "oups main\n";die; - $this->formater = text_format::GetInstance(); - $this->connected = false; - } - - static private function plugins() { - if (!$plugins) - $plugins = new plugins($this); - return $plugins; - } - - private function load_core_plugin() { - // core plugin is an exeption in do_command - $this->plugins()->add_command('core','shownick',0,'Show the current nick used (debug)','mixed'); - $this->plugins()->add_command('core','nick',1,'Change the current nick','mixed'); - $this->plugins()->add_command('core','quit',0,'Disconnect and stop the process','mixed'); - $this->plugins()->add_command('core','restart',0,'Disconnect and restart the process','mixed'); - $this->plugins()->add_command('core','help',0,'Hmm, je dois recoder cette fonction','mixed'); - } - - public function launch() { - self::load_core_plugin(); - self::plugins()->Init(); - try { - //$this->C = @fsockopen(self::$server, self::$port, $errno, $errstr, 10); - $this->lastData = mktime(); - $this->C = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); - if ($this->C === false) { - throw new Exception('Impossible de créer le socket IRC !',0); - } - - if (self::$ip != "") { socket_bind($this->C, self::$ip); } - - $x = socket_connect($this->C, self::$server, self::$port); - if ($x===false) { - throw new Exception('Impossible de se connecter au server IRC ! ('.socket_last_error().')' ,0); - } - - $this->connected = true; - - if (self::$connection_password !== false) { - $this->put('PASS '.self::$connection_password); - } - // TODO : be sure for the validity of the connection password (what chain server return if fail ?) - - $this->put('USER '.self::$myBotName.' '.self::$myBotName.'@'.self::$ip.' '.self::$server.' :'.self::$myBotName); - $this->put('NICK '.self::$myBotName); - - /*$this->tick->setTick('all5sec',5); - $this->tick->addJob('all5sec','hello chan','privmsg',array(self::$channel,"I'm a tick. I show this msg all 5sec."),0,$this); - */ - while (1) { - $this->msg = $this->get(); - - if (is_array($this->msg)) { - foreach ($this->msg as $msg) { - if (!empty($msg)) { - $event = $this->event()->setIncoming($msg); - - $action = $event->getAction(); - - switch ($action) { - case Event::ACT_DISCONNECT: - $this->disconnect('ERROR: Closing Link'); - sleep(3); - throw new Exception('Closing Link.',1); - break; - case Event::ACT_PING: - $pong = split(':',$msg); - $this->put('PONG '.$pong[1]); - echo "PING :{$pong[1]}\nPONG {$pong[1]}\n\n"; - break; - case Event::ACT_KICK: - sleep(1); - $this->joinChannel(bot::$channel); - break; - } - - $this->msg_info = $msg_info = $event->getData(); - - switch ($msg_info['type']) { - - case Plugins_Command_Abstract::EVENT_PRIVMSG: - - // ctcp - if ($msg_info['message'][0] == chr(001)) { - - // we don't need this character - $msg_info['message'] = str_replace(chr(001), "", $msg_info['message']); - if (strstr($msg_info['message'],' ') === true) { - list($cmd,$query) = explode(" ",$msg_info['message']); - } else { - $cmd = $msg_info['message']; - } - - // we don't need this character - //$cmd = str_replace(chr(001), "", $msg_info['message']); - $cmd = trim($cmd); - - switch ($cmd) { - case self::CTCP_CLIENTINFO: - self::notice($msg_info['from'],$this->formater->ctcp('PING VERSION TIME USERINFO CLIENTINFO')); - break; - - case self::CTCP_VERSION: - self::notice($msg_info['from'],$this->formater->ctcp('RPGBot version '.bot::$botVersion.' - PHP '.phpversion().' -- on http://irstat.org')); - break; - - case self::CTCP_USERINFO: - self::notice($msg_info['from'],$this->formater->ctcp('RPGBot')); - break; - - case self::CTCP_TIME: - self::notice($msg_info['from'],$this->formater->ctcp(date('Y-m-d H:i:s'))); - break; - - case self::CTCP_PING: - self::notice($msg_info['from'],$this->formater->ctcp("PING ".$query)); - break; - default: - self::notice($msg_info['from'],$this->formater->ctcp("UNKNOWN CTCP REQUEST : '$cmd'")); - break; - } - } else { - $msg_info['message'] = trim($msg_info['message']); - if ($msg_info['to'] == bot::$myBotName) { - // auth proccess - // TODO : create a better login process - if (preg_match('`^connect ([^ ]+) ([^ ]+)`',$msg_info['message'],$m)) { - if ($m[1] == 'admin' && $m[2] == 'mypass') { - $this->auth = true; - self::notice($msg_info['from'],'Vous êtes bien authentifié comme administrateur.'); - } else { - self::notice($msg_info['from'],'Erreur dans votre login et / ou mot de passe.'); - echo debug() ? 'l: '.$m[1].' p: '.$m[2]."\n":''; - } - continue; - } - } - } - break; - case 'NOTICE': - break; - } - self::$plugins->set_event($event); - - } - } - } else { - $this->irc->parse_get($this->msg); - $this->work_on_listen(); - } - } - } catch (myRuntimeException $e) { - $x = $e->getMessage(); - echo $x; - $x.= backtrace($e->getTrace()); - file_put_contents('errorlog',$x); - //if ($e->_level < 2 || ($e->_level >= 256 && $e->_level < 1024)) { - echo 'Error level : '.$e->_level."\n\n"; - throw new Exception('Error occured',0); - /*} else { - echo 'Error level : '.$e->_level."\n\n\n\n"; - throw new Exception("Error occured. Please see errorlog for details.",1); - }*/ - } catch (Exception $e) { - throw $e; - } - } - - protected function event() { - return new Event($this); - } - - private function work_on_listen () { - $this->msg_info = $msg_info = $this->irc->get_msg_info(); - - switch ($msg_info['type']) { - - case 'PRIVMSG': - - // ctcp - if ($msg_info['message'][0] == chr(001)) { - - // we don't need this character - $msg_info['message'] = str_replace(chr(001), "", $msg_info['message']); - if (strstr($msg_info['message'],' ')===true) { - list($cmd,$query) = explode(" ",$msg_info['message']); - } else { - $cmd = $msg_info['message']; - } - - // we don't need this character - //$cmd = str_replace(chr(001), "", $msg_info['message']); - $cmd = trim($cmd); - - switch ($cmd) { - case 'CLIENTINFO': - self::notice($msg_info['from'],$this->formater->ctcp('PING VERSION TIME USERINFO CLIENTINFO')); - break; - - case 'VERSION': - self::notice($msg_info['from'],$this->formater->ctcp('RPGBot version '.bot::$botVersion.' - PHP '.phpversion().' -- on http://irstat.org')); - break; - - case 'USERINFO': - self::notice($msg_info['from'],$this->formater->ctcp('RPGBot')); - break; - - case 'TIME': - self::notice($msg_info['from'],$this->formater->ctcp(date('Y-m-d H:i:s'))); - break; - - case 'PING': - self::notice($msg_info['from'],$this->formater->ctcp("PING ".$query)); - break; - default: - self::notice($msg_info['from'],$this->formater->ctcp("UNKNOWN CTCP REQUEST : '$cmd'")); - break; - } - } else { - $msg_info['message'] = trim($msg_info['message']); - if ($msg_info['to'] == bot::$myBotName) { - // auth proccess - if (preg_match('`^connect ([^ ]+) ([^ ]+)`',$msg_info['message'],$m)) { - if ($m[1] == 'admin' && $m[2] == 'mypass') { - $this->auth = true; - self::notice($msg_info['from'],'Vous êtes bien authentifié comme administrateur.'); - } else { - self::notice($msg_info['from'],'Erreur dans votre login et / ou mot de passe.'); - echo debug() ? 'l: '.$m[1].' p: '.$m[2]."\n":''; - } - continue; - } - } -/* - if ($msg_info['message'][0] == '!') { - $message = substr($msg_info['message'],1); - $query = explode(' ',$message); - $query_count = count($query); - - if (isset($this->plugins->commands[$query[0]])) { - if ($query_count > 1) { - if (isset($this->plugins->commands[$query[0]][$query[1]])) { - call_user_func_array(array($this->plugins,'do_command'),array_merge(array('msg_info'=>$msg_info),$query)); - } else { - $this->privmsg($msg_info['from'],"This command do not exist. Try !{$query[0]} for the list of commands avaiable with this plugin."); - } - } else { - // no method : need a list of commands - $plugin = $message; - - $commands = $this->plugins->list_command($plugin); - foreach ($commands as $command_info) { - if ($command_info['type'] == 'public') { - $get_plugin_method = '!'.$plugin; - } else { - $get_plugin_method = '/msg ' . bot::$myBotName . ' !' . $plugin; - } - - $msg = array_merge(array($this->formater->bold('Command :')." $get_plugin_method {$command_info['method']}".(($command_info['accepted_args']>0)?' [some args...]':'')),text_format::paragraphe($command_info['help'])); - $this->mprivmsg($msg_info['from'],$msg); - } - } - } else { - //var_dump($this->plugins->commands); - } - } -*/ - } - break; - case 'NOTICE': - break; - } - self::$plugins->set_event($msg_info); - } - - public function joinChannel($channel) { - $this->put('JOIN '.$channel); - echo "Join channel $channel ...\n"; - } - - public function newNick($new=false) { - switch ($new) { - case self::$myBotName: - echo "New nick : [ERR] no changes :". self::$myBotName . ' == ' . $new ."\n"; - break; - case false: - self::$myBotName .= '_'; - self::nick_change(); - break; - default: - self::$myBotName = $new; - self::nick_change(); - break; - } - } - - /** - * Envoie une notice a un salon / utilisateur - * - * @param string $to - * @param string $message - */ - public function notice ($to,$message) { - self::put('NOTICE '.$to.' :'.$message."\n"); - } - - /** - * Envoie un message (PRIVMSG) a un salon / utilisateur - * - * @param string $to - * @param string $message - */ - public function privmsg ($to,$message) { - $search = array('#name'); - $replace = array(self::$myBotName); - $message = str_replace($search,$replace,$message); - self::put('PRIVMSG '.$to.' :'.$message."\n"); - } - - public function mprivmsg($to,$messages,$interval=650000) { - if (is_array($messages)) { - foreach ($messages as $msg) { - $this->privmsg($to,$msg); - usleep($interval); - } - } - } - - public function put($data) { - if (!is_resource($this->C)) { - throw new Exception('Connection lost...',1); - return; - } - - echo debug() ? 'bot::put() -> ' . $data . "\n" : ''; - - $ok = socket_write($this->C, $data ."\n"); - if ($ok) { - return true; - } else { - return false; - } - -// fputs($this->C, $command . "\n"); - return true; - } - - public function get() { - - $buffer = ''; - socket_set_nonblock($this->C); - - while (1) { - //echo "TOC - ",time(),"\n"; - $this->tick->doAllTicks(); - $buf = @socket_read($this->C, 4096); - - if (empty($buf)) { - $this->CheckTimeout(); - sleep(1); - continue; - } - - $this->lastData = mktime(); - - if (!strpos($buf, "\n")) { //Si ne contient aucun retour, on bufferise - $buffer = $buffer.$buf; - $data = ""; //rien è envoyer - } else { - //Si contient au moins un retour, - //on vèrifie que le dernier caractère en est un - if (substr($buf, -1, 1) == "\n") { - //alors on additionne ces donnèes au buffer - $data = $buffer.$buf; - $buffer = ""; //on vide le buffer - } else { - //si le dernier caractère n'est pas un retour è la - //ligne, alors on envoit tout jusqu'au dernier retour - //puis on bufferise le reste - $buffer = $buffer.substr($buf, strrchr($buf, "\n")); - $data = substr($buf, 0, strrchr($buf, "\n")); - $data = $buffer.$data; - $buffer = ""; //on vide le buffer - } - } - - if ($data != '') { - $data = split("\n", $data); - return $data; - } - - continue; - } - - } - - public function shownick() { - $this->privmsg(bot::$channel,bot::$myBotName."\n"); - } - - public function nick($newNick) { - $this->newNick($newNick); - } - - public function help() { - $this->privmsg($this->msg_info['from'],"List of plugins :"); - foreach($this->plugins->plugin_list as $pluginName => $object) { - $this->privmsg($this->msg_info['from'],"!$pluginName"); - usleep(500000); - } - } - - public function restart() { - if ($this->auth) { - echo 'Restart...'."\n"; - $this->disconnect(); - sleep(5); - throw new Exception('Restart...',1); - } else { - $this->privmsg($this->msg_info['from'],"Vous n'etes pas authentifie."); - } - } - - public function quit() { - if ($this->auth) { - $this->disconnect(); - throw new Exception('Quit from',3); - } else { - $this->privmsg($this->msg_info['from'],"Vous n'etes pas authentifie."); - } - } - - public function disconnect($msg='EOL ;') { - $this->plugins->unload_plugin('_all'); - echo "Closing Link..."; - if (is_resource($this->C)) { - if ($this->put('QUIT :'.$msg)) { - $this->connected = false; - socket_close($this->C); - } - echo "\t\t\tdone.\n"; - } else { - echo "\t\t\tError.\nConnection already breack down. ".'bot::disconnect'."\n"; - } - return true; - } - - private function nick_change() { - echo "New nick : ".self::$myBotName."\n"; - if ($this->put('NICK :'.self::$myBotName)) { - return true; - } - return false; - } - - private function CheckTimeout() { - $now = mktime(); - if ($this->lastData+$this->socketTimeout < mktime()) { - throw new Exception('Connection lost (Timeout).',1); - } - $lag = $now-$this->lastData; - if ( $lag > 20 && ($lag % 10) == 0) { - echo "Lag: ".$lag." seconds\n"; - } - } - - private function load_user($file='users.db') { - echo "Loading users ..."; - $ulist = explode("\n",file_get_contents($file)); - foreach ($ulist as $user) { - list($uname,$upass,$uright) = explode(':',$user); - $this->users_list[$uname] = array($upass,$uright); - } - echo "\t\t\tdone.\n"; - } - - function __destruct() { - if (is_resource($this->C)) { - if ($this->put('QUIT :Error occured')) { - socket_close($this->C); - } - } - } -} - -- 2.11.4.GIT