diff --git a/ircbot/bot.conf b/ircbot/bot.conf deleted file mode 100644 index 357d3e3..0000000 --- a/ircbot/bot.conf +++ /dev/null @@ -1,147 +0,0 @@ -;+--------------------------------------------------------------------------- -;| PHP-IRC v2.2.1 Service Release -;| ======================================================= -;| by Manick -;| (c) 2001-2006 by http://www.phpbots.org/ -;| Contact: manick@manekian.com -;| irc: #manekian@irc.rizon.net -;| ======================================== -;| Special Contributions were made by: -;| cortex -;+--------------------------------------------------------------------------- -;| > Configuration File -;+--------------------------------------------------------------------------- -;| > This program is free software; you can redistribute it and/or -;| > modify it under the terms of the GNU General Public License -;| > as published by the Free Software Foundation; either version 2 -;| > of the License, or (at your option) any later version. -;| > -;| > This program is distributed in the hope that it will be useful, -;| > but WITHOUT ANY WARRANTY; without even the implied warranty of -;| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;| > GNU General Public License for more details. -;| > -;| > You should have received a copy of the GNU General Public License -;| > along with this program; if not, write to the Free Software -;| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -;+--------------------------------------------------------------------------- -;| Changes -;| =======------- -;| > If you wish to suggest or submit an update/change to the source -;| > code, email me at manick@manekian.com with the change, and I -;| > will look to adding it in as soon as I can. -;+--------------------------------------------------------------------------- - - -;====Bot config file - -;====Contains the nickname of the Bot -nick LW-Bot - -;====The nickserv password, if any (autoident).. -password ... - -;====Real name.. -realname Legacy Worlds Bot - -;====The server you are going to connect to -server localhost - -;====The server port -port 6667 - -;====The server password you are going to connect to -;serverpassword test - -;====NAT IP -;natip 192.168.1.101 - -;===BIND IP -;Specify the IP this bot should bind to when connecting to a server -;bind 127.0.0.1 - -;====DCC Range start for chats/files -;dccrangestart 6081 - -;====DCC Reverse Protocl -;This follows the mIRC DCC Server Protocol -;When this is set, you will connect to this port -;on the users machine, and send them the file, similar to -;sysreset's firewall workaround. -;This function is EXPERIMENTAL -;==== -;mircdccreverse 4000 - -;====Who on join? -;After joining a channel, populate the host lists -;with /WHO information? This probably isn't so good -;for larger channels... -;This function populates host/ident information for -;all users in a channel. Useful for running channel protection -;scripts and such. The DCC Reverse setting above using a WHOIS -;command to get user hosts, so this doesn't have to be set -;to use the above setting. -;==== -;populatewho - -;====Populate ban list? -;This will make php-irc run MODE #chan +b upon joining, populating -;the ban list. This is useful for running channel protection or ban -;rotating scripts. -;==== -;populatebans - -;====Flood lines -;when someone types text that is a trigger for the bot, how many times can they type -;different triggers (within a 10 second period) before the bot ignores them for spamming the bot -floodlines 500 - -;====Time to ban user in seconds for abusing the bots triggers -floodtime 60 - -;====Channels.. unlimited -;====i.e., channel #channel key -;====but you don't have to specify a key -channel #testing meeeh - -;====Your ident -ident lwbot - -;====Log file -logfile __CFG:cachedir__/ircbot.log - -;====uncomment the following lines to use a database -;either 'usedatabase mysql' or 'usedatabase postgre' -;usedatabase mysql - -;dbuser root -;dbpass none -;db question -;dbprefix bot_ -;dbhost localhost -;dbport - -;====Send queue timeout -;How often to send more text to the irc server. This handles the 'notice' -;and 'privMsg' commands sent from modules and such (in seconds) -queuetimeout 1 - -;====Send queue buffer -;How many bytes of text to send to the server every 'queuetimeout' period. -queuebuffer 225 - -;====Perm. Ignore (These hosts will always be ignored, forever) -;example: -;ignore *!*@* - -;====DCC Admin password //default is 'mypass' -;dccadminpass a029d0df84eb5549c641e04a9ef389e5 - -;====set this to your function file -functionfile function.conf - -;====whether this bot accepts sends from other people -upload no - -;====The place where uploaded files are put. -;uploaddir /home/my/dir/ diff --git a/ircbot/bot.php b/ircbot/bot.php deleted file mode 100644 index 1719a6a..0000000 --- a/ircbot/bot.php +++ /dev/null @@ -1,476 +0,0 @@ - Main module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -error_reporting(E_ALL); -set_time_limit(0); - - -$oldDir = getcwd(); -chdir("../scripts"); -$__logPrefix = "lwBot"; -$__loader = array( - 'log', 'classloader', 'version', 'game', 'tick', 'config', - 'db_connection', 'db_accessor', 'db', 'library' -); -require_once('loader.inc'); -chdir($oldDir); - -require('./defines.php'); -require('./queue.php'); -require('./module.php'); -require('./irc.php'); -require('./socket.php'); -require('./timers.php'); -require('./dcc.php'); -require('./chat.php'); -require('./file.php'); -require('./parser.php'); -require('./databases/ini.php'); -require('./error.php'); -require('./connection.php'); -require('./remote.php'); - - -final class bot { - - /* Global socket class used by all bots */ - private $socketClass; - - /* Global process Queue used by all bots, timers, dcc classes */ - private $procQueue; - - /* Whether we are running in background mode or not. (not sure if this is used anymore */ - private $background = 0; - - //contain all the bots - private $bots = array(); - - // save the only one instance of bot (singleton) - private static $_instance; - - public static function getInstance() - { - if (!isset (self :: $_instance)) - { - self :: $_instance = new bot(); - } - return self :: $_instance; - } - - - //Main Method - private function __construct() - { - - $this->socketClass = new socket(); - $this->procQueue = new processQueue(); - - $this->socketClass->setProcQueue($this->procQueue); - - $this->readConfig(); - } - - public function launch(){ - - foreach($this->bots as $bot) - { - $this->createBot($bot); - } - - try - { - - /* Main program loop */ - - while (1) - { - //Get data from sockets, and trigger procQueue's for new data to be read - $this->socketClass->handle(); - - //The bots main process loop. Run everything we need to! - $timeout = $this->procQueue->handle(); - - //Okay, set the socketclass timeout based on the next applicable process - if ($timeout !== true) - { - $this->socketClass->setTimeout($timeout); - } - - //echo $this->procQueue->getNumQueued() . "\n"; - //$this->procQueue->displayQueue(); - - //Aight, if we don't have any sockets open/in use, and - //we have no processes in the process queue, then there are - //obviously no bots running, so just exit! - if ($this->socketClass->getNumSockets() == 0 && $this->procQueue->getNumQueued() == 0) - { - break; - } - } - - } - catch (Exception $e) - { - $this->ircClass->log($e->_toString()); - } - - } - - - public static function addBot($filename){ - $bot = bot::getInstance(); - $config = bot::parseConfig($filename); - if ($config == false) - { - return false; - } - - $newBot = new botClass(); - $newBot->config = $config; - $newBot->configFilename = $filename; - - $bot->bots[] = $newBot; - $bot->createBot($newBot); - return true; - } - - - private function createBot($bot) - { - $this->connectToDatabase($bot); - - $bot->socketClass = $this->socketClass; - $bot->timerClass = new timers(); - $bot->parserClass = new parser(); - - $bot->dccClass = new dcc(); - $bot->ircClass = new irc(); - - $bot->ircClass->setConfig($bot->config, $bot->configFilename); - $bot->ircClass->setSocketClass($this->socketClass); - $bot->ircClass->setParserClass($bot->parserClass); - $bot->ircClass->setDccClass($bot->dccClass); - $bot->ircClass->setTimerClass($bot->timerClass); - $bot->ircClass->setProcQueue($this->procQueue); - - $bot->dccClass->setSocketClass($this->socketClass); - $bot->dccClass->setTimerClass($bot->timerClass); - $bot->dccClass->setParserClass($bot->parserClass); - $bot->dccClass->setProcQueue($this->procQueue); - - $bot->parserClass->setTimerClass($bot->timerClass); - $bot->parserClass->setSocketClass($this->socketClass); - $bot->parserClass->setDatabase($bot->db); - - $bot->timerClass->setIrcClass($bot->ircClass); - $bot->timerClass->setSocketClass($this->socketClass); - $bot->timerClass->setProcQueue($this->procQueue); - - $bot->parserClass->init(); - - //Okay, this function adds the connect timer and starts up this bot class. - $bot->ircClass->init(); - - bot::createChannelArray($bot->ircClass); - - } - - - private function readConfig() - { - global $argc, $argv; - - if ($argc < 2) { - $args = array(config::$main['scriptdir'] . "/../ircbot/bot.conf"); - } else { - $args = $argv; - array_shift($args); - } - - $isPasswordEncrypt = false; - - foreach ($args AS $filename) - { - if ($filename == "") - { - continue; - } - - if ($isPasswordEncrypt == true) - { - die("Encrypted Password: " . md5($filename) . "\nReplace this as 'dccadminpass' in bot.conf!"); - } - - if ($filename == "-c") - { - $isPasswordEncrypt = true; - continue; - } - - if ($filename == "-b" && $this->background != 1) - { - $this->background = 1; - $this->doBackground(); - continue; - } - - $config = bot::parseConfig($filename); - - if ($config == false) - { - echo "Could not spawn bot $filename"; - die(); - } - - $bot = new botClass(); - $bot->config = $config; - $bot->configFilename = $filename; - - $this->bots[] = $bot; - } - - if ($isPasswordEncrypt == true) { - die("No password submitted on command line! Syntax: bot.php -c \n"); - } - - if (! $this->background && PID != '') { - $file = fopen(PID, "w+"); - fwrite($file, getmypid()); - fclose($file); - } - } - - - - - private function connectToDatabase($bot) - { - if (isset($bot->config['usedatabase'])) - { - if (!file_exists("./databases/" . $bot->config['usedatabase']. ".php")) - { - die("Couldn't find the database file! Make sure it exists!"); - } - - require_once("./databases/" . $bot->config['usedatabase']. ".php"); - - $dbType = $bot->config['usedatabase']; - - if (!isset($bot->config['dbhost'])) - $bot->config['dbhost'] = "localhost"; - if (!isset($bot->config['dbuser'])) - $bot->config['dbuser'] = "root"; - if (!isset($bot->config['dbpass'])) - $bot->config['dbpass'] = ""; - if (!isset($bot->config['db'])) - $bot->config['db'] = "test"; - if (!isset($bot->config['dbprefix'])) - $bot->config['dbprefix'] = ""; - if (!isset($bot->config['dbport'])) - { - $bot->db = new $dbType($bot->config['dbhost'], - $bot->config['db'], - $bot->config['dbuser'], - $bot->config['dbpass'], - $bot->config['dbprefix']); - } - else - { - $bot->db = new $dbType($bot->config['dbhost'], - $bot->config['db'], - $bot->config['dbuser'], - $bot->config['dbpass'], - $bot->config['dbprefix'], - $bot->config['dbport']); - } - - if (!$bot->db->isConnected()) - { - die("Couldn't connect to database..."); - } - - } - } - - - public static function createChannelArray($ircClass) - { - $channels = $ircClass->getClientConf('channel'); - - if ($channels != "") - { - if (!is_array($channels)) - { - $channels = array($channels); - } - - foreach ($channels AS $channel) - { - $chan = $channel; - $key = ""; - - if (strpos($channel, chr(32)) !== false) - { - $channelVars = explode(chr(32), $channel); - $chan = $channelVars[0]; - $key = $channelVars[1]; - } - - $ircClass->maintainChannel($chan, $key); - } - } - } - - public static function parseConfig($filename) - { - $configFPtr = @fopen($filename, "rt"); - - if ($configFPtr == null) - { - // echo "Could not find config file '".$filename."'\n"; - return false; - } - - $configRaw = ""; - - try - { - - while (!feof($configFPtr)) - { - $configRaw .= fgets($configFPtr, 1024); - } - - fclose($configFPtr); - - } - catch (Exception $e) - { - // echo "A fatal IO Exception occured."; - return false; - } - - $config = array(); - - $configRaw = str_replace("\r", "", $configRaw); - - $confLines = explode("\n", $configRaw); - - foreach ($confLines AS $line) - { - $line = trim($line); - - if ($line == "" || substr($line, 0, 1) == ";") - { - continue; - } - - $offsetA = strpos($line, chr(32)); - - if ($offsetA != false) - { - $confVar = substr($line, 0, $offsetA); - $confParams = substr($line, $offsetA + 1); - } - else - { - $confVar = $line; - $confParams = ""; - } - - if (preg_match('/__CFG:([a-zA-Z_]+)__/', $confParams, $matches)) { - $src = array(); $dst = array(); - array_shift($matches); - foreach ($matches as $cfgSubst) { - array_push($src, "/__CFG:{$cfgSubst}__/"); - array_push($dst, config::$main[$cfgSubst]); - } - $confParams = preg_replace($src, $dst, $confParams); - } - - if (isset($config[$confVar])) - { - if (!is_array($config[$confVar])) - { - $prevParam = $config[$confVar]; - $config[$confVar] = array(); - $config[$confVar][] = $prevParam; - } - - $config[$confVar][] = $confParams; - - } - else - { - $config[$confVar] = $confParams; - } - } - - return $config; - } - - - private function doBackground() - { - $pid = pcntl_fork(); - if ($pid == -1) { - die("Error: could not fork\n"); - } else if ($pid) { - if (PID != "") { - $file = fopen(PID, "w+"); - fwrite($file, $pid); - fclose($file); - } - - exit(); // Parent - } - - if (!posix_setsid()) { - die("Error: Could not detach from terminal\n"); - } - - fclose(STDIN); - fclose(STDOUT); - fclose(STDERR); - } - -} - -$ircBot = bot::getInstance(); -$ircBot->launch(); - -?> diff --git a/ircbot/chat.php b/ircbot/chat.php deleted file mode 100644 index cd5abaf..0000000 --- a/ircbot/chat.php +++ /dev/null @@ -1,364 +0,0 @@ - dcc chat module -| > Module written by Manick -| > Module Version Number: 2.2.1 beta -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class chat { - - /* Chat specific Data */ - public $id; - public $status; - public $sockInt; - public $isAdmin; - public $timeConnected; - public $verified; - public $readQueue; - public $floodQueue; - public $floodQueueTime; - public $port; - public $type; - public $nick; - public $timeOutLevel; - public $removed; - public $connection; - - public $handShakeSent; - public $handShakeTime; - public $reverse; - public $connectHost; - - /* Classes */ - private $dccClass; - private $parserClass; - private $ircClass; - private $socketClass; - private $timerClass; - - //class handler - private $handler; - - /* Constructor */ - public function __construct($id, $nick, $admin, $sockInt, $host, $port, $handler, $reverse) - { - $this->id = $id; - $this->handler = $handler; - $this->nick = $nick; - $this->isAdmin = $admin; - $this->sockInt = $sockInt; - $this->port = $port; - $this->connectHost = $host; - $this->reverse = $reverse; - $this->handShakeSent = false; - - $this->sendQueue = array(); - $this->sendQueueCount = 0; - } - - public function setIrcClass($class) - { - $this->ircClass = $class; - } - - public function setDccClass($class) - { - $this->dccClass = $class; - } - - public function setSocketClass($class) - { - $this->socketClass = $class; - } - - public function setParserClass($class) - { - $this->parserClass = $class; - } - - public function setTimerClass($class) - { - $this->timerClass = $class; - } - - private function sendUserGreeting() - { - if ($this->verified == true) - { - return; - } - - $this->dccSend("Welcome to " . $this->ircClass->getNick()); - $this->dccSend("PHP-iRC v". VERSION ." [". VERSION_DATE ."]"); - $time = $this->ircClass->timeFormat($this->ircClass->getRunTime(), "%d days, %h hrs, %m min, %s sec"); - $this->dccSend("running " . $time); - $this->dccSend("You are currently in the dcc chat interface. Type 'help' to begin."); - } - - private function sendAdminGreeting() - { - if ($this->verified == true) - { - return; - } - - $this->dccSend("Welcome to " . $this->ircClass->getNick()); - $this->dccSend("PHP-iRC v". VERSION ." [". VERSION_DATE ."]"); - $time = $this->ircClass->timeFormat($this->ircClass->getRunTime(), "%d days, %h hrs, %m min, %s sec"); - $this->dccSend("running " . $time); - $this->dccSend("Enter Your Password:"); - } - - public function dccSend($data, $to = null) - { - if ($this->status != DCC_CONNECTED) - { - return; - } - - if ($to == null) - { - $to = $this; - } - - $this->dccClass->dccSend($to, "--> " . $data . "\n"); - } - - public function dccSendRaw($data, $to = null) - { - if ($this->status != DCC_CONNECTED) - { - return; - } - - if ($to == null) - { - $to = $this; - } - - $this->dccClass->dccSend($to, $data); - } - - - public function disconnect($msg = "") - { - - $msg = str_replace("\r", "", $msg); - $msg = str_replace("\n", "", $msg); - - if (is_object($this->handler) && $this->status == DCC_CONNECTED) - { - $this->handler->disconnected($this); - } - - $this->status = false; - - if ($msg != "") - { - $this->dccClass->dccInform("DCC: " . $this->nick . " closed DCC Chat (" . $msg . ")", $this); - $this->ircClass->notice($this->nick, "DCC session ended: " . $msg, 1); - } - else - { - $this->dccClass->dccInform("DCC: " . $this->nick . " closed DCC Chat", $this); - } - - $this->dccClass->disconnect($this); - - $this->connection = null; - - return true; - } - - - - private function doHandShake() - { - $this->dccSendRaw("100 ".$this->ircClass->getNick()."\n"); - $this->handShakeSent = true; - $this->timerClass->addTimer(irc::randomHash(), $this, "handShakeTimeout", "", 8); - } - - private function processHandShake() - { - if ($this->readQueue == "") - { - return; - } - - $response = $this->readQueue; - $this->readQueue = ""; - $responseArray = explode(chr(32), $response); - if ($responseArray[0] == "101") - { - $this->reverse = false; - $this->onConnect($this->connection); - return; - } - - $this->disconnect("DCC Client Server reported error on attempt to start chat"); - } - - public function handShakeTimeout() - { - if ($this->status != false) - { - if ($this->reverse == true) - { - $this->disconnect("DCC Reverse handshake timed out"); - } - } - return false; - } - - /* Main events */ - public function onTimeout($conn) - { - $this->disconnect("Connection transfer timed out"); - } - - public function onDead($conn) - { - $this->disconnect($this->connection->getErrorMsg()); - } - - public function onRead($conn) - { - if ($this->socketClass->hasLine($this->sockInt)) - { - $this->readQueue .= $this->socketClass->getQueueLine($this->sockInt); - } - - if ($this->status == DCC_CONNECTED) - { - if ($this->reverse != false) - { - if ($this->handShakeSent != false) - { - $this->processHandShake(); - } - } - else - { - if ($this->readQueue != "") - { - $this->parserClass->parseDcc($this, $this->handler); - } - } - - } - - if ($this->socketClass->hasLine($this->sockInt)) - { - return true; - } - } - - public function onWrite($conn) - { - //do nothing - } - - public function onAccept($oldConn, $newConn) - { - $this->dccClass->accepted($oldConn, $newConn); - $this->connection = $newConn; - $oldConn->disconnect(); - $this->sockInt = $newConn->getSockInt(); - $this->onConnect($newConn); - } - - public function onConnectTimeout($conn) - { - $this->disconnect("Connection attempt timed out"); - } - - public function onConnect($conn) - { - $this->status = DCC_CONNECTED; - - if ($this->reverse != false) - { - $this->dccClass->dccInform("DCC CHAT: " . $this->nick . " handling dcc server request"); - $this->doHandShake(); - return; - } - - $this->dccClass->dccInform("DCC CHAT: " . $this->nick . " connection established"); - - if ($this->handler === false || $this->handler == null) - { - if ($this->isAdmin == true) - { - $this->sendAdminGreeting(); - } - else - { - $this->sendUserGreeting(); - } - } - else - { - - if (is_object($this->handler)) - { - $this->handler->connected($this); - } - } - - } - - - public function initialize() - { - - $this->dccClass->dccInform("DCC: " . $this->nick . " is attempting to login"); - - if ($this->status == DCC_LISTENING) - { - $this->ircClass->privMsg($this->nick, "\1DCC CHAT chat " . $this->ircClass->getClientIP(1) . " " . $this->port . "\1", 0); - $this->ircClass->notice($this->nick, "DCC Chat (" . $this->ircClass->getClientIP(0) . ")", 0); - } - - $this->timeConnected = time(); - $this->timeOutLevel = 0; - $this->verified = 0; - $this->readQueue = ""; - $this->floodQueue = ""; - $this->floodQueueTime = 0; - $this->type = CHAT; - } - - -} - -?> diff --git a/ircbot/command_reference.txt b/ircbot/command_reference.txt deleted file mode 100644 index 72611e2..0000000 --- a/ircbot/command_reference.txt +++ /dev/null @@ -1,870 +0,0 @@ -+--------------------------------------------------------------------------- -| PHP-IRC v2.2.1 Service Release -| ======================================================== -| by Manick -| (c) 2001-2006 by http://www.phpbots.org/ -| Contact: manick@manekian.net -| irc: #manekian@irc.rizon.net -| ======================================================== -+--------------------------------------------------------------------------- -| > Module Command Reference -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- - -The following file is a quickly put together command reference of all the functions that you can use to complement the php scripting language while writing your modules. - -=============== -Quick Reference (See below the quick reference for function descriptions) -=============== - -irc.php (Accessed with $this->ircClass->) ------------------------------------------ -array parseModes($modeString) -array getMaintainedChannels() -string getClientConf($var = "") -string getNick() -string getServerConf($var) -string getStatusString($status) -string getClientIP($long = 1) -class getChannelData($channel) -class getUserData($user, $channel = "") -void disconnect() -void setClientConfigVar($var, $value) -void joinChannel($chan) -void sendRaw($text, $force = false) -void privMsg($who, $msg, $queue = 1) -void action($who, $msg, $queue = 1) -void notice($who, $msg, $queue = 1) -void log($text) -void maintainChannel($channel, $key = "") -void removeMaintain($channel) -void addQuery($host, $port, $query, $line, $class, $function) -int getStatusRaw() -bool changeMode($chan, $act, $mode, $user) -bool isOnline($nick, $chan) -bool isMode($nick, $channel, $mode) -bool isChanMode($channel, $mode, $extra = "") -bool hasModeSet($chan, $user, $modes); -bool hostMasksMatch($mask1, $mask2) -bool checkIgnore($mask) - -socket.php (Accessed with $this->socketClass->) ------------------------------------------------ -string getHost($sockInt) -string getQueue($sockInt) -string getQueueLine($sockInt) -int sendSocket($sockInt, $data) -int getSockStatus($sockInt) -object getSockData($sockInt) -bool hasWriteQueue($sockInt) -bool hasLine($sockInt) - -timers.php (Accessed with $this->timerClass->) ----------------------------------------------- -class addTimer($name, $class, $function, $args, $interval, $runRightAway = false) -class getTimers() -void removeTimer($timer) (MUST be name) - -mysql/postgre.php (Accessed with $this->db->) ---------------------------------------------- -array queryFetch($query) -array fetchArray($object) -array fetchRow($object) -string getError() -bool isConnected() -int lastID() -int numRows($toFetch) -int numQueries() -void close() -object query($query) - -dcc.php (Accessed with $this->dccClass->) ------------------------------------------ -array getDccList() -int getDownloadCount() -int getUploadCount() -int getChatCount() -int getBytesDown() -int getBytesUp() -int addChat($nick, $host, $port, $admin, $handler) -int addFile($nick, $host, $port, $type, $filename, $size) -int sendFile($nick, $file) -class getDcc($dcc) -void dccInform($text, $from = null) - -chat.php ----------- -void disconnect($msg = "") -void dccSend($msg) - -file.php ----------- -void disconnect($msg = "") - -ini.php ----------- -bool getError() -bool sectionExists($section) -bool deleteSection($section) -bool deleteVar($section, $var) -bool setIniVal($section, $var, $val) -bool writeIni() -array getSections() -array getVars($section) -array getSection($section) -array randomSection($num = 1) -array searchSections($search, $type = EXACT_MATCH) -array searchVars($section, $search, $type = EXACT_MATCH) -array searchSectionsByVar($var, $search, $type = EXACT_MATCH) -array searchVals($section, $search, $type = EXACT_MATCH) -mixed randomVar($section, $num = 1) -mixed getIniVal($section, $var) -int numSections() -int numVars($section) - -Useful Static Routines ------------------------ -string socket::generatePostQuery($query, $host, $path, $httpVersion) -string socket::generateGetQuery($query, $host, $path, $httpVersion) -string irc::intToSizeString($size) -string irc::myStrToLower($text) -string irc::myStrToUpper($text) -string irc::timeFormat($time, $format) -string irc::randomHash() -array irc::multiLine($text) - - -========================= -Full Function Definitions -========================= - -irc.php (Accessed with $this->ircClass->) ------------------------------------------ - -------------------------------- -array parseModes($modeString) -------------------------------- - -Mode strings usually come from the $line['params'] variable. However, they look like this: - -+o-b Manick blah!*@* - -This is a real mess to parse. Thus, this function takes the line and returns an array of each mode being operated. The format is as follows: - -$modesArray = array( - - [0] = array( 'ACTION' => '+', - 'MODE' => 'o', - 'EXTRA' => 'Manick', - 'TYPE' => USER_MODE, - ) - - [1] = array( 'ACTION' => '-', - 'MODE' => 'b', - 'EXTRA' => 'blah!*@*', - 'TYPE' => CHANNEL_MODE, - ) -) - - --------------------------------- -array getMaintainedChannels() --------------------------------- -This will return an array of all the channels that php-irc will attempt to stay in. Every sixty seconds or so, the bot will attempt to join these channels if it is not currently in them. See 'maintainChannel()' and 'removeMaintain()' for more information. - - --------------------------------- -string getClientConf($var = "") --------------------------------- - -Will return the corresponding value for the setting of $var in bot.conf. If $var == "", the full configuration array is returned as an array. Also, if the setting does not exist in the configuration, this function will return an empty string, "". - - --------------------------------- -string getNick() --------------------------------- - -Returns the bots current, IRC recognized nick. - - --------------------------------- -string getServerConf($var) --------------------------------- - -When connecting to a server, it will send these lines upon connection: -NETWORK=Rizon STATUSMSG=@%+ MODES=4 CHANLIMIT=#:30 MAXCHANNELS=30 MAXLIST=beI:100 MAXBANS=100 MAXTARGETS=4 NICKLEN=30 TOPICLEN=400 KICKLEN=400 CHANNELLEN=50 AWAYLEN=90 are supported by this server -CHANTYPES=# KNOCK EXCEPTS INVEX PREFIX=(ohv)@%+ CHANMODES=eIb,k,l,cimnpstMNORZ CASEMAPPING=rfc1459 CALLERID WALLCHOPS FNC PENALTY ETRACE are supported by this server - -(These are just samples). So, you can retrieve the value for say, CHANMODES by doing this: - -getServerConf("CHANMODES"); - -This will return a string, "eIb,k,l,cimnpstMNORZ". - - ----------------------------------- -string getStatusString($status) ----------------------------------- - -After using getStatusRaw(), you can feed its value to this function, and it'll send back what it means, like "Connecting to Server..." - - ----------------------------------- -string getClientIP($long = 1) ----------------------------------- - -This function returns the IP that the bot is using. if you specify $long as 1, then the ip address converted to long integer form is returned. - - ----------------------------------- -class getChannelData($channel) ----------------------------------- - -This will search the channel database for the channel $channel, and then if it finds it, it will return that channels object. See the "channelLink" class in defines.php for member information. - - ----------------------------------- -class getUserData($user, $channel = "") ----------------------------------- - -If a channel is specified, this will search the channel for the specified user's data. If it is found, it will return it as an object. See the "memberLink" class in defines.php for member information. If no channel is specified, this will search the entire channel database until the member is found, and then return that object. - - ----------------------------------- -void disconnect() ----------------------------------- - -Disconnect the bot from the server... - - ----------------------------------- -void setClientConfigVar($var, $value) ----------------------------------- - -This will overwrite a configuration setting from bot.conf that the bot is currently using. Self-explanitory. - - ----------------------------------- -void joinChannel($chan) ----------------------------------- - -Join the channel $chan - - ----------------------------------- -void sendRaw($text, $force = false) ----------------------------------- - -Send the raw text $text to the server. If $force is true, then the data is sent RIGHT away, it totally bypasses the queue, everything. It goes right to the send function, even through the socket class. Use this if you need lightning fast responses, such as writing a channel guard script. - - ----------------------------------- -void privMsg($who, $msg, $queue = 1) ----------------------------------- - -$who = nick of user/name of channel - -Send text to a channel or user. If $queue is 1, then the data will be put at the end of the text queue, if it is 0, it'll be pushed onto the beginning of the queue. - ----------------------------------- -void action($who, $msg, $queue = 1) ----------------------------------- - -Same as privMsg... emulates the /me command from mIRC - - ----------------------------------- -void notice($who, $msg, $queue = 1) ----------------------------------- - -Same as privMsg, except a notice. - - ----------------------------------- -void log($text) ----------------------------------- - -Write something to the log file. - ----------------------------------- -void maintainChannel($channel, $key = "") ----------------------------------- - -Attempt to stay in channel $channel. The bot will attempt rejoining every 60 seconds. You may specify a $key or leave it blank. - ----------------------------------- -void removeMaintain($channel) ----------------------------------- - -No longer attempt to say in channel $channel. - ----------------------------------- -void addQuery($host, $port, $query, $line, $class, $function) ----------------------------------- - -Also make sure you read the text about this function in the readme.txt, "Querying remote servers". This function takes 6 arguments. - -$host = the host machine you want to connect to -$port = the port you want to connect to -$query = the raw data that will be sent to the server upon connection -$line = the $line argument that was passed to your module's function (just pass this right along with addQuery) -$class = usually '$this'.. -$function = the function to run after the query is complete. - -See sections 8 and 9 of readme.txt for information related to writing 'query' function types. - - ----------------------------------- -int getStatusRaw() ----------------------------------- - -Returns an integer corresponding to current server status. See defines.php for meanings - - ----------------------------------- -bool changeMode($chan, $act, $mode, $user) ----------------------------------- - -Changes the mode of $user on $chan - -$act = either "+" or "-" -$mode = some mode, like "o" (ops), or "b" (ban), or something else. -$user = whatever the mode is being applied to - - ----------------------------------- -bool isOnline($nick, $chan) ----------------------------------- - -Send back whether the nick is on the channel $chan (true or false) - - ----------------------------------- -bool isMode($nick, $channel, $mode) ----------------------------------- - -See if some $user has some $mode activated on him in $channel - -$user = nick of user -$mode = any mode, such as "o", "h", "v" - - ----------------------------------- -bool isChanMode($channel, $mode, $extra = "") ----------------------------------- - -Sends back whether a specific mode is set in a channel - -$mode = "b" or "s" or any other chan mode - -$extra = (if you're using "b" for $mode, specify mask here) - - ----------------------------------- -bool hasModeSet($chan, $nick, $modes) ----------------------------------- - -If any of the modes specified in "$modes" are set on a user in a channel, this will return true. -For instance: - -If Manick is +vo in channel #manekian, - -hasModeSet("#manekian", "Manick", "oh") - -will return true. I'm asking php-irc if Manick is either mode o or mode h. Which he's mode o, so it returns true. - - ----------------------------------- -bool hostMasksMatch($mask1, $mask2) ----------------------------------- - -Use this to determine whether two host masks match - - ----------------------------------- -bool checkIgnore($mask) ----------------------------------- -Check whether a hostmask is on the bot.conf ignore list. - - -socket.php (Accessed with $this->socketClass->) ------------------------------------------------ - ----------------------------------- -string getHost($sockInt) ----------------------------------- -Return the IP address of the current socket integer of a connection. You can use connection::getSockInt() to get the sock int. - - ----------------------------------- -string getQueue($sockInt) ----------------------------------- -Retrieve the current read queue for a socket. The queue is then purged. - - ----------------------------------- -string getQueueLine($sockInt) ----------------------------------- -Get the next line in the queue, purging it from the read buffer and returning it (without crlf) - - ----------------------------------- -int sendSocket($sockInt, $data) ----------------------------------- -Send data to a socket - - ----------------------------------- -int getSockStatus($sockInt) ----------------------------------- -Get the status of a socket. See defines.php for list of constants. - - ----------------------------------- -object getSockData($sockInt) ----------------------------------- -Return the object that retains all data about socket "$sockInt". This is a php-irc maintained list. - - ----------------------------------- -bool hasWriteQueue($sockInt) ----------------------------------- -Return true or false depending on whether the bot has data to write to the socket. If this is true, you should restrain yourself from sending more data to the socket. An onWrite() call will be sent every time data is written, and each time "hasWriteQueue()" should be called to see if the queue is empty before sending data. - - ----------------------------------- -bool hasLine($sockInt) ----------------------------------- -Return true or false depending on if there is a newline in the buffer. - - -timers.php (Accessed with $this->timerClass->) ----------------------------------------------- - ----------------------------------- -class addTimer($name, $class, $function, $args, $interval, $runRightAway = false) ----------------------------------- - -Add a timer. Please view the readme.txt documentation on this. - ----------------------------------- -class getTimers() ----------------------------------- - -This function will return a pointer to all the active timers. See the class "timer" in defines.php for member information. - - ----------------------------------- -void removeTimer($timer) (MUST be timer name) ----------------------------------- - -Remove a timer $timer <-- can only be the name of timer, unlike in 2.1.1 where it could be the object itself. - - -mysql/postgre.php (Accessed with $this->db->) ---------------------------------------------- -Some items for postgre aren't fully implemented or work yet... most notably queryFetch(), and some others. See postgre.php for more details. - ----------------------------------- -array queryFetch($query) ----------------------------------- - -Runs a query and returns the first row. Basically does query() and then mysql_fetch_array() - - ----------------------------------- -array fetchArray($object) ----------------------------------- - -Does mysql_fetch_array() (see php.net for help) - - ----------------------------------- -array fetchRow($object) ----------------------------------- - -Does mysql_fetch_row() - - ----------------------------------- -string getError() ----------------------------------- - -Does mysql_error(); - - ----------------------------------- -bool isConnected() ----------------------------------- - -Returns whether the database is connected - ----------------------------------- -int lastID() ----------------------------------- - -Gets the last inserted 'id' row from the database. - - ----------------------------------- -int numRows($toFetch) ----------------------------------- - -Does mysql_num_rows() - - ----------------------------------- -int numQueries() ----------------------------------- - -sends back an integer of all the queries since the database class was spawned. - - ----------------------------------- -void close() ----------------------------------- - -Closes the database connection - - ----------------------------------- -object query($query) ----------------------------------- - -Runs a query, and returns the result as an object. - - -dcc.php (Accessed with $this->dccClass->) ------------------------------------------ - ----------------------------------- -array getDccList() ----------------------------------- - -Returns an array of all current dcc's in progress (chat and file) - - ----------------------------------- -int getDownloadCount() ----------------------------------- - -Number of all current downloads - - ----------------------------------- -int getUploadCount() ----------------------------------- - -Number of all current uploads - - ----------------------------------- -int getChatCount() ----------------------------------- - -Number of all current dcc chat sessions - - ----------------------------------- -int getBytesDown() ----------------------------------- - -Returns number of bytes downloaded since bot was started - - ----------------------------------- -int getBytesUp() ----------------------------------- - -Returns number of bytes uploaded since bot was started - - ----------------------------------- -int addChat($nick, $host, $port, $admin, $handler) ----------------------------------- - -Use this to create a dcc chat session. - -$nick = nick of user to chat with -$host = host of user to chat with -$port = port to connect to -$admin = whether the user is admin (use admin dcc chat administration) -$handler = null, usually, unless you are creating a custom dcc chat handler. See readme.txt for more information. - -If $host or $port is null, then addChat will think you are setting up a listening connection, otherwise it will try to connect to the host/port specified. - - ----------------------------------- -int addFile($nick, $host, $port, $type, $filename, $size) ----------------------------------- - -Send a file to someone, or recieve a file. - -$nick = nick of person sending/receiving file -$host = host of person sending/receiving file -$port = port of transfer -$type = either UPLOAD or DOWNLOAD -$filename = full filename with full path to file -$size = size of the file, can be null if its an UPLOAD type. - -See readme.txt for more information regarding file transfers. - - ----------------------------------- -int sendFile($nick, $file) ----------------------------------- -Alias for addFile($nick, null, null, UPLOAD, $file, null)... basically just an easier way of sending files. - - ----------------------------------- -class getDcc($dcc) ----------------------------------- - -$dcc = sockInt of the transfer - -Returns dcc object for some sockInt, see fileserver.php for example. - - ----------------------------------- -void dccInform($text) ----------------------------------- - -Send a message to all administrators - - -chat.php ----------- - ----------------------------------- -void disconnect($msg = "") ----------------------------------- - -End the chat session - ----------------------------------- -void dccSend($msg) ----------------------------------- - -Send text to the user - - -file.php ----------- - ----------------------------------- -void disconnect($msg = "") ----------------------------------- - -End the dcc file transfer session - - -ini.php ----------- -Please see readme.txt for more information on create ini objects. - - ----------------------------------- -bool getError() ----------------------------------- -An ini object will not operate after a fatal error. You can use this to retrieve whether a fatal error has happened. - - ----------------------------------- -bool sectionExists($section) ----------------------------------- -Return true if the section exists, or false if it doesn't. - - ----------------------------------- -bool deleteSection($section) ----------------------------------- -Delete a section. - - ----------------------------------- -bool deleteVar($section, $var) ----------------------------------- -Delete a var in a section. - - ----------------------------------- -bool setIniVal($section, $var, $val) ----------------------------------- -Set the '$var' value '$val' in section $section. - - ----------------------------------- -bool writeIni() ----------------------------------- -Write all of the ini changes to a file - - ----------------------------------- -array getSections() ----------------------------------- -Return an array of all the section names. - - ----------------------------------- -array getVars($section) ----------------------------------- -Return all the vars/vals in an associative array for $section. - - ----------------------------------- -array getSection($section) ----------------------------------- -Alias for getVars() - - ----------------------------------- -array randomSection($num = 1) ----------------------------------- -Does same as getVars(), but returns random section. $num is the number of random sections to return. Default 1. - - ----------------------------------- -array searchSections($search, $type = EXACT_MATCH) ----------------------------------- -Search section names for $search, can do 4 types of searches: Exact, and, or, contains: - -Exact: the section and search match completely -And: the section name contains all componants of search (separated by space) -Or: the section name contains at least one of the componants of search (separated by space) -Contains: the section contains the search string within it - - ----------------------------------- -array searchVars($section, $search, $type = EXACT_MATCH) ----------------------------------- -Search the variable names of a section for $search, same as searchSections() except with vars. - - ----------------------------------- -array searchSectionsByVar($var, $search, $type = EXACT_MATCH) ----------------------------------- -In every section that has '$var' as a varaible, see if the var's value matches $search. - - ----------------------------------- -array searchVals($section, $search, $type = EXACT_MATCH) ----------------------------------- -Search all the values of a section for '$search'. Return list of vars. - - ----------------------------------- -mixed randomVar($section, $num = 1) ----------------------------------- -Return a random var in a section. - - ----------------------------------- -mixed getIniVal($section, $var) ----------------------------------- -Retrieve an ini value '$var' in section '$section'. False if non-existant. - - ----------------------------------- -int numSections() ----------------------------------- -Return number of sections. - - ----------------------------------- -int numVars($section) ----------------------------------- -Return number of vars in a section. - - -Useful Static Routines ------------------------ - ----------------------------------- -string socket::generatePostQuery($query, $host, $path, $httpVersion = "") ----------------------------------- - -Takes a query, like so: - -$query = "search=blah&somesetting=5"; - -And turns it into a POST query you can send off to addQuery - -$host = host of server you will be accessing, like "www.manekian.com" -$path = script + path of script you will be accessing, like "/search.php" or "/index.php", or just "/" -$httpVersion, you can ignore this, but sometimes you might want to set this to "1.0" - - ----------------------------------- -string socket::generateGetQuery($query, $host, $path, $httpVersion) ----------------------------------- - -Same as generatePostQuery except with Get String - - ----------------------------------- -string irc::intToSizeString($size) ----------------------------------- - -Takes a large size, and then changes it into MB, GB, KB, depending on the size. - - ----------------------------------- -string irc::myStrToLower($text) ----------------------------------- - -RFC1459 complient strtolower() - - ----------------------------------- -string irc::myStrToUpper($text) ----------------------------------- - -RFC1459 complient strtoupper() - - ----------------------------------- -string irc::timeFormat($time, $format) ----------------------------------- -Feed this thing a timestring, and a format, and it'll send back a user friendly representation of the timestamp. - -for example: - -timeFormat(5, "%d days, %h hours, %m minutes, %s seconds") - -This will return a string, "0 days, 0 hours, 0 minutes, 5 seconds". - - ----------------------------------- -string irc::randomHash() ----------------------------------- - -Generates a 32 char random md5 hash - - ----------------------------------- -array irc::multiLine($text) ----------------------------------- - -Feed this a huge text string, and it will split it up into 255 max char increment lines you can send to the irc server. It returns an array of all of these. - - - diff --git a/ircbot/connection.php b/ircbot/connection.php deleted file mode 100644 index 1a248df..0000000 --- a/ircbot/connection.php +++ /dev/null @@ -1,432 +0,0 @@ - connection class module -| > Module written by Manick -| > Module Version Number: 2.1.2 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -/* Connection class. A Layer between dcc/irc class and socket class. */ -/* To use, simply create an object, call the calls listed under the constructor in order. */ -/* Damn I'm hungry... */ - -class connection { - - //External Classes - private $socketClass; - private $ircClass; - private $timerClass; - - //Internal variables - private $callbackClass; - private $host; - private $port; - private $connTimeout; - private $transTimeout; - private $sockInt; - - //Function specific - private $connected; - private $connStartTime; - private $lastTransTime; - - //If this is set to true, this connection class will no longer function. - private $error; - private $errorMsg; - - //Called first - function __construct($host, $port, $connTimeout) - { - $this->error = true; - $this->errorMsg = "Connection not initialized"; - $this->host = $host; - $this->port = $port; - $this->connTimeout = $connTimeout; - $this->transTimeout = 0; - $this->connected = false; - $this->sockInt = false; - } - - //Called second - public function setSocketClass($class) - { - $this->socketClass = $class; - } - - //Called third - public function setIrcClass($class) - { - $this->ircClass = $class; - } - - //Called fourth - public function setCallbackClass($class) - { - $this->callbackClass = $class; - } - - //Called fifth - public function setTimerClass($class) - { - $this->timerClass = $class; - } - - //Called sixth - public function init() - { - $this->error = false; - - if ($this->host != null) - { - if ($this->connTimeout <= 0) - { - $this->setError("Must set connection timeout > 0 for non-listening sockets"); - return; - } - } - else - { - if ($this->connTimeout < 0) - { - $this->setError("Must set connection timeout >= 0 for listening sockets"); - return; - } - } - - if (!is_object($this->callbackClass)) - { - $this->setError("Specified callback class is not an object"); - return; - } - - if (!is_object($this->socketClass)) - { - $this->setError("Specified socket class is not an object"); - return; - } - - if (!is_object($this->ircClass)) - { - $this->setError("Specified irc class is not an object"); - return; - } - - $sockInt = $this->socketClass->addSocket($this->host, $this->port); // add socket - if ($sockInt == false) - { - $this->setError("Could not create socket"); - return; - } - - $sockData = $this->socketClass->getSockData($sockInt); - - $this->socketClass->setHandler($sockInt, $this->ircClass, $this, "handle"); - - //Set internal variables - if ($this->port == NULL) - { - $this->port = $sockData->port; - } - $this->sockInt = $sockInt; - - return $this->port; - } - - public function bind($ip) - { - if ($this->error != false || $this->sockInt == false) - { - return; - } - - if ($this->connected == true) - { - return; - } - - $this->socketClass->bindIP($this->sockInt, $ip); - } - - //Called to listen, only called by onAccept() function in this class - public function listen() - { - $this->error = false; - $this->connected = true; - } - - //Called last, and only to start connection to another server - public function connect() - { - if ($this->error == true) - { - return false; - } - - if ($this->connTimeout > 0) - { - $this->timerClass->addTimer(irc::randomHash(), $this, "connTimeout", "", $this->connTimeout); - } - - $this->timerClass->addTimer(irc::randomHash(), $this->socketClass, "connectSocketTimer", $this->sockInt, 1); - - /* $this->socketClass->beginConnect($this->sockInt); */ - $this->connStartTime = time(); - } - - public function disconnect() - { - unset($this->callbackClass); - $this->socketClass->killSocket($this->sockInt); - $this->socketClass->removeSocket($this->sockInt); - $this->setError("Disconnected from server"); - } - - public function getSockInt() - { - return $this->sockInt; - } - - public function setSockInt($sockInt) - { - $this->sockInt = $sockInt; - } - - public function setTransTimeout($time) - { - $this->transTimeout = ($time < 0 ? 0 : $time); - } - - /* Timers */ - - public function connTimeout() - { - if ($this->connected == false) - { - $this->handle(CONN_CONNECT_TIMEOUT); - } - } - - public function transTimeout() - { - if ($this->error == true) - { - return false; - } - - if ($this->connected == false) - { - return true; - } - - if ($this->transTimeout > 0) - { - if (time() > $this->transTimeout + $this->lastTransTime) - { - $this->handle(CONN_TRANSFER_TIMEOUT); - } - } - - return true; - } - - //handle function, handles all calls from socket class, and calls appropriate - //functions in the callback class - public function handle($msg) - { - - if ($this->socketClass->getSockStatus($this->sockInt) === false) - { - return false; - } - - $stat = false; - - if ($this->error == true) - { - return false; - } - - switch ($msg) - { - case CONN_CONNECT: - $stat = $this->onConnect(); - break; - case CONN_READ: - $stat = $this->onRead(); - break; - case CONN_WRITE: - $stat = $this->onWrite(); - break; - case CONN_ACCEPT: - $stat = $this->onAccept(); - break; - case CONN_DEAD: - $stat = $this->onDead(); - break; - case CONN_TRANSFER_TIMEOUT: - $stat = $this->onTransferTimeout(); - break; - case CONN_CONNECT_TIMEOUT: - $stat = $this->onConnectTimeout(); - break; - default: - return false; - break; - } - - return $stat; - } - - /* Specific handling functions */ - - private function onTransferTimeout() - { - $this->callbackClass->onTransferTimeout($this); - } - - private function onConnectTimeout() - { - $this->callbackClass->onConnectTimeout($this); - } - - private function onConnect() - { - $this->connected = true; - - if ($this->transTimeout > 0) - { - $this->timerClass->addTimer(irc::randomHash(), $this, "transTimeout", "", $this->transTimeout); - } - - $this->callbackClass->onConnect($this); - return false; - } - - //For this function, true can be returned from onRead() to input more data. - private function onRead() - { - $this->lastTransTime = time(); - - $stat = $this->callbackClass->onRead($this); - if ($stat !== true) - { - $this->socketClass->clearReadSchedule($this->sockInt); - } - - return $stat; - } - - private function onWrite() - { - $this->socketClass->clearWriteSchedule($this->sockInt); - $this->lastTransTime = time(); - $this->callbackClass->onWrite($this); - return false; - } - - private function onAccept() - { - //Get the sockInt from the socketClass - $newSockInt = $this->socketClass->hasAccepted($this->sockInt); - - if ($newSockInt === false) - { - //False alarm.. just ignore it. - return false; - } - - //Create a new connection object for the new socket connection, then return it to onAccept - //We must assume that onAccept will handle the connection object. Otherwise it'll die, and the - //connection will be orphaned. - - $newConn = new connection(null, null, 0); - $newConn->setSocketClass($this->socketClass); - $newConn->setIrcClass($this->ircClass); - $newConn->setCallbackClass($this->callbackClass); //Can be overwritten in the onAccept function - $newConn->setTimerClass($this->timerClass); - $newConn->listen(); - //We don't need to call init(), we're already setup. - - //Setup our connection transmission timeout thing. - if ($this->transTimeout > 0) - { - $this->timerClass->addTimer(irc::randomHash(), $newConn, "transTimeout", "", $this->transTimeout); - } - - $newConn->setTransTimeout($this->transTimeout); - - //Set handler for our new sockInt to new connection class - $this->socketClass->setHandler($newSockInt, $this->ircClass, $newConn, "handle"); - - //Set our new sockInt - $newConn->setSockInt($newSockInt); - - //Call our callback function for accepting with old object, and new object. - $this->callbackClass->onAccept($this, $newConn); - return false; - } - - private function onDead() - { - if ($this->connected == true) - { - $this->setError("Connection is dead"); - } - else - { - $this->setError("Could not connect: " . $this->socketClass->getSockStringError($this->sockInt)); - } - $this->callbackClass->onDead($this); - return false; - } - - /* Error handling routines */ - - private function setError($msg) - { - $this->error = true; - $this->errorMsg = $msg; - } - - public function getError() - { - return $this->error; - } - - public function getErrorMsg() - { - return $this->errorMsg; - } - -} - -?> diff --git a/ircbot/databases/ini.php b/ircbot/databases/ini.php deleted file mode 100644 index a2712f8..0000000 --- a/ircbot/databases/ini.php +++ /dev/null @@ -1,515 +0,0 @@ - ini-file database module -| > Module written by Manick -| > Module Version Number: 2.2.1 alpha -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class ini { - - private $filename; - private $error; - private $ini = array(); - private $numSections; - - //used in isMatched() - private $search; - private $searchParts; - - - //Load ini into memory - public function __construct($filename) - { - $this->error = false; - $this->filename = $filename; - - $filePtr = @fopen($filename, "r"); - - if ($filePtr === false) - { - $filePtr = @fopen($filename, "a"); - - if ($filePtr === false) - { - $this->error = true; - return; - } - else - { - fclose($filePtr); - return; - } - } - - $fileData = ""; - - while (!feof($filePtr)) - { - $fileData .= fread($filePtr, 4096); - } - - fclose($filePtr); - - $fileData = str_replace("\r", "", $fileData); - - $lines = explode("\n", $fileData); - - $currSection = ""; - $this->numSections = 0; - - foreach($lines AS $line) - { - $line = trim($line); - - $offsetA = strpos($line, "["); - $offsetB = strpos($line, "]"); - - if ($offsetA === 0) - { - $currSection = substr($line, 1, $offsetB - 1); - $this->numSections++; - $this->ini[$currSection] = array(); - } - else - { - if ($currSection != "") - { - $offsetC = strpos($line, "="); - - if ($offsetC !== false) - { - $var = trim(substr($line, 0, $offsetC)); - $val = substr($line, $offsetC + 1); - - if ($var != "") - { - $this->ini[$currSection][$var] = $val; - } - } - else - { - $this->ini[$currSection][$line] = true; - } - } - } - } - } - - public function getError() - { - return $this->error; - } - - public function getSections() - { - $sections = array(); - - if ($this->numSections == 0) - { - return $sections; - } - - foreach ($this->ini AS $section => $vals) - { - $sections[] = $section; - } - - return $sections; - } - - public function getVars($section) - { - if (!isset($this->ini[$section])) - { - return false; - } - - return $this->ini[$section]; - } - - public function sectionExists($section) - { - if (isset($this->ini[$section]) && is_array($this->ini[$section])) - { - return true; - } - return false; - } - - public function getSection($section) - { - return $this->getVars($section); - } - - public function randomSection($num = 1) - { - if ($this->numSections == 0 || $num < 1 || $num > $this->numSections) - { - return false; - } - - return array_rand($this->ini, $num); - } - - public function randomVar($section, $num = 1) - { - if (!isset($this->ini[$section])) - { - return false; - } - - $count = count($this->ini[$section]); - - if ($count == 0 || $num < 1 || $num > $count) - { - return false; - } - - return array_rand($this->ini[$section], $num); - } - - - public function searchSections($search, $type = EXACT_MATCH) - { - $results = array(); - - if (trim($search) == "") - { - return $results; - } - - if ($this->numSections == 0) - { - return; - } - - foreach($this->ini AS $section => $vars) - { - if ($this->isMatched($search, $section, $type)) - { - $results[] = $section; - } - } - - return $results; - } - - public function searchVars($section, $search, $type = EXACT_MATCH) - { - $results = array(); - - if (trim($search) == "") - { - return $results; - } - - if (!isset($this->ini[$section])) - { - return $results; - } - - if ($this->numSections == 0) - { - return; - } - - if (count($this->ini[$section]) == 0) - { - return $results; - } - - foreach($this->ini[$section] AS $var => $val) - { - if ($this->isMatched($search, $var, $type)) - { - $results[] = $var; - } - } - - return $results; - } - - public function searchSectionsByVar($var, $search, $type = EXACT_MATCH) - { - $results = array(); - - if ($this->numSections == 0) - { - return $results; - } - - foreach($this->ini AS $section => $vars) - { - if (isset($vars[$var])) - { - if ($this->isMatched($search, $vars[$var], $type)) - { - $results[] = $section; - } - } - } - - return $results; - - } - - public function searchVals($section, $search, $type = EXACT_MATCH) - { - $results = array(); - - if (trim($search) == "") - { - return $results; - } - - if (!isset($this->ini[$section])) - { - return $results; - } - - if ($this->numSections == 0) - { - return; - } - - if (count($this->ini[$section]) == 0) - { - return $results; - } - - foreach($this->ini[$section] AS $var => $val) - { - if ($this->isMatched($search, $val, $type)) - { - $results[] = $var; - } - } - - return $results; - } - - private function isMatched(&$needle, &$haystack, $type = EXACT_MATCH) - { - - if ($type == EXACT_MATCH) - { - if ($haystack == $needle) - { - return true; - } - } - - if ($type == CONTAINS_MATCH) - { - if (strpos(strtolower($haystack), strtolower($needle)) !== false) - { - return true; - } - } - - if ($search != $this->search) - { - $this->searchParts = explode(chr(32), $search); - $this->search = $search; - } - - if ($type == AND_MATCH) - { - $foundAll = true; - - foreach($this->searchParts AS $part) - { - if (strpos($val, $part) === false) - { - $foundAll = false; - break; - } - } - - if ($foundAll == true) - { - return true; - } - } - else if ($type == OR_MATCH) - { - foreach($this->searchParts AS $part) - { - if (strpos($val, $part) !== false) - { - return true; - break; - } - } - } - - return false; - } - - - public function deleteSection($section) - { - if (isset($this->ini[$section])) - { - unset($this->ini[$section]); - return true; - } - - return false; - } - - public function deleteVar($section, $var) - { - if (isset($this->ini[$section])) - { - if (isset($this->ini[$section][$var])) - { - unset($this->ini[$section][$var]); - return true; - } - } - - return false; - } - - public function numSections() - { - return $this->numSections; - } - - public function numVars($section) - { - if (isset($this->ini[$section])) - { - return count($this->ini[$section]); - } - return 0; - } - - public function setIniVal($section, $var, $val) - { - if ($this->error == true) - { - return; - } - - if (!isset($this->ini[$section])) - { - $this->numSections++; - $this->ini[$section] = array(); - } - - if (strpos($var, "=") !== false) - { - return false; - } - - $this->ini[$section][$var] = $val; - - return true; - } - - public function getIniVal($section, $var) - { - if ($this->error == true) - { - return; - } - - if (isset($this->ini[$section]) - && isset($this->ini[$section][$var])) - { - return $this->ini[$section][$var]; - } - else - { - return false; - } - } - - //Update and write ini to file - public function writeIni() - { - if ($this->error == true) - { - return; - } - - if ($this->numSections == 0) - { - return; - } - - $output = ""; - - foreach ($this->ini AS $section => $vars) - { - - $output .= "[" . $section . "]\n"; - - if (count($vars)) - { - foreach ($vars AS $var => $val) - { - $output .= $var . "=" . $val . "\n"; - } - } - } - - $filePtr = fopen($this->filename, "at"); - - if ($filePtr === false) - { - $this->error = true; - return false; - } - - flock($filePtr, LOCK_EX); - - ftruncate($filePtr, 0); - - if (fwrite($filePtr, $output) === FALSE) - { - $this->error = true; - } - - flock($filePtr, LOCK_UN); - - fclose($filePtr); - - return !$this->error; - } - -} - -?> diff --git a/ircbot/databases/mysql.php b/ircbot/databases/mysql.php deleted file mode 100644 index 7ffaa3a..0000000 --- a/ircbot/databases/mysql.php +++ /dev/null @@ -1,169 +0,0 @@ - database module -| > Module written by Manick -| > Module Version Number: 2.2.0 alpha1 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class mysql { - - private $dbIndex; - private $prefix; - private $queries = 0; - private $isConnected = false; - - private $user; - private $pass; - private $database; - private $host; - private $port; - - public function __construct($host, $database, $user, $pass, $prefix, $port = 3306) - { - $this->user = $user; - $this->pass = $pass; - $this->host = $host; - $this->database = $database; - $this->port = $port; - - $db = mysql_connect($host . ":" . $port, $user, $pass); - - if (!$db) - { - return; - } - - $dBase = mysql_select_db($database, $db); - - if (!$dBase) - { - return; - } - - $this->prefix = $prefix; - $this->dbIndex = $db; - $this->isConnected = true; - } - - public function getError() - { - return (@mysql_error($this->dbIndex)); - } - - public function isConnected() - { - return $this->isConnected; - } - - //Call by reference switched to function declaration, 05/13/05 - private function fixVar($id, &$values) - { - return mysql_real_escape_string($values[intval($id)-1], $this->dbIndex); - } - - public function query($query, $values = array()) - { - - if (!is_array($values)) - $values = array($values); - - $query = preg_replace('/\[([0-9]+)]/e', "\$this->fixVar(\\1, \$values)", $query); - - $this->queries++; - - $data = mysql_query($query, $this->dbIndex); - - if (!$data) - { - return false; - } - - return $data; - } - - - public function queryFetch($query, $values = array()) - { - - if (!is_array($values)) - $values = array($values); - - $query = preg_replace('/\[([0-9]+)]/e', "\$this->fixVar(\\1, &\$values)", $query); - - $this->queries++; - - $data= mysql_query($query, $this->dbIndex); - - if (!$data) - { - return false; - } - - return mysql_fetch_array($data); - } - - - public function fetchArray($toFetch) - { - return mysql_fetch_array($toFetch); - } - - public function fetchRow($toFetch) - { - return mysql_fetch_row($toFetch); - } - - public function close() - { - @mysql_close($this->dbIndex); - } - - public function lastID() - { - return mysql_insert_id(); - } - - public function numRows($toFetch) - { - return mysql_num_rows($toFetch); - } - - public function numQueries() - { - return $this->queries; - } - -} - -?> - diff --git a/ircbot/databases/postgre.php b/ircbot/databases/postgre.php deleted file mode 100644 index 1bb3e51..0000000 --- a/ircbot/databases/postgre.php +++ /dev/null @@ -1,162 +0,0 @@ - database module -| > Module written by Manick -| > Module Version Number: 2.1.1 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class postgre { - - private $dbIndex; - private $prefix; - private $queries = 0; - private $isConnected = false; - private $error; - - public function __construct($host, $database, $user, $pass, $prefix, $port = 5432) - { - $this->error = true; - - $connect = "host=" . $host . " ". - "port=" . $port . " ". - "dbname=" . $database . " ". - "user=" . $user . " ". - "password=" . $pass; - - $this->error = pg_connect($connect); - - if (!$this->error) - { - return; - } - - $this->prefix = $prefix; - $this->dbIndex = $this->error; - $this->isConnected = true; - } - - public function getError() - { - return $this->error === false ? true : false; - //return (@mysql_error($this->dbIndex)); - } - - public function isConnected() - { - return $this->isConnected; - } - - private function fixVar($id, $values) - { - return pg_escape_string($values[intval($id)-1]); - } - - public function query($query, $values = array()) - { - - if (!is_array($values)) - $values = array($values); - - $query = preg_replace('/\[([0-9]+)]/e', "\$this->fixVar(\\1, &\$values)", $query); - - $this->queries++; - - $data = pg_query($this->dbIndex, $query); - - if (!$data) - { - $this->error = $data; - return false; - } - - return $data; - } - - - public function queryFetch($query, $values = array()) - { - - if (!is_array($values)) - $values = array($values); - - $query = preg_replace('/\[([0-9]+)]/e', "\$this->fixVar(\\1, &\$values)", $query); - - $this->queries++; - - $data = pg_query($query, $this->dbIndex); - - if (!$data) - { - $this->error = false; - return false; - } - - return pg_fetch_array($data); - } - - - public function fetchArray($toFetch) - { - return pg_fetch_array($toFetch); - } - - public function fetchRow($toFetch) - { - return pg_fetch_row($toFetch); - } - - public function close() - { - @pg_close($this->dbIndex); - } - - public function lastID() - { - //ehhh. don't use this. - return null; - } - - public function numRows($toFetch) - { - return pg_num_rows($toFetch); - } - - public function numQueries() - { - return $this->queries; - } - -} - -?> - diff --git a/ircbot/databases/postgres.php b/ircbot/databases/postgres.php deleted file mode 100644 index 92264c2..0000000 --- a/ircbot/databases/postgres.php +++ /dev/null @@ -1,148 +0,0 @@ - database module -| > Module written by Manick -| > Module Version Number: 2.1.1 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -// *** Modified by Nemesis128_at_atarax_dot_org - -class postgresql { - - private $dbRes; - private $prefix; - private $numQueries = 0; - private $isConnected = false; - private $error = false; - - private $user; - private $pswd; - private $dbase; - private $host; - private $port; - - public function __construct ($user,$pswd,$dbase,$prefix,$host = null,$port = 5432) { - - $this->user = $user; - $this->pswd = $pswd; - $this->dbase = $dbase; - $this->prefix = $prefix; - $this->host = $host; - $this->port = $port; - - $conn_str = ''; - - if (!is_null($host)) { // connect thru TCP/IP - $conn_str .= 'host='.$host; - $conn_str .= ' port='.$port; - } // else thru intern sockets - $conn_str .= ' user='.$user; - $conn_str .= ' password='.$pswd; - $conn_str .= ' dbname='.$dbase; - - $this->dbRes = pg_connect($conn_str); - - if (!is_resource($this->dbRes)) { - $this->error = 'PgSQL Connection error'; - return; - } - - $this->isConnected = true; - } - - public function getError () { - if ($this->error) { - $err = $this->error."\n\n"; - return ($err.@pg_last_error($this->dbIndex)); - } else { - return null; - } - } - - public function isConnected () { - return $this->isConnected; - } - - public static function esc ( $var ) { - return pg_escape_string ( $var ); - } - - public function query ( $query_str ) { - - if (pg_connection_status($this->dbRes) === PGSQL_CONNECTION_BAD) { - if (!pg_connection_reset($this->dbRes)) { - $this->error = 'Connection lost'; - $this->isConnected = false; - return false; - } - } - - $this->numQueries++; - - $res = @pg_query($this->dbRes,$query_str); - - if (!$res) { - $this->error = 'Query failed: '.pg_last_error().' ('.$query_str.')'; - return false; - } - - return $res; - } - - public function fetchArray ( $toFetch ) { - return pg_fetch_assoc($toFetch); - } - - public function fetchObject ( $toFetch ) { - return pg_fetch_object($toFetch); - } - - public function fetchRow ( $toFetch ) { - return pg_fetch_row($toFetch); - } - - public function numRows ( $toFetch ) { - return pg_num_rows($toFetch); - } - - public function numQueries () { - return $this->numQueries; - } - - public function close () { - @pg_close($this->dbRes); - } - -} - -?> \ No newline at end of file diff --git a/ircbot/dcc.php b/ircbot/dcc.php deleted file mode 100644 index 5ec3282..0000000 --- a/ircbot/dcc.php +++ /dev/null @@ -1,579 +0,0 @@ - dcc module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class dcc { - - private $dccList = array(); //holds all connected sockets - private $dccChangedList = array(); - private $dccChangedCount = 0; - - private $fileDlCount = 0; - private $fileUlCount = 0; - private $chatCount = 0; - - //Classes - private $timerClass; - private $socketClass; - private $ircClass; - private $parserClass; - - //Bytes Transferred - private $bytesUp = 0; - private $bytesDown = 0; - - //Process Queue - private $procQueue; - - public function __construct() - { - // do nothing... - } - - public function setProcQueue($class) - { - $this->procQueue = $class; - } - - public function setIrcClass($class) - { - $this->ircClass = $class; - } - - public function setParserClass($class) - { - $this->parserClass = $class; - $this->parserClass->setDccClass($this); - } - - public function setSocketClass($class) - { - $this->socketClass = $class; - } - - public function setTimerClass($class) - { - $this->timerClass = $class; - } - - public function getDownloadCount() - { - return $this->fileDlCount; - } - - public function getUploadCount() - { - return $this->fileUlCount; - } - - public function getChatCount() - { - return $this->chatCount; - } - - public function closeAll() - { - foreach ($this->dccList AS $dcc) - { - $dcc->disconnect("Owner Requsted Close"); - } - } - - public function addBytesUp($num) - { - $this->bytesUp += $num; - } - - public function addBytesDown($num) - { - $this->bytesDown += $num; - } - - public function getBytesDown() - { - return $this->bytesDown; - } - - public function getBytesUp() - { - return $this->bytesUp; - } - - - public function getDcc($someDcc) - { - if (isset($this->dccList[$someDcc])) - { - return $this->dccList[$someDcc]; - } - - return false; - } - - - public function dccInform($data, $from = null) - { - foreach ($this->dccList AS $dcc) - { - if ($dcc->type == CHAT && $dcc->verified == true && $dcc->isAdmin == true) - { - if ($from != null) - { - if ($dcc->sockInt != $from->sockInt) - { - $dcc->dccSend($data); - } - } - else - { - $dcc->dccSend($data); - } - - } - - } - } - - //Works in conjunction with $oldConn->connected - public function accepted($oldConn, $newConn) - { - $sockInt = $oldConn->getSockInt(); - $hasAccepted = $newConn->getSockInt(); - - $dcc = $this->dccList[$sockInt]; - $this->dccList[$hasAccepted] = $dcc; - $dcc->status = DCC_CONNECTED; - $dcc->sockInt = $hasAccepted; - unset($this->dccList[$sockInt]); - } - - //CheckDccTimeout function - public function checkDccTimeout($dcc) - { - if (!is_object($dcc) || $dcc->removed == true) - { - return false; - } - - if ($dcc->status != DCC_LISTENING) - { - return false; - } - - switch ($dcc->timeOutLevel) - { - case 0: - $dcc->timeOutLevel++; - break; - case 1: - $dcc->timeOutLevel++; - $this->ircClass->notice($dcc->nick, "You have a DCC session pending. Set your client to connect. 60 seconds before timeout.", 1); - break; - case 2: - $dcc->timeOutLevel++; - $this->ircClass->notice($dcc->nick, "You have a DCC session pending. Set your client to connect. 30 seconds before timeout.", 1); - break; - case 3: - $dcc->timeOutLevel = 0; - $dcc->disconnect("DCC Session timed out (90 Seconds)"); - return false; - break; - default: - break; - } - - return true; - - } - - public function getDccList() - { - return $this->dccList; - } - - private function removeDcc($dcc) - { - $sockInt = $dcc->sockInt; - unset($this->dccList[$sockInt]); - } - - public function dccSend($to, $data) - { - if (($len = $this->socketClass->sendSocket($to->sockInt, $data)) === false) - { - $to->disconnect(); - } - return $len; - } - - - private function highestId() - { - $highest = 0; - - foreach ($this->dccList AS $index => $dcc) - { - $highest = ($dcc->id > $highest ? $dcc->id : $highest); - } - - return $highest + 1; - } - - - public function addChat($nick, $host, $port, $admin, $handler, $fromTimer = false) - { - $lnick = irc::myStrToLower($nick); - - foreach ($this->dccList AS $index => $dcc) - { - if ($dcc->type == CHAT) - { - if (irc::myStrToLower($dcc->nick) == $lnick) - { - $dcc->disconnect(); - break; - } - } - } - - $reverse = false; - - if ($this->ircClass->getClientConf("mircdccreverse") != "" && $fromTimer == false) - { - $port = intval($this->ircClass->getClientConf("mircdccreverse")); - if ($port == 0) - { - return NULL; - } - - $args = new argClass; - - $args->arg1 = $nick; - $args->arg2 = $host; - $args->arg3 = $port; - $args->arg4 = $admin; - $args->arg5 = $handler; - $args->arg7 = time(); - $args->arg8 = CHAT; - - $this->ircClass->notice($nick, "DCC: NOTICE: This server is using the mIRC Chat Server Protocol. Please use ' /dccserver +c on " . $this->ircClass->getClientConf("mircdccreverse") . " ' to chat with me! Starting 6 second delay...", 0); - - $this->ircClass->sendRaw("WHOIS " . $nick); - $this->timerClass->addTimer(irc::randomHash(), $this, "reverseTimer", $args, 6, false); - return; - } - - if ($fromTimer == true) - { - $reverse = DCC_REVERSE; // using mIRC dcc reverse protocol - } - - if ($host == NULL || $port == NULL) - { - $conn = new connection(null, null, 0); - $listening = true; - $status = DCC_LISTENING; - } - else - { - $conn = new connection($host, $port, CONNECT_TIMEOUT); - $listening = false; - $status = DCC_CONNECTING; - } - - $conn->setSocketClass($this->socketClass); - $conn->setIrcClass($this->ircClass); - $conn->setCallbackClass($this); - $conn->setTimerClass($this->timerClass); - $port = $conn->init(); - - if ($conn->getError()) - { - $this->ircClass->log("Start Chat Error: " . $conn->getErrorMsg()); - return false; - } - - $sockInt = $conn->getSockInt(); - - $this->chatCount++; - - $id = $this->highestId(); - - $chat = new chat($id, $nick, $admin, $sockInt, $host, $port, $handler, $reverse); - $chat->setIrcClass($this->ircClass); - $chat->setDccClass($this); - $chat->setParserClass($this->parserClass); - $chat->setSocketClass($this->socketClass); - $chat->setTimerClass($this->timerClass); - $chat->connection = $conn; - $chat->status = $status; - $chat->removed = false; - - $this->dccList[$sockInt] = $chat; - - $chat->initialize(); - - $conn->setCallbackClass($chat); - - if ($listening == true) - { - $this->timerClass->addTimer(irc::randomHash(), $this, "checkDccTimeout", $chat, 30, true); - } - else - { - $conn->connect(); - } - - return $port; - } - - public function addFile($nick, $host, $port, $type, $filename, $size, $fromTimer = false) // <-- ignore fromTimer, it is sent by reverseTimer() above - { - $reverse = false; - - if ($this->ircClass->getClientConf("mircdccreverse") != "" && $fromTimer == false && $type != DOWNLOAD) - { - $port = intval($this->ircClass->getClientConf("mircdccreverse")); - if ($port == 0) - { - return NULL; - } - - $args = new argClass; - - $args->arg1 = $nick; - $args->arg2 = $host; - $args->arg3 = $port; - $args->arg4 = $type; - $args->arg5 = $filename; - $args->arg6 = $size; - $args->arg7 = time(); - $args->arg8 = FILE; - - $this->ircClass->notice($nick, "DCC: NOTICE: This server is using the mIRC File Server Protocol. Please use ' /dccserver +s on " . $this->ircClass->getClientConf("mircdccreverse") . " ' to recieve files from me! Starting 6 second delay...", 0); - - $this->ircClass->sendRaw("WHOIS " . $nick); - $this->timerClass->addTimer(irc::randomHash(), $this, "reverseTimer", $args, 6); - return; - } - - if ($fromTimer == true) - { - $reverse = DCC_REVERSE; // using mIRC dcc reverse protocol - } - - if ($host == NULL || $port == NULL) - { - $conn = new connection(null, null, 0); - $listening = true; - $status = DCC_LISTENING; - } - else - { - $conn = new connection($host, $port, CONNECT_TIMEOUT); - $listening = false; - $status = DCC_CONNECTING; - } - - $conn->setSocketClass($this->socketClass); - $conn->setIrcClass($this->ircClass); - $conn->setCallbackClass($this); - $conn->setTransTimeout(30); - $conn->setTimerClass($this->timerClass); - $port = $conn->init(); - - if ($conn->getError()) - { - $this->ircClass->log("File transfer start error: " . $conn->getErrorMsg()); - return false; - } - - $sockInt = $conn->getSockInt(); - - $id = $this->highestId(); - - $file = new file($id, $nick, $sockInt, $host, $port, $type, $reverse); - - if ($file->transferType == UPLOAD) - { - $this->fileUlCount++; - } - else - { - $this->fileDlCount++; - } - - $file->setIrcClass($this->ircClass); - $file->setDccClass($this); - $file->setSocketClass($this->socketClass); - $file->setProcQueue($this->procQueue); - $file->setTimerClass($this->timerClass); - $file->connection = $conn; - $file->status = $status; - $file->removed = false; - - $this->dccList[$sockInt] = $file; - - $file->initialize($filename, $size); - - $conn->setCallbackClass($file); - - if ($listening == true) - { - $this->timerClass->addTimer(irc::randomHash(), $this, "checkDccTimeout", $file, 30, true); - } - - if ($reverse == true) - { - $conn->connect(); - } - - return $port; - } - - - public function alterSocket($sockInt, $level, $opt, $val) - { - return $this->socketClass->alterSocket($sockInt, $level, $opt, $val); - } - - - public function reverseTimer($args) - { - $memData = $this->ircClass->getUserData($args->arg1); - - if ($memData == NULL || ($memData->host == "" || $memData->host == NULL)) - { - $this->ircClass->notice($args->arg1, "DCC: ERROR: Couldn't resolve your hostname. Try again?"); - } - else - { - - if ($args->arg8 == FILE) - { - $this->addFile( $args->arg1, - $memData->host, - $this->ircClass->getClientConf("mircdccreverse"), - $args->arg4, - $args->arg5, - $args->arg6, - true); - } - else - { - $this->addChat( $args->arg1, - $memData->host, - $this->ircClass->getClientConf("mircdccreverse"), - $args->arg4, - $args->arg5, - true); - } - } - - return false; - } - - public function sendFile($nick, $file) - { - return $this->addFile($nick, null, null, UPLOAD, $file, NULL); - } - - - public function dccResume($port, $size) - { - foreach ($this->dccList AS $dcc) - { - if ($dcc->type == FILE) - { - if ($dcc->port == $port) - { - $dcc->resume($size); - break; - } - } - } - } - - public function dccAccept($port) - { - foreach ($this->dccList AS $dcc) - { - if ($dcc->type == FILE) - { - if ($dcc->port == $port) - { - $dcc->accepted(); - break; - } - } - } - } - - public function disconnect($dcc) - { - - switch ($dcc->type) - { - case CHAT: - $this->chatCount--; - break; - case FILE: - switch($dcc->transferType) - { - case UPLOAD: - $this->fileUlCount--; - break; - case DOWNLOAD: - $this->fileDlCount--; - break; - } - break; - default: - break; - } - - $dcc->removed = true; - - $dcc->connection->disconnect(); - $this->removeDcc($dcc); - - return true; - } - - -} - -?> diff --git a/ircbot/defines.php b/ircbot/defines.php deleted file mode 100644 index 15d283e..0000000 --- a/ircbot/defines.php +++ /dev/null @@ -1,314 +0,0 @@ - defines module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -// Debug Mode -define('DEBUG', 1); - -// PID file -define('PID', config::$main['cs_path'] . "/ircbot.pid"); - -// OS Type (windows/unix/linux/freebsd/unknown/auto) -define('OS', 'auto'); - -//YOU SHOULD NOT HAVE TO EDIT BELOW THIS POINT UNLESS YOU SPECIFY "unknown" AS OS! - -if (OS == "auto") -{ - switch (PHP_OS) - { - case "Windows NT": - $OS = "windows"; - break; - case "Linux": - $OS = "linux"; - break; - case "FreeBSD": - $OS = "freebsd"; - break; - case "Unix": - $OS = "unix"; - break; - //Thx OrochiTux for below - case "Darwin": - $OS = "freebsd"; - break; - default: - $OS = "windows"; - break; - } -} -else -{ - $OS = OS; -} - -if ($OS == 'unknown') -{ - define('EAGAIN', 0); /* Try again */ - define('EISCONN', 0); /* Transport endpoint is already connected */ - define('EALREADY', 0); /* Operation already in progress */ - define('EINPROGRESS', 0); /* Operation now in progress */ -} -else if ($OS == 'windows') -{ - //http://developer.novell.com/support/winsock/doc/appenda.htm - define('EAGAIN', 10035); //EWOULDBLOCK.. kinda like EAGAIN in windows? - define('EISCONN', 10056); /* Transport endpoint is already connected */ - define('EALREADY', 10037); /* Operation already in progress */ - define('EINPROGRESS', 10036); /* Operation now in progress */ -} -else if ($OS == 'freebsd') -{ - //Thanks to ryguy@efnet - ///usr/include/errno.h (freebsd) - define('EAGAIN', 35); /* Try again */ - define('EISCONN', 56); /* Transport endpoint is already connected */ - define('EALREADY', 37); /* Operation already in progress */ - define('EINPROGRESS', 36); /* Operation now in progress */ -} -else if ($OS == 'linux') -{ - ///usr/include/sys/errno.h (sparc) - define('EAGAIN', 11); /* Try again */ - define('EISCONN', 106); /* Transport endpoint is already connected */ - define('EALREADY', 114); /* Operation already in progress */ - define('EINPROGRESS', 115); /* Operation now in progress */ -} -else if ($OS == 'unix') -{ - ///usr/include/asm/errno.h (mandrake 9.0) - define('EAGAIN', 11); /* Try again */ - define('EISCONN', 133); /* Transport endpoint is already connected */ - define('EALREADY', 149); /* Operation already in progress */ - define('EINPROGRESS', 150); /* Operation now in progress */ -} - -// Version Definition -define('VERSION', '2.2.1'); -define('VERSION_DATE', '04/08/06'); - -// Timer declarations -define('NICK_CHECK_TIMEOUT', 120); //seconds -define('CHAN_CHECK_TIMEOUT', 60); //seconds -define('PING_TIMEOUT', 130); //seconds (check every 130 seconds if we're still connected) - -// Parser definitions -define('MAX_ARGS', 4); - -// Status definitions -define('STATUS_IDLE', 0); -define('STATUS_ERROR', 1); -define('STATUS_CONNECTING', 2); -define('STATUS_CONNECTED', 3); -define('STATUS_CONNECTED_SENTREGDATA', 4); -define('STATUS_CONNECTED_REGISTERED', 5); - -// Constant Definitions -define('ERROR_TIMEOUT', 60); -define('CONNECT_TIMEOUT', 45); -define('REGISTRATION_TIMEOUT', 60); -define('TIMEOUT_CHECK_TIME', 85); //85 - -//Constants for Channel Modes -define('BY_MASK', 0); -define('BY_STRING', 1); -define('BY_INT', 2); -define('BY_NONE', 3); - -//Used with $ircClass->parseMode -define('USER_MODE', 0); -define('CHANNEL_MODE', 1); - -//Random Vars -define('STATUS_JUST_BANNED', 1); -define('STATUS_ALREADY_BANNED', 2); -define('STATUS_NOT_BANNED', 3); - -//Socket Class defines -define('SOCK_DEAD', 1); -define('SOCK_CONNECTING', 2); -define('SOCK_LISTENING', 3); -define('SOCK_ACCEPTED', 4); -define('SOCK_ACCEPTING', 5); -define('SOCK_CONNECTED', 6); -define('HIGHEST_PORT', 1000); // this is tcpRangeStart + HIGHEST_PORT - -//DCC Class defines -define('FILE', 0); -define('CHAT', 1); -define('DCC_WAITING', 3); -define('DCC_REVERSE', 4); -define('DCC_CONNECTING', 0); -define('DCC_CONNECTED', 1); -define('DCC_LISTENING', 2); - -//Connection class defines -define('CONN_READ', 0); -define('CONN_WRITE', 1); -define('CONN_ACCEPT', 2); -define('CONN_CONNECT', 3); -define('CONN_DEAD', 4); -define('CONN_CONNECT_TIMEOUT', 5); -define('CONN_TRANSFER_TIMEOUT', 6); - -//Parser Class defines -define('BRIGHT', chr(3) . "13"); -define('DARK', chr(3) . "03"); -define('NORMAL', chr(16)); -define('BOLD', chr(2)); -define('UNDERLINE', chr(31)); -define('PRIV', 1); -define('DCC', 2); - -//File Class defines -define('UPLOAD', 0); -define('DOWNLOAD', 1); - -//Used with $ircClass->addQuery -define('QUERY_SUCCESS', 0); -define('QUERY_ERROR', 1); - -//Used in ini -define('EXACT_MATCH', 0); -define('AND_MATCH', 1); -define('OR_MATCH', 2); -define('CONTAINS_MATCH', 3); - -//Used in socket class to keep track of sockets - -class socketInfo { - public $socket; - public $status; - public $readQueue; - public $readLength; - public $writeQueue; - public $writeLength; - public $host; - public $port; - public $newSockInt; - public $listener; - public $owner; - public $class; - public $func; - public $readScheduled; //Used so we don't add infinite queues to the process queue. - public $writeScheduled; -} - -//Channel and Username Linked List (Links) Definitions - -class channelLink { - public $name; - public $count; - public $memberList = array(); - public $banList = array(); - public $whoComplete; - public $banComplete; - public $modes; - public $created; - public $topic; - public $topicBy; -} - -class memberLink { - public $nick; - public $realNick; - public $host; - public $ident; - public $banned; - public $bantime; - public $status; - public $ignored; -} - -// Used in timer class - -class timer { - public $name; - public $class; - public $args; - public $interval; - public $lastTimeRun; - public $nextRunTime; - public $func; -} - -class usageLink { - public $isBanned; - public $timeBanned; - public $lastTimeUsed; - public $timesUsed; -} - - -// Useful for sending arguments with timers -class argClass -{ - public $arg1; - public $arg2; - public $arg3; - public $arg4; - public $arg5; - public $arg6; - public $arg7; - public $arg8; - public $timer; -} - -// Used to instantiate a bot -class botClass { - public $timerClass; - public $ircClass; - public $dccClass; - public $parserClass; - public $socketClass; - public $configFilename; - public $db; - public $config; -} - -// Used with processQueue -class queueItem { - public $owner; //IRC Class of owner - public $callBack_class; //CALL BACK class/function to use - public $callBack_function; - public $nextRunTime; //The next getMicroTime() time to run - public $removed; - public $next; - public $prev; -} - -?> diff --git a/ircbot/error.php b/ircbot/error.php deleted file mode 100644 index 789b7fb..0000000 --- a/ircbot/error.php +++ /dev/null @@ -1,107 +0,0 @@ - error module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class ConnectException extends Exception { - - private $exceptionTime = 0; - - function __construct($message) - { - parent::__construct($message); - $this->exceptionTime = time(); - } - - function getTime() - { - return $this->exceptionTime; - } -} - - -class SendDataException extends Exception { - - private $exceptionTime = 0; - - function __construct($message) - { - parent::__construct($message); - $this->exceptionTime = time(); - } - - function getTime() - { - return $this->exceptionTime; - } -} - - - -class ConnectionTimeout extends Exception { - - private $exceptionTime = 0; - - function __construct($message) - { - parent::__construct($message); - $this->exceptionTime = time(); - } - - function getTime() - { - return $this->exceptionTime; - } -} - - - -class ReadException extends Exception { - - private $exceptionTime = 0; - - function __construct($message) - { - parent::__construct($message); - $this->exceptionTime = time(); - } - - function getTime() - { - return $this->exceptionTime; - } -} - -?> diff --git a/ircbot/file.php b/ircbot/file.php deleted file mode 100644 index 0b7f84c..0000000 --- a/ircbot/file.php +++ /dev/null @@ -1,663 +0,0 @@ - dcc chat module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class file { - - /* Chat specific Data */ - public $id; - public $status; - public $sockInt; - public $timeConnected; - public $readQueue; - public $port; - public $dccString; - public $type; - public $transferType; - public $nick; - public $timeOutLevel; - public $removed; - public $connection; - - public $reverse; // reverse dcc? - private $handShakeSent; - private $handShakeTime; - - public $filename; - public $filenameNoDir; - public $filePointer; - public $filesize; - public $bytesTransfered; - public $resumedSize; - public $completed; - public $reportedRecieved; - - public $connectHost; - - //private $resumed; - private $started; - - private $sendQueue; - private $sendQueueCount; - - //keep track of speed; - private $speed_sec_add; - public $speed_lastavg; - private $speed_starttime; - - /* Classes */ - private $dccClass; - private $ircClass; - private $socketClass; - private $procQueue; - private $timerClass; - - /* Constructor */ - public function __construct($id, $nick, $sockInt, $host, $port, $type, $reverse) - { - $this->id = $id; - $this->nick = $nick; - $this->sockInt = $sockInt; - $this->connectHost = $host; - $this->port = $port; - $this->transferType = $type; - $this->filesize = 0; - $this->bytesTransfered = 0; - $this->resumedSize = 0; - $this->started = false; - $this->status = DCC_WAITING; - $this->reverse = $reverse; - $this->handShakeSent = false; - - $this->speed_sec_add = 0; - $this->speed_lastavg = 0; - $this->speed_starttime = 0; - - if ($type == UPLOAD) - { - $this->dccString = "DCC UPLOAD[".$this->id."]: "; - } - else - { - $this->dccString = "DCC DOWNLOAD[".$this->id."]: "; - } - - } - - public function setProcQueue($class) - { - $this->procQueue = $class; - } - - public function setSocketClass($class) - { - $this->socketClass = $class; - } - - public function setIrcClass($class) - { - $this->ircClass = $class; - } - - public function setTimerClass($class) - { - $this->timerClass = $class; - } - - public function setDccClass($class) - { - $this->dccClass = $class; - } - - public function dccSend($data) - { - return $this->dccClass->dccSend($this, $data); - } - - public function disconnect($msg = "") - { - - $msg = str_replace("\r", "", $msg); - $msg = str_replace("\n", "", $msg); - - if ($this->started == true) - { - fclose($this->filePointer); - } - - if ($msg != "") - { - $this->dccClass->dccInform($this->dccString . "DCC session ended with " . $this->nick . " (" . $msg . ")", $this); - $this->ircClass->notice($this->nick, "DCC session ended: " . $msg, 1); - } - else - { - $this->dccClass->dccInform($this->dccString . "DCC session ended with " . $this->nick, $this); - } - - $this->status = false; - - $this->dccClass->disconnect($this); - - $this->connection = null; - - return true; - } - - function xferUpload() - { - - while ($this->readQueue != "") - { - $unsignedLong = substr($this->readQueue, 0, 4); - - if (strlen($unsignedLong) < 4) - { - break; - } - - $sizeArray = unpack("N", $unsignedLong); - - $this->reportedRecieved = $sizeArray[1]; - - $this->readQueue = substr($this->readQueue, 4); - } - - if ($this->completed == 1) - { - if ($this->reportedRecieved >= $this->filesize) - { - $avgspeed = ""; - if ($this->speed_lastavg != 0) - { - $size = irc::intToSizeString($this->speed_lastavg); - $avgspeed = " (" . $size . "/s)"; - } - - $totalTime = $this->ircClass->timeFormat(time() - $this->timeConnected, "%h hrs, %m min, %s sec"); - $size = irc::intToSizeString($this->bytesTransfered - $this->resumedSize); - $this->disconnect("Transfer Completed, Sent " . $size . " in " . $totalTime . $avgspeed); - } - return; - } - - if ($this->status != DCC_CONNECTED) - { - return; - } - - if ($this->socketClass->hasWriteQueue($this->sockInt)) - { - return; - } - - if ($this->bytesTransfered >= $this->filesize) - { - $this->completed = 1; - return; - } - - if (time() >= $this->speed_starttime + 3) - { - $this->speed_lastavg = $this->speed_sec_add / 3.0; - $this->speed_sec_add = 0; - $this->speed_starttime = time(); - } - - if (!is_resource($this->filePointer)) - { - $this->disconnect("File pointer is not a resource"); - return; - } - - for ($i = 0; $i < 30; $i++) - { - if (($data = fread($this->filePointer, 4096)) === false) - { - $this->disconnect("Read error: Could not access file"); - return; - } - - $this->dccSend($data); - - $dataSize = strlen($data); - - $this->bytesTransfered += $dataSize; - $this->dccClass->addBytesUp($dataSize); - $this->speed_sec_add += $dataSize; - - if ($this->socketClass->hasWriteQueue($this->sockInt)) - { - break; - } - } - - } - - function xferDownload() - { - - if ($this->status != DCC_CONNECTED) - { - return; - } - - $readQueueSize = strlen($this->readQueue); - - if ($readQueueSize <= 0) - { - return; - } - - if (fwrite($this->filePointer, $this->readQueue, $readQueueSize) === false) - { - $this->disconnect("Write error: Could not access file"); - } - - $this->speed_sec_add += $readQueueSize; - $this->dccClass->addBytesDown($readQueueSize); - $this->bytesTransfered += $readQueueSize; - $this->readQueue = ""; - - $this->dccSend(pack("N", $this->bytesTransfered)); - - if ($this->bytesTransfered >= $this->filesize) - { - $avgspeed = ""; - if ($this->speed_lastavg != 0) - { - $size = irc::intToSizeString($this->speed_lastavg); - $avgspeed = " (" . $size . "/s)"; - } - - $totalTime = $this->ircClass->timeFormat(time() - $this->timeConnected, "%h hrs, %m min, %s sec"); - $size = irc::intToSizeString($this->bytesTransfered - $this->resumedSize); - $this->disconnect("Transfer Completed, Recieved " . $size . " in " . $totalTime . $avgspeed); - } - - if (time() >= $this->speed_starttime + 3) - { - $this->speed_lastavg = $this->speed_sec_add / 3.0; - $this->speed_sec_add = 0; - $this->speed_starttime = time(); - } - } - - - private function doHandShake() - { - $this->dccSend("120 ".$this->ircClass->getNick()." ".$this->filesize." ".$this->filenameNoDir."\n"); - $this->handShakeSent = true; - $this->timerClass->addTimer(irc::randomHash(), $this, "handShakeTimeout", "", 8); - } - - private function processHandShake() - { - if ($this->readQueue == "") - { - return; - } - - $response = $this->readQueue; - $this->readQueue = ""; - $responseArray = explode(chr(32), $response); - if ($responseArray[0] == "121") - { - $this->resumedSize = intval($responseArray[2]); - $this->reverse = false; - $this->onConnect($conn); - return; - } - - $this->disconnect("DCC Client Server reported error on attempt to send file"); - } - - public function handShakeTimeout() - { - if ($this->status != false) - { - if ($this->reverse == true) - { - $this->disconnect("DCC Reverse handshake timed out"); - } - } - return false; - } - - - - /* Main events */ - public function onDead($conn) - { - if ($this->completed == 1) - { - $avgspeed = ""; - if ($this->speed_lastavg != 0) - { - $size = irc::intToSizeString($this->speed_lastavg); - $avgspeed = " (" . $size . "/s)"; - } - - $totalTime = $this->ircClass->timeFormat(time() - $this->timeConnected, "%h hrs, %m min, %s sec"); - $size = irc::intToSizeString($this->bytesTransfered - $this->resumedSize); - $this->disconnect("Transfer Completed, Sent " . $size . " in " . $totalTime . $avgspeed); - } - else - { - $this->disconnect($this->connection->getErrorMsg()); - } - } - - public function onRead($conn) - { - - $this->readQueue .= $this->socketClass->getQueue($this->sockInt); - - if ($this->status == DCC_CONNECTED) - { - - if ($this->transferType == UPLOAD) - { - if ($this->reverse != false) - { - if ($this->handShakeSent != false) - { - $this->processHandShake(); - } - } - } - else - { - $this->xferDownload(); - } - } - return false; - } - - public function onWrite($conn) - { - if ($this->status == DCC_CONNECTED && $this->reverse == false) - { - $this->xferUpload(); - } - } - - public function onAccept($oldConn, $newConn) - { - $this->dccClass->accepted($oldConn, $newConn); - $this->connection = $newConn; - $oldConn->disconnect(); - $this->sockInt = $newConn->getSockInt(); - $this->onConnect($newConn); - } - - public function onTransferTimeout($conn) - { - $this->disconnect("Transfer timed out"); - } - - public function onConnectTimeout($conn) - { - $this->disconnect("Connection attempt timed out"); - } - - public function onConnect($conn) - { - $this->status = DCC_CONNECTED; - - $this->dccClass->dccInform($this->dccString . $this->nick . " connection established"); - - if ($this->reverse != false) - { - $this->doHandShake(); - return; - } - - if ($this->transferType == UPLOAD) - { - $this->dccClass->alterSocket($this->sockInt, SOL_SOCKET, SO_SNDBUF, 32768); - - $this->filePointer = fopen($this->filename, "rb"); - - if ($this->filePointer === false) - { - $this->disconnect("Error opening local file for reading"); - return; - } - - if ($this->resumedSize > 0) - { - if (fseek($this->filePointer, $this->resumedSize, SEEK_SET) == -1) - { - $this->disconnect("Error seeking to resumed file position in file"); - return; - } - } - - $this->xferUpload(); - - } - else - { - $this->dccClass->alterSocket($this->sockInt, SOL_SOCKET, SO_RCVBUF, 32768); - - $this->filePointer = fopen($this->filename, "ab"); - - $this->ircClass->notice($this->nick, "DCC: Upload connection established", 0); - - if ($this->filePointer === false) - { - $this->disconnect("Error opening local file for writing"); - return; - } - - } - - $this->started = true; - $this->speed_starttime = time(); - - } - - - public function initialize($filename, $size = 0) - { - $this->reportedRecieved = 0; - $this->completed = 0; - $this->filesize = $size; - $this->timeConnected = time(); - $this->timeOutLevel = 0; - $this->readQueue = ""; - $this->type = FILE; - - if ($this->transferType == UPLOAD) - { - $this->filename = $filename; - - if (strpos($filename, "/") !== false) - { - $filenameArray = explode("/", $filename); - $this->filenameNoDir = $filenameArray[count($filenameArray) - 1]; - } - else if (strpos($filename, "\\") !== false) - { - $filenameArray = explode("\\", $filename); - $this->filenameNoDir = $filenameArray[count($filenameArray) - 1]; - } - else - { - $this->filenameNoDir = $filename; - } - - $this->filenameNoDir = $this->cleanFilename($this->filenameNoDir); - - $this->dccClass->dccInform($this->dccString . "Initiating file transfer of (".$this->filenameNoDir.") to " . $this->nick); - - if (!$this->file_exists($this->filename)) - { - $this->disconnect("File does not exist"); - return; - } - - $fileSize = $this->filesize($this->filename); - if ($fileSize === false) - { - $this->disconnect("File does not exist"); - return; - } - - $this->filesize = $fileSize; - - - $kbSize = irc::intToSizeString($fileSize); - - if ($this->reverse == false) - { - $this->ircClass->privMsg($this->nick, "\1DCC SEND " . $this->filenameNoDir . " " . $this->ircClass->getClientIP(1) . " " . $this->port . " " . $fileSize . "\1", 0); - } - - $this->ircClass->notice($this->nick, "DCC: Sending you (\"" . $this->filenameNoDir . "\") which is " . $kbSize . " (resume supported)", 0); - - } - else - { - $uldir = $this->ircClass->getClientConf('uploaddir'); - - $lastChar = substr($uldir, strlen($uldir) - 1, 1); - - if ($lastChar != "\\" || $lastChar != "/") - { - $uldir .= "/"; - } - - $filename = $this->cleanFilename($filename); - - $this->filename = $uldir . $filename; - $this->dccClass->dccInform($this->dccString . "Initiating file transfer of (".$filename.") from " . $this->nick); - - if ($this->file_exists($this->filename)) - { - $bytesFinished = $this->filesize($this->filename); - if ($bytesFinished >= $this->filesize) - { - $this->disconnect("Connection aborted. I already have that file."); - return; - } - else - { - $this->status = DCC_WAITING; - $this->bytesTransfered = $bytesFinished; - $this->resumedSize = $bytesFinished; - $this->ircClass->privMsg($this->nick, "\1DCC RESUME file.ext " . $this->port . " " . $bytesFinished . "\1", 0); - } - return; - } - - $this->ircClass->notice($this->nick, "DCC: Upload accepted, connecting to you (" . $this->connectHost . ") on port " . $this->port . ".",0); - - - $this->status = DCC_CONNECTING; - $this->connection->connect(); - - } - - } - - public function accepted() - { - $this->status = DCC_CONNECTING; - $this->connection->connect(); - } - - public function resume($size) - { - $this->resumedSize = $size; - $this->bytesTransfered = $size; - - $resumePlace = round($size / 1000, 0); - $this->dccClass->dccInform($this->dccString . "Resumed at " . $resumePlace . "K"); - $this->ircClass->privMsg($this->nick, "\1DCC ACCEPT file.ext " . $this->port . " " . $size . "\1", 0); - } - - public static function cleanFilename($filename) - { - $filename = str_replace("..", "__", $filename); - $filename = str_replace(chr(47), "_", $filename); - $filename = str_replace(chr(92), "_", $filename); - $filename = str_replace(chr(58), "_", $filename); - $filename = str_replace(chr(63), "_", $filename); - $filename = str_replace(chr(34), "_", $filename); - $filename = str_replace(chr(62), "_", $filename); - $filename = str_replace(chr(60), "_", $filename); - $filename = str_replace(chr(124), "_", $filename); - $filename = str_replace(chr(32), "_", $filename); - - return $filename; - } - - private function file_exists($filename) - { - $fp = @fopen($filename, "rb"); - if ($fp === false) - { - return false; - } - else - { - fclose($fp); - return true; - } - } - - private function filesize($filename) - { - - $fp = @fopen($filename, "rb"); - if ($fp === false) - { - return false; - } - else - { - $fstat = fstat($fp); - fclose($fp); - return $fstat['size']; - } - - } - -} - -?> diff --git a/ircbot/function.conf b/ircbot/function.conf deleted file mode 100644 index c940125..0000000 --- a/ircbot/function.conf +++ /dev/null @@ -1,58 +0,0 @@ -;+--------------------------------------------------------------------------- -;| PHP-IRC v2.2.1 Service Release -;| ======================================================= -;| by Manick -;| (c) 2001-2006 by http://www.phpbots.org/ -;| Contact: manick@manekian.com -;| irc: #manekian@irc.rizon.net -;| ======================================== -;| Special Contributions were made by: -;| cortex -;+--------------------------------------------------------------------------- -;| > Function File -;+--------------------------------------------------------------------------- -;| > This program is free software; you can redistribute it and/or -;| > modify it under the terms of the GNU General Public License -;| > as published by the Free Software Foundation; either version 2 -;| > of the License, or (at your option) any later version. -;| > -;| > This program is distributed in the hope that it will be useful, -;| > but WITHOUT ANY WARRANTY; without even the implied warranty of -;| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;| > GNU General Public License for more details. -;| > -;| > You should have received a copy of the GNU General Public License -;| > along with this program; if not, write to the Free Software -;| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -;+--------------------------------------------------------------------------- -;| Changes -;| =======------- -;| > If you wish to suggest or submit an update/change to the source -;| > code, email me at manick@manekian.com with the change, and I -;| > will look to adding it in as soon as I can. -;+--------------------------------------------------------------------------- - -; some notes: -; the ~ operater spans definitions over multiple lines. the ; operator -; denotes a comment. it can be placed anywhere. you must escape -; your single quotes in quoted entries with a backslash \. the first -; type of every statement is explained - -; NOTE: as of 2.2.0, all function configuration was moved to specific files using -; the 'include' function. General type definitions can be found in typedefs.conf - -include typedefs.conf - -include modules/lw/lw_mod.conf -;include modules/default/priv_mod.conf -;include modules/default/dcc_mod.conf -;include modules/bad_words/bad_words.conf -;include modules/peak_mod/peak_mod.conf -;include modules/seen/seen_mod.conf -;include modules/news/news_mod.conf -;include modules/imdb/imdb_mod.conf -;include modules/quotes_ini/quote_mod.conf -;include modules/quotes_sql/quote_mod.conf -;include modules/httpd/httpd_mod.conf -;include modules/fileserver/fileserver.conf -;include modules/bash/bash_mod.conf diff --git a/ircbot/irc.php b/ircbot/irc.php deleted file mode 100644 index 432dca5..0000000 --- a/ircbot/irc.php +++ /dev/null @@ -1,2501 +0,0 @@ - irc module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class irc { - - // Config Vars - private $clientConfig = array(); - private $configFilename = ""; - // nick, realname, localhost, remotehost, ident, host, port - private $serverConfig = array(); - private $nick = ""; - private $tempNick = ""; - // only used if our nick is taken initially - private $clientIP; - private $clientLongIP; - // Above address related determined on runtime.. - private $startTime = 0; //when the bot was started - - // Status Vars - private $status = STATUS_IDLE; - private $exception; - private $reportedStatus = STATUS_IDLE; - - //Classes - private $timerClass = null; - private $socketClass = null; - private $dccClass = null; - private $parserClass = null; - - //Socket Vars - private $sockInt; //old pre 2.1.2 method - private $conn; //new 2.1.2 method - private $connectStartTime = 0; - private $lagTime = 0; - private $timeConnected = 0; - - //Queue Vars - private $textQueueTime = 0; - private $textQueue = array(); - private $textQueueLength = 0; - - /* This variable will be set when new text is sent to be sent to the irc server, its so we don't - have to call addQueue() more than once. */ - private $textQueueAdded = false; - private $modeQueueAdded = false; - - private $modeQueue = array(); - private $modeQueueLength = 0; - private $modeTimerAdded = false; - - //Stats Var - private $stats = array(); - - //Parsing Vars - private $lVars = array(); - private $modeArray; - private $prefixArray; - - //Channel and User Linked Lists - private $chanData = array(); - private $maintainChannels = array(); -/* private $chanData = null; */ - - private $usageList = array(); - - //Timers - private $timeoutTimer = 0; - private $lastPing = 0; - private $lastPingTime = 0; - private $nickTimer = 0; - private $checkChansTimer = 0; - - //Kill - private $setKill = false; - - //My process id - private $pid; - - //Process Queue - private $procQueue; - - function __construct() - { - - $this->startTime = time(); - - // Initialize the stats array - $this->stats = array( 'BYTESUP' => 0, - 'BYTESDOWN' => 0, - ); - - $this->pid = getmypid(); - - return; - - } - - public function init() - { - $this->socketClass->setTcpRange( $this->getClientConf('dccrangestart') ); - - /* Add other timers */ - $this->timerClass->addTimer("check_nick_timer", $this, "checkNick", "", NICK_CHECK_TIMEOUT); - $this->timerClass->addTimer("check_channels_timer", $this, "checkChans", "", CHAN_CHECK_TIMEOUT); - $this->timerClass->addTimer("check_ping_timeout_timer", $this, "checkPingTimeout", "", PING_TIMEOUT+1); - - /* Timer that makes sure we're connected every 1:15 minutes */ - $this->reconnect(); - //$this->timerClass->addTimer("check_connection", $this, "checkConnection", "", 75, true); - } - - public function pid() - { - return $this->pid; - } - - public function setConfig($config, $filename = "") - { - $this->clientConfig = $config; - $this->configFilename = $filename; - $this->nick = $config['nick']; - } - - public function setProcQueue($class) - { - $this->procQueue = $class; - } - - public function setDccClass($class) - { - $this->dccClass = $class; - $this->dccClass->setIrcClass($this); - } - - public function setParserClass($class) - { - $this->parserClass = $class; - $this->parserClass->setIrcClass($this); - } - - public function setSocketClass($class) - { - $this->socketClass = $class; - } - - public function setTimerClass($class) - { - $this->timerClass = $class; - } - - public function setClientConfigVar($var, $value) - { - $this->clientConfig[$this->myStrToLower($var)] = $value; - } - - public function getNick() - { - return $this->nick; - } - - public function getMaintainedChannels() - { - return $this->maintainChannels; - } - - public function getServerConf($var) - { - if (isset($this->serverConfig[$this->myStrToUpper($var)])) - { - return $this->serverConfig[$this->myStrToUpper($var)]; - } - - return ""; - } - - - public function getConfigFilename() - { - return $this->configFilename; - } - - public function getClientConf($var = "") - { - - if ($var != "") - { - if (isset($this->clientConfig[$var])) - { - return $this->clientConfig[$var]; - } - } - else - { - return $this->clientConfig; - } - - return ""; - - } - - - //debug only! - public function displayUsers() - { - $toReturn = ""; - - foreach($this->chanData AS $chanPtr) - { - - $toReturn .= $chanPtr->name . "\n"; - - foreach($chanPtr->memberList AS $memPtr) - { - $toReturn .= $memPtr->realNick . " -- "; - $toReturn .= $memPtr->status . "\n"; - } - - } - - return trim($toReturn); - } - - - - private function addMember($channel, $nick, $ident, $status, $host = "") - { - $channel = $this->myStrToLower($channel); - $realNick = trim($nick); - $nick = trim($this->myStrToLower($nick)); - - $newMember = new memberLink; - if ($host != "") - { - $newMember->host = $host; - } - $newMember->nick = $nick; - $newMember->realNick = $realNick; - $newMember->ident = $ident; - $newMember->status = $status; - - if (!isset($this->chanData[$channel])) - { - $chanPtr = new channelLink; - $chanPtr->count = 1; - $chanPtr->memberList = NULL; - $chanPtr->banComplete = 1; - $chanPtr->name = $channel; - $this->chanData[$channel] = $chanPtr; - } - else - { - $chanPtr = $this->chanData[$channel]; - - if (!isset($chanPtr->memberList[$nick])) - { - $chanPtr->count++; - } - } - - $chanPtr->memberList[$nick] = $newMember; - - return $chanPtr->count; - - } - - public function &getChannelData($channel = "") - { - - if ($channel == "") - { - return $this->chanData; - } - - $channel = $this->myStrToLower($channel); - - if (isset($this->chanData[$channel])) - { - return $this->chanData[$channel]; - } - - return NULL; - - } - - - public function setMemberData($nick, $ident, $host) - { - $nick = $this->myStrToLower($nick); - - foreach($this->chanData AS $chanPtr) - { - if (isset($chanPtr->memberList[$nick])) - { - $chanPtr->memberList[$nick]->ident = $ident; - $chanPtr->memberList[$nick]->host = $host; - } - } - - } - - - public function getUserData($user, $channel = "") - { - if ($user == "") - { - return NULL; - } - - $channel = $this->myStrToLower($channel); - $user = $this->myStrToLower($user); - - if ($channel == "") - { - foreach ($this->chanData AS $chanPtr) - { - if (isset($chanPtr->memberList[$user])) - { - return $chanPtr->memberList[$user]; - } - } - return NULL; - } - - if (isset($this->chanData[$channel])) - { - if (isset($this->chanData[$channel]->memberList[$user])) - { - return $this->chanData[$channel]->memberList[$user]; - } - return NULL; - } - } - - - - - - - private function changeMember( $channel, $oldNick, $newNick, $ident, - $newStatus, $action, $newHost = "") - { - - $channel = $this->myStrToLower($channel); - $ident = trim($ident); - $oldNick = trim($this->myStrToLower($oldNick)); - $realNick = trim($newNick); - $newNick = trim($this->myStrToLower($newNick)); - - // See if we have a valid usermode - - if ($newStatus != "") - { - if (strpos($this->getServerConf('PREFIX'), $newStatus) === false) - { - $newStatus = ""; - $action = ""; - } - } - - //Find our channel, also change user name if no channel name given - - if ($channel == "") - { - foreach($this->chanData AS $chanPtr) - { - if (isset($chanPtr->memberList[$oldNick])) - { - $memPtr = $chanPtr->memberList[$oldNick]; - - if ($newHost != "") - { - $memPtr->host = $newHost; - } - if ($ident != "") - { - $memPtr->ident = $ident; - } - $memPtr->nick = $newNick; - $memPtr->realNick = $realNick; - - $chanPtr->memberList[$newNick] = $memPtr; - unset($chanPtr->memberList[$oldNick]); - } - } - return; - } - - if (isset($this->chanData[$channel])) - { - $chanPtr = $this->chanData[$channel]; - - if (isset($chanPtr->memberList[$oldNick])) - { - $memPtr = $chanPtr->memberList[$oldNick]; - - if ($newHost != "") - { - $memPtr->host = $newHost; - } - if ($ident != "") - { - $memPtr->ident = $ident; - } - - if ($newStatus != "") - { - if ($action == "+") - { - if (strpos($memPtr->status, $newStatus) === false) - { - $memPtr->status .= $newStatus; - } - } - else - { - $memPtr->status = str_replace($newStatus, "", $memPtr->status); - } - } - - } - - } - - - } - - private function setChannelData($channel, $item, $val) - { - $channel = $this->myStrToLower($channel); - $item = $this->myStrToLower($item); - - if (isset($this->chanData[$channel])) - { - $chanPtr = $this->chanData[$channel]; - - switch ($item) - { - case "topicby": - $chanPtr->topicBy = $val; - break; - - case "topic": - $chanPtr->topic = $val; - break; - - case "bancomplete": - $chanPtr->banComplete = $val; - break; - - case "created": - $chanPtr->created = $val; - break; - - case "modes": - unset($chanPtr->modes); - $chanPtr->modes = array(); - $chanPtr->modes['MODE_STRING'] = substr($val, 1); - break; - } - - } - - } - - - private function clearBanList($channel) - { - $channel = $this->myStrToLower($channel); - - if (isset($this->chanData[$channel])) - { - unset($this->chanData[$channel]->banList); - $this->chanData[$channel]->banList = array(); - } - } - - private function changeChannel($channel, $action, $newStatus, $extraStatus = "") - { - - $channel = $this->myStrToLower($channel); - $newStatus = trim($newStatus); // i.e, l, b - - if (!is_array($extraStatus)) - { - $extraStatus = trim($extraStatus); // i.e, 50, *!*@* - } - - - - //ex. CHANMODES=eIb,k,l,cimnpstMNORZ - - if ($newStatus == "" || $action == "") - { - return; - } - - if (!isset($this->modeArray[$newStatus])) - { - return; - } - - $type = $this->modeArray[$newStatus]; - - if ($type != BY_NONE && $extraStatus == "") - { - return; - } - - if (strpos($this->getServerConf('CHANMODES'), $newStatus) === false) - { - return; - } - - //Find our channel - - if (isset($this->chanData[$channel])) - { - $chanPtr = $this->chanData[$channel]; - - if (!is_array($chanPtr->modes)) - { - unset($chanPtr->modes); - $chanPtr->modes = array(); - } - - if (!isset($chanPtr->modes['MODE_STRING'])) - { - $chanPtr->modes['MODE_STRING'] = ""; - } - - if ($type == BY_MASK) - { - - if ($newStatus == "b") - { - if ($action == "+") - { - if (is_array($extraStatus)) - { - $ban = $extraStatus[0]; - $time = $extraStatus[1]; - } - else - { - $ban = $extraStatus; - $time = time(); - } - - $chanPtr->banList[] = array( 'HOST' => $ban, - 'TIME' => $time, - ); - - - } - else - { - foreach ($chanPtr->banList AS $index => $data) - { - if ($data['HOST'] == $extraStatus) - { - unset($chanPtr->banList[$index]); - break; - } - } - } - } - } - else - { - if ($action == "+") - { - if (strpos($chanPtr->modes['MODE_STRING'], $newStatus) === false) - { - $chanPtr->modes['MODE_STRING'] .= $newStatus; - if ($type != BY_NONE) - { - $chanPtr->modes[$newStatus] = $extraStatus; - } - } - } - else - { - $chanPtr->modes['MODE_STRING'] = str_replace($newStatus, "", $chanPtr->modes['MODE_STRING']); - if ($type != BY_NONE) - { - unset($chanPtr->modes[$newStatus]); - } - } - } - - } - - - } - - private function purgeChanList() - { - foreach ($this->chanData AS $cIndex => $chanPtr) - { - foreach ($chanPtr->memberList AS $mIndex => $memPtr) - { - unset($chanPtr->memberList[$mIndex]); - } - - unset($this->chanData[$cIndex]); - } - - unset($this->chanData); - $this->chanData = array(); - } - - private function removeMember($channel, $nick) - { - - $channel = $this->myStrToLower($channel); - $nick = trim($this->myStrToLower($nick)); - - if ($channel == "") - { - foreach($this->chanData AS $chanPtr) - { - if (isset($chanPtr->memberList[$nick])) - { - unset($chanPtr->memberList[$nick]); - $chanPtr->count--; - } - } - - } - else - { - if (isset($this->chanData[$channel])) - { - if (isset($this->chanData[$channel]->memberList[$nick])) - { - unset($this->chanData[$channel]->memberList[$nick]); - $this->chanData[$channel]->count--; - } - } - } - - } - - private function removeChannel($channel) - { - $channel = $this->myStrToLower($channel); - - if (isset($this->chanData[$channel])) - { - $chanPtr = $this->chanData[$channel]; - - foreach ($chanPtr->memberList AS $mIndex => $memPtr) - { - $this->removeMember($channel, $mIndex); - } - - unset($chanPtr->banList); - unset($chanPtr->modes); - - unset($this->chanData[$channel]); - } - } - - public function isChanMode($channel, $mode, $extra = "") - { - $channel = $this->myStrToLower($channel); - $extra = $this->myStrToLower($extra); - - if (!isset($this->chanData[$channel])) - { - return; - } - - $chanPtr = $this->chanData[$channel]; - - if (!isset($this->modeArray[$mode])) - { - return false; - } - - $type = $this->modeArray[$mode]; - - if ($type == BY_MASK) - { - if ($mode == "b") - { - - foreach ($chanPtr->banList AS $index => $ban) - { - - if ($this->hostMasksMatch($ban['HOST'], $extra)) - { - return true; - } - - } - } - } - else - { - if (strpos($chanPtr->modes['MODE_STRING'], $mode) !== false) - { - return true; - } - } - - return false; - } - - public function hasModeSet($chan, $nick, $modes) - { - $channel = $this->myStrToLower($chan); - $nick = $this->myStrToLower($nick); - - if (isset($this->chanData[$channel])) - { - if (isset($this->chanData[$channel]->memberList[$nick])) - { - $memPtr = $this->chanData[$channel]->memberList[$nick]; - - while ($modes != "") - { - $mode = substr($modes, 0, 1); - $modes = substr($modes, 1); - - if (strpos($memPtr->status, $mode) !== false) - { - return true; - } - } - - } - } - - return false; - - } - - public function isMode($nick, $channel, $mode) - { - $channel = $this->myStrToLower($channel); - $nick = $this->myStrToLower($nick); - - if (isset($this->chanData[$channel])) - { - if (isset($this->chanData[$channel]->memberList[$nick])) - { - $memPtr = $this->chanData[$channel]->memberList[$nick]; - - if ($mode == "online") - { - return true; - } - else - { - if (strpos($memPtr->status, $mode) !== false) - { - return true; - } - } - } - } - - return false; - } - - private function getHostMask($mask) - { - $offsetA = strpos($mask, "!"); - $offsetB = strpos($mask, "@"); - - $myMask = array(); - - $myMask['nick'] = $this->myStrToLower(substr($mask, 0, $offsetA)); - $myMask['ident'] = $this->myStrToLower(substr($mask, $offsetA + 1, $offsetB - $offsetA - 1)); - $myMask['host'] = $this->myStrToLower(substr($mask, $offsetB + 1)); - - return $myMask; - } - - public function hostMasksMatch($mask1, $mask2) - { - - $maskA = $this->getHostMask($mask1); - $maskB = $this->getHostMask($mask2); - - $ident = false; - $nick = false; - $host = false; - - if ($maskA['ident'] == $maskB['ident'] - || $maskA['ident'] == "*" || $maskB['ident'] == "*") - { - $ident = true; - } - - if ($maskA['nick'] == $maskB['nick'] - || $maskA['nick'] == "*" || $maskB['nick'] == "*") - { - $nick = true; - } - - if ($maskA['host'] == $maskB['host'] - || $maskA['host'] == "*" || $maskB['host'] == "*") - { - $host = true; - } - - if ($host && $nick && $ident) - { - return true; - } - else - { - return false; - } - - } - - - public function setToIdleStatus() - { - $this->status = STATUS_IDLE; - } - - - private function getStatus() - { - $this->reportedStatus = $this->status; - return $this->status; - } - - private function getStatusChange() - { - return ($this->reportedStatus != $this->status); - } - - private function getException() - { - return $this->exception; - } - - private function updateContext() - { - - if ($this->getStatusChange()) - { - $status = $this->getStatus(); - $statusStr = $this->getStatusString($status); - $this->log("STATUS: " . $statusStr); - $this->dccClass->dccInform("Status: " . $statusStr); - - switch($status) - { - case STATUS_ERROR: - $exception = $this->getException(); - $this->log("Error: " . $exception->getMessage()); - $this->dccClass->dccInform("Error: " . $exception->getMessage()); - break; - default: - break; - } - - } - - } - - public function reconnect() - { - $this->updateContext(); - - try { - - $this->connectStartTime = time(); - - $conn = new connection($this->getClientConf('server'), $this->getClientConf('port'), CONNECT_TIMEOUT); - - $this->conn = $conn; - - $conn->setSocketClass($this->socketClass); - $conn->setIrcClass($this); - $conn->setCallbackClass($this); - $conn->setTimerClass($this->timerClass); - $conn->init(); - - if ($conn->getError()) - { - throw new ConnectException($conn->getErrorMsg()); - } - - //Bind socket... - if ($this->getClientConf('bind') != "") - { - $conn->bind($this->getClientConf('bind')); - } - - $this->sockInt = $conn->getSockInt(); - $conn->connect(); - - - } - catch (ConnectException $e) - { - $this->beginReconnectTimer(); - $this->status = STATUS_ERROR; - $this->exception = $e; - return; - } - - $this->status = STATUS_CONNECTING; - - $this->updateContext(); - - return; - } - - public function onConnect($conn) - { - $this->status = STATUS_CONNECTED; - - $this->updateContext(); - - $this->timeoutTimer = time(); - $ip = ""; - if ($this->getClientConf('natip') != "") - { - $ip = $this->getClientConf('natip'); - } - $this->setClientIP($ip); - - $this->register(); - //TODO: Add registration timeout timer (with $conn to check identity) - - return false; - } - - public function onRead($conn) - { - $this->updateContext(); - - return $this->readInput(); - } - - public function onWrite($conn) - { - //Do nothing.. this function has no purpose for the ircClass - return false; - } - - public function onAccept($listenConn, $newConn) - { - //Do nothing.. this function has no purpose for the ircClass - return false; - } - - public function onDead($conn) - { - if ($conn->getError()) - { - $this->status = STATUS_ERROR; - $this->exception = new ConnectException($conn->getErrorMsg()); - } - - $this->disconnect(); - return false; - } - - public function onConnectTimeout($conn) - { - $this->status = STATUS_ERROR; - $this->exception = new ConnectException("Connection attempt timed out"); - $this->disconnect(); - } - - private function beginReconnectTimer() - { - $this->timerClass->addTimer(self::randomHash(), $this, "reconnectTimer", $this->conn, ERROR_TIMEOUT); - } - - public function reconnectTimer($conn) - { - //If curr connection is equal to the stored connection, then no forced - //connect was attempted, so attempt another. - - if ($this->conn === $conn) - { - $this->reconnect(); - } - - return false; - } - - - public function disconnect() - { - $this->conn->disconnect(); - - $this->updateContext(); - - $this->status = STATUS_ERROR; - $this->exception = new ConnectException("Disconnected from server"); - - $this->updateContext(); - - //reset all vars - $this->purgeChanList(); - $this->timeoutTimer = 0; - $this->lastPing = 0; - $this->lastPingTime = 0; - $this->nickTimer = 0; - $this->connectStartTime = 0; - $this->lagTime = 0; - $this->checkChansTimer = 0; - $this->purgeTextQueue(); - $this->nick = $this->getClientConf('nick'); - $this->tempNick = ""; - unset($this->modeArray); - unset($this->prefixArray); - unset($this->serverConfig); - $this->modeArray = array(); - $this->prefixArray = array(); - $this->serverConfig = array(); - - $this->beginReconnectTimer(); - - return; - } - - private function register() - { - $login_string = "NICK ".$this->getClientConf('nick')."\r\n"."USER ".$this->getClientConf('ident')." "."localhost"." ".$this->getClientConf('server')." :".$this->getClientConf('realname'); - if ($this->getClientConf('serverpassword') != "") - $login_string = "PASS ".$this->getClientConf('serverpassword')."\r\n".$login_string; - - $validate = $this->clientFormat($login_string); - - $this->timeConnected = time(); - $this->pushAfter($validate); - $this->status = STATUS_CONNECTED_SENTREGDATA; - - $this->timerClass->addTimer($this->randomHash(), $this, "regTimeout", $this->sockInt, REGISTRATION_TIMEOUT); - } - - - public function regTimeout($sockInt) - { - if ($sockInt != $this->sockInt) - { - return false; - } - - if ($this->status != STATUS_CONNECTED_SENTREGDATA) - { - return false; - } - - $this->disconnect(); - - $this->status = STATUS_ERROR; - $this->exception = new ConnectionTimeout("Session Authentication Timed out"); - - return false; - } - - //The following function kills this irc object, but ONLY if there is no send queue. - //A good way to use it is with a timer, say, ever second or so. - public function shutDown() - { - if (!$this->conn->getError()) - { - return; - } - - /* - if ($this->socketClass->hasWriteQueue($this->sockInt)) - { - return true; - } - - $this->disconnect(); - */ - $this->parserClass->destroyModules(); - $this->dccClass->closeAll(); - $this->procQueue->removeOwner($this); - $date = date("h:i:s a, m-d-y"); - $this->log("The bot successfully shutdown, $date"); - - //Okay.. now the bot is PSEUDO dead. It still exists, however it has no open sockets, it will not - //attempt to reconnect to the server, and all dcc sessions, modules, timers, and processes related to it - //have been destroyed. - - return false; - - } - - /* Some assorted timers */ - - public function checkNick() - { - if ($this->getStatusRaw() != STATUS_CONNECTED_REGISTERED) - { - return true; - } - - if ($this->nick != $this->getClientConf('nick')) - { - $this->changeNick($this->getClientConf('nick')); - } - - return true; - } - - public function checkPingTimeout() - { - if ($this->getStatusRaw() != STATUS_CONNECTED_REGISTERED) - { - return true; - } - - try { - if ($this->lastPing == 1) - { - $this->lastPing = 0; - throw new ConnectionTimeout("The connection with the server timed out."); - } - else - { - if (time() > $this->timeoutTimer + PING_TIMEOUT + $this->lagTime) - { - $this->pushBefore($this->clientFormat("PING :Lagtime")); - $this->lastPingTime = time(); - $this->lastPing = 1; - } - } - } - catch (ConnectionTimeout $e) - { - $this->disconnect(); - $this->status = STATUS_ERROR; - $this->exception = $e; - } - - return true; - } - - public function getStatusRaw() - { - return $this->status; - } - - - public function getLine() - { - return $this->lVars; - } - - private function readInput() - { - if ($this->status != STATUS_CONNECTED_REGISTERED && $this->status != STATUS_CONNECTED_SENTREGDATA) - { - return false; - } - - if ($this->socketClass->isDead($this->sockInt) && !$this->socketClass->hasLine($this->sockInt)) - { - $this->disconnect(); - $this->status = STATUS_ERROR; - $this->exception = new ReadException("Failed while reading from socket"); - return false; - } - - if ($this->socketClass->hasLine($this->sockInt)) - { - $this->timeoutTimer = time(); - - if ($this->lastPing == 1) - { - $this->lagTime = time() - $this->lastPingTime; - } - $this->lastPing = 0; - - $line = $this->socketClass->getQueueLine($this->sockInt); - - $this->stats['BYTESDOWN'] += strlen($line); - - $this->log($line); - - if (substr($line, 0, 1) != ":") - { - $line = ":Server " . $line; - } - - $line = substr($line, 1); - - $parts = explode(chr(32), $line); - - $params = substr($line, strlen($parts[0]) + strlen($parts[1]) + strlen($parts[2]) + 3); - if (strpos($params, " :")) - { - $params = substr($params, 0, strpos($params, " :")); - } - - $offset1 = strpos($parts[0], '!'); - $offset2 = $offset1 + 1; - $offset3 = strpos($parts[0], '@') + 1; - $offset4 = $offset3 - $offset2 - 1; - $offset5 = strpos($line, " :") + 2; - - unset($this->lVars); - - $this->lVars = array( 'from' => $parts[0], - 'fromNick' => substr($parts[0], 0, $offset1), - 'fromIdent' => substr($parts[0], $offset2, $offset4), - 'fromHost' => substr($parts[0], $offset3), - 'cmd' => $parts[1], - 'to' => $parts[2], - 'text' => substr($line, $offset5), - 'params' => trim($params), - 'raw' => ":" . $line, - ); - - if ($offset5 === false) - { - $line['text'] = ""; - } - - if (intval($this->lVars['cmd']) > 0) - { - $this->parseServerMsgs($this->lVars['cmd']); - } - else - { - $this->parseMsgs(); - } - - $this->parserClass->parseLine($this->lVars); - } - - if ($this->socketClass->hasQueue($this->sockInt)) - { - return true; - } - - return false; - } - - - private function parseServerMsgs($cmd) - { - switch ($cmd) - { - case 004: - $this->status = STATUS_CONNECTED_REGISTERED; - if ($this->tempNick != "") - { - $this->nick = $this->tempNick; - } - break; - - case 005: - $this->parseServerConfig(); - if (!isset($this->modeArray) || !is_array($this->modeArray) || count($this->modeArray) <= 0) - { - if ($this->getServerConf("CHANMODES") != "") - { - $this->createModeArray(); - $this->checkChans(); - } - } - break; - - case 311: - $params = explode(chr(32), $this->lVars['params']); - $this->setMemberData($params[0], $params[1], $params[2]); - - case 324: - $params = explode(chr(32), $this->lVars['params']); - $channel = $params[0]; - $query = substr($this->lVars['params'], strlen($channel) + 1); - $this->setChannelData($channel, "modes", $query); - break; - - case 329: - $params = explode(chr(32), $this->lVars['params']); - $channel = $params[0]; - $query = substr($this->lVars['params'], strlen($channel) + 1); - $this->setChannelData($channel, "created", $query); - break; - - case 332: - $this->setChannelData(trim($this->lVars['params']), "topic", $this->lVars['text']); - break; - - case 333: - $params = explode(chr(32), $this->lVars['params']); - $channel = $params[0]; - $query = substr($this->lVars['params'], strlen($channel) + 1); - $this->setChannelData($channel, "topicby", $query); - break; - - case 352: - $params = explode(chr(32), $this->lVars['params']); - $this->changeMember($params[0], $params[4], $params[4], $params[1], "", "", $params[2]); - break; - - case 353: - $channel = substr($this->lVars['params'], 2); - $this->updateOpList($channel); - break; - - case 367: - $params = explode(chr(32), $this->lVars['params']); - $data = $this->getChannelData($params[0]); - if ($data != NULL) - { - if ($data->banComplete == 1) - { - $this->clearBanList($params[0]); - $data->banComplete = 0; - } - - $this->changeChannel($params[0], "+", "b", array($params[1], $params[3])); - } - break; - - case 368: - $params = explode(chr(32), $this->lVars['params']); - $channel = $params[0]; - $this->setChannelData($channel, "bancomplete", 1); - break; - - case 401: - $this->removeQueues($this->lVars['params']); - break; - - case 433: - if ($this->getStatusRaw() != STATUS_CONNECTED_REGISTERED) - { - if ($this->nick == $this->getClientConf('nick')) - { - $this->changeNick($this->nick . rand() % 1000); - } - $this->nickTimer = time(); - } - break; - } - - } - - public function isOnline($nick, $chan) - { - return $this->isMode($nick, $chan, "online"); - } - - - private function updateOpList($channel) - { - $channel = $this->myStrToLower($channel); - $users = explode(chr(32), $this->lVars['text']); - - if (!isset($this->prefixArray) || count($this->prefixArray) <= 0) - { - $this->createPrefixArray(); - } - - foreach ($users AS $user) - { - if (trim($user) == "") - { - continue; - } - - $userModes = ""; - $userNick = ""; - - for ($currIndex = 0; $currIndex < strlen($user); $currIndex++) - { - $currChar = substr($user, $currIndex, 1); - - if (!isset($this->prefixArray[$currChar])) - { - $userNick = substr($user, $currIndex); - break; - } - - $userModes .= $currChar; - } - - if ($userNick != $this->nick) - { - $this->addmember($channel, $userNick, "", $this->convertUserModes($userModes)); - } - - } - - } - - - private function convertUserModes($modes) - { - $newModes = ""; - - for ($index = 0; $index < strlen($modes); $index++) - { - $newModes .= $this->prefixArray[$modes[$index]]; - } - - return $newModes; - } - - - private function createPrefixArray() - { - $modeSymbols = substr($this->getServerConf('PREFIX'), strpos($this->getServerConf('PREFIX'), ")") + 1); - - $leftParan = strpos($this->getServerConf('PREFIX'), "("); - $rightParan = strpos($this->getServerConf('PREFIX'), ")"); - $modeLetters = substr($this->getServerConf('PREFIX'), $leftParan + 1, $rightParan - $leftParan - 1); - - for ($index = 0; $index < strlen($modeLetters); $index++) - { - $this->prefixArray[$modeSymbols[$index]] = $modeLetters[$index]; - } - - } - - - public function doMode() - { - $this->modeQueueAdded = false; - - $currAct = ""; - $currChan = ""; - - $modeLineModes = ""; - $modeLineParams = ""; - - $maxModesPerLine = ($this->getServerConf('MODES') == "" ? 1 : $this->getServerConf('MODES')); - $currLineModes = 0; - - foreach($this->modeQueue AS $modeChange) - { - if ($modeLineModes != "" && ($currChan != $modeChange['CHANNEL'] || $currLineModes >= $maxModesPerLine)) - { - $this->pushAfter($this->clientFormat("MODE " . $currChan . " " . $modeLineModes . " " . trim($modeLineParams))); - $modeLineModes = ""; - $currAct = ""; - $currChan = ""; - $modeLineParams = ""; - $currLineModes = 0; - } - - if ($currAct != $modeChange['ACT']) - { - $modeLineModes .= $modeChange['ACT']; - } - - $modeLineModes .= $modeChange['MODE']; - - if ($modeChange['USER'] != "") - { - $modeLineParams .= $modeChange['USER'] . " "; - } - - $currLineModes++; - - $currAct = $modeChange['ACT']; - $currChan = $modeChange['CHANNEL']; - - } - - if ($modeLineModes != "") - { - $this->pushAfter($this->clientFormat("MODE " . $currChan . " " . $modeLineModes . " " . trim($modeLineParams))); - } - - unset($this->modeQueue); - $this->modeQueue = array(); - $this->modeQueueLength = 0; - - return false; - - } - - public function changeMode($chan, $act, $mode, $user) - { - $user = trim($user); - $chan = trim($chan); - $act = trim($act); - $mode = trim($mode); - - if ($chan == "" || $mode == "") - { - return false; - } - - if (!($act == "+" || $act == "-")) - { - return false; - } - - if (strlen($mode) > 1) - { - return false; - } - - if (!isset($this->modeArray[$mode])) - { - if ($user == "") - { - return false; - } - } - - if ($this->modeQueueAdded != true) - { - $this->timerClass->addTimer("mode_timer", $this, "doMode", "", 0, true); - $this->modeQueueAdded = true; - } - - $this->modeQueue[] = array('USER' => $user, 'CHANNEL' => $chan, 'ACT' => $act, 'MODE' => $mode); - $this->modeQueueLength++; - - return true; - - } - - public function parseModes($modeString) - { - $modeString .= " "; - - $offset = strpos($modeString, chr(32)); - $modes = substr($modeString, 0, $offset); - $users = substr($modeString, $offset + 1); - $userArray = explode(chr(32), $users); - - if (count($this->modeArray) <= 0) - { - $this->createModeArray(); - } - - $action = ""; - $returnModes = array(); - - while (trim($modes) != "") - { - $thisMode = substr($modes, 0, 1); - - $modes = substr($modes, 1); - - if ($thisMode == "-" || $thisMode == "+") - { - $action = $thisMode; - continue; - } - - if (strpos($this->getServerConf('CHANMODES'), $thisMode) !== false) - { - if (!isset($this->modeArray[$thisMode])) - { - return false; - } - - $type = $this->modeArray[$thisMode]; - $extra = ""; - if ($type != BY_NONE) - { - $extra = array_shift($userArray); - } - - $type = CHANNEL_MODE; - - } - else - { - $extra = array_shift($userArray); - $type = USER_MODE; - } - - $returnModes[] = array( 'ACTION' => $action, - 'MODE' => $thisMode, - 'EXTRA' => $extra, - 'TYPE' => $type, - ); - - } - - return $returnModes; - } - - public static function intToSizeString($size) - { - - $i = 20; - while ($size > pow(2, $i)) - { - $i += 10; - } - - switch ($i) - { - case 20: //kb - $num = $size / 1000; - $type = "KB"; - break; - case 30: //mb - $num = $size / 1000000; - $type = "MB"; - break; - case 40: //gb - $num = $size / 1000000000; - $type = "GB"; - break; - case 50: //tb - $num = $size / 1000000000000; - $type = "TB"; - break; - default: //pb - $num = $size / 1000000000000000; - $type = "PB"; - break; - } - - $stringSize = round($num, 2) . $type; - - return $stringSize; - - } - - - public function checkIgnore($mask) - { - $ignore = $this->getClientConf('ignore'); - - if ($ignore == "") - { - return false; - } - - if (!is_array($ignore)) - { - $ignore = array($ignore); - } - - foreach($ignore AS $ig) - { - $case = $this->hostMasksMatch($mask, $ig); - - if ($case) - { - return true; - } - } - - return false; - } - - - private function parseMsgs() - { - - switch($this->lVars['cmd']) - { - case "JOIN": - $chan = $this->lVars['to']; - if (substr($this->lVars['to'], 0, 1) == ":") - { - $chan = substr($this->lVars['to'], 1); - } - $this->addMember($chan, $this->lVars['fromNick'], $this->lVars['fromIdent'], "", $this->lVars['fromHost']); - if ($this->lVars['fromNick'] == $this->getNick()) - { - $this->sendRaw("MODE " . $chan); - - if (isset($this->clientConfig['populatebans'])) - { - $this->sendRaw("MODE " . $chan . " +b"); - } - - if (isset($this->clientConfig['populatewho'])) - { - $this->sendRaw("WHO " . $chan); - } - } - break; - - case "PART": - if ($this->lVars['fromNick'] == $this->nick) - { - $this->removeChannel($this->lVars['to']); - } - else - { - $this->removeMember($this->lVars['to'], $this->lVars['fromNick']); - } - break; - - case "QUIT": - if ($this->lVars['fromNick'] == $this->nick) - { - $this->purgeChanList(); - } - else - { - $this->removeMember("", $this->lVars['fromNick']); - } - break; - - case "NICK": - if ($this->lVars['fromNick'] == $this->nick) - { - $this->nick = $this->lVars['text']; - } - $this->changeMember("", $this->lVars['fromNick'], $this->lVars['text'], "", "", ""); - break; - - case "KICK": - if ($this->myStrToLower($this->lVars['params']) == $this->myStrToLower($this->nick)) - { - $this->removeChannel($this->lVars['to']); - $this->joinChannel($this->lVars['to']); - } - else - { - $this->removeMember($this->lVars['to'], $this->lVars['params']); - } - break; - - case "MODE": - $channel = $this->myStrToLower($this->lVars['to']); - if ($channel == $this->myStrToLower($this->nick)) - break; - $modes = $this->parseModes($this->lVars['params']); - foreach($modes AS $mode) - { - if ($mode['TYPE'] == CHANNEL_MODE) - { - $this->changeChannel($channel, $mode['ACTION'], $mode['MODE'], $mode['EXTRA']); - } - else - { - $this->changeMember($channel, $mode['EXTRA'], $mode['EXTRA'], "", $mode['MODE'], $mode['ACTION']); - } - unset($mode); - } - unset($modes); - break; - case "NOTICE": - if ($this->checkIgnore($this->lVars['from'])) - { - return; - } - if ($this->myStrToLower($this->lVars['fromNick']) == "nickserv") - { - if (strpos($this->myStrToLower($this->lVars['text']), "identify") !== false) - { - if ($this->getClientConf('password') != "") - { - $this->pushBefore($this->clientFormat("PRIVMSG HostServ :ON")); - $this->pushBefore($this->clientFormat("PRIVMSG NickServ :IDENTIFY " . $this->getClientConf('password'))); - $this->pushBefore($this->clientFormat("MODE " . $this->getClientConf('nick') . " +B")); - } - } - } - break; - case "PRIVMSG": - if ($this->checkIgnore($this->lVars['from'])) - { - return; - } - if (strpos($this->lVars['text'], chr(1)) !== false) - { - $this->parseCtcp(); - } - break; - case "TOPIC": - $this->setChannelData($this->lVars['to'], "topic", $this->lVars['text']); - break; - - case "PING": - if ($this->lVars['from'] == "Server") - { - $this->pushBefore($this->clientFormat("PONG :" . $this->lVars['text'])); - } - - default: - break; - - - } - - - - - } - - - - private function parseCtcp() - { - $cmd = str_replace(chr(1), "", $this->lVars['text']) . " "; - $query = trim(substr($cmd, strpos($cmd, chr(32)) + 1)); - $cmd = substr($this->myStrToLower($cmd), 0, strpos($cmd, chr(32))); - - $msg = ""; - - switch($cmd) - { - case "version": - // PLEASE DO NOT CHANGE THE FOLLOWING LINE OF CODE. It is the only way for people to know that this project - // exists. If you would like to change it, please leave the project name/version or url in there somewhere, - // so that others may find this project as you have. :) - $msg = "PHP-iRC v" . VERSION . " [".VERSION_DATE."] by Manick (visit http://www.phpbots.org/ to download)"; - $this->notice($this->lVars['fromNick'], chr(1) . $msg . chr(1)); - $msg = ""; - $this->showModules($this->lVars['fromNick']); - break; - - case "time": - $msg = "My current time is " . date("l, F jS, Y @ g:i a O", time()) . "."; - break; - - case "uptime": - $msg = "My uptime is " . $this->timeFormat($this->getRunTime(), "%d days, %h hours, %m minutes, and %s seconds."); - break; - - case "ping": - $msg = "PING " . $query; - - } - - if ($msg != "") - { - $this->notice($this->lVars['fromNick'], chr(1) . $msg . chr(1)); - } - - } - - //Split huge lines up by spaces 255 by default - public static function multiLine($text, $separator = " ") - { - $returnArray = array(); - $text = trim($text); - $strlen = strlen($text); - $sepSize = strlen($separator); - - while ($strlen > 0) - { - if (256 > $strlen) - { - $returnArray[] = $text; - break; - } - - for ($i = 255; $i > 0; $i--) - { - if (substr($text, $i, $sepSize) == $separator) - { - break; - } - } - - if ($i <= 0) - { - $returnArray[] = substr($text, 0, 255); - $text = substr($text, 254); - $strlen -= 255; - } - else - { - $returnArray[] = substr($text, 0, $i); - $text = substr($text, $i - 1); - $strlen -= $i; - } - } - - return $returnArray; - } - - - private function showModules($nick) - { - $cmdList = $this->parserClass->getCmdList(); - - if (isset($cmdList['file'])) - { - $mod = ""; - - foreach($cmdList['file'] AS $module) - { - $class = $module['class']; - - if (isset($class->dontShow) && $class->dontShow == true) - { - continue; - } - $mod .= "[" . $class->title . " " . $class->version . "] "; - } - - if ($mod != "") - { - $modArray = $this->multiLine("Running Modules: " . $mod); - - foreach ($modArray AS $myMod) - { - $this->notice($nick, chr(1) . $myMod . chr(1)); - } - } - } - unset($cmdList); - } - - - public function getRunTime() - { - return (time() - $this->startTime); - } - - - public static function timeFormat($time, $format) - { - - $days = 0; - $seconds = 0; - $minutes = 0; - $hours = 0; - - if (strpos($format, "%d") !== FALSE) - { - $days = (int) ($time / (3600 * 24)); - $time -= ($days * (3600 * 24)); - } - - if (strpos($format, "%h") !== FALSE) - { - $hours = (int) ($time / (3600)); - $time -= ($hours * (3600)); - } - - if (strpos($format, "%m") !== FALSE) - { - $minutes = (int) ( $time / (60)); - $time -= ($minutes * (60)); - } - - $seconds = $time; - - $format = str_replace("%d", $days, $format); - $format = str_replace("%s", $seconds, $format); - $format = str_replace("%m", $minutes, $format); - $format = str_replace("%h", $hours, $format); - - return $format; - - } - - - private function createModeArray() - { - $modeArray = explode(",", $this->getServerConf('CHANMODES')); - - for ($i = 0; $i < count($modeArray); $i++) - { - for ($j = 0; $j < strlen($modeArray[$i]); $j++) - { - $this->modeArray[$modeArray[$i][$j]] = $i; - } - - } - } - - public function checkChans() - { - if ($this->getStatusRaw() != STATUS_CONNECTED_REGISTERED) - { - return true; - } - - foreach ($this->maintainChannels AS $index => $channel) - { - if ($this->isOnline($this->nick, $channel['CHANNEL']) === false) - { - if ($channel['KEY'] != "") - { - $this->joinChannel($channel['CHANNEL'] . " " . $channel['KEY']); - } - else - { - $this->joinChannel($channel['CHANNEL']); - } - } - } - - return true; - } - - public function getStatusString($status) - { - $msg = ""; - - switch ($status) - { - case STATUS_IDLE: - $msg = "Idle"; - break; - case STATUS_ERROR: - $msg = "Error"; - break; - case STATUS_CONNECTING: - $msg = "Connecting to server..."; - break; - case STATUS_CONNECTED: - $msg = "Connected to server: " . $this->getClientConf('server') . " " . $this->getClientConf('port'); - break; - case STATUS_CONNECTED_SENTREGDATA: - $msg = "Sent registration data, awaiting reply..."; - break; - case STATUS_CONNECTED_REGISTERED: - $msg = "Authenticated"; - break; - default: - $msg = "Unknown"; - } - - return $msg; - } - - - public function purgeMaintainList() - { - unset($this->maintainChannels); - $this->maintainChannels = array(); - } - - - public function removeMaintain($channel) - { - $channel = $this->myStrToLower($channel); - - foreach ($this->maintainChannels AS $index => $chan) - { - if ($chan['CHANNEL'] == $channel) - { - unset($this->maintainChannels[$index]); - break; - } - } - } - - - public function maintainChannel($channel, $key = "") - { - $channel = $this->myStrToLower($channel); - $this->maintainChannels[] = array('CHANNEL' => $channel, 'KEY' => $key); - } - - - public function joinChannel($chan) - { - $this->pushBefore($this->clientFormat("JOIN " . $chan)); - } - - public function changeNick($nick) - { - $this->pushBefore($this->clientFormat("NICK " . $nick)); - $this->tempNick = $nick; - } - - - private function parseServerConfig() - { - $args = explode(chr(32), $this->lVars['params']); - - foreach ($args AS $arg) - { - - if (strpos($arg, "=") === false) - { - $arg .= "=1"; - } - - $argParts = explode("=", $arg); - - $this->serverConfig[$argParts[0]] = $argParts[1]; - - } - } - - private function clientFormat($text) - { - return array("USER" => "*", "TEXT" => $text); - } - - - - public function removeQueues($nick) - { - $nick = $this->myStrToLower($nick); - - foreach ($this->textQueue AS $index => $queue) - { - if ($this->myStrToLower($queue['USER']) == $nick) - { - unset($this->textQueue[$index]); - $this->textQueueLength--; - } - } - - - } - - public function getStats() - { - return $this->stats; - } - - public function doQueue() - { - if ($this->status < STATUS_CONNECTED) - { - $this->textQueueAdded = false; - return false; - } - - if ($this->socketClass->hasWriteQueue($this->sockInt) !== false) - { - return true; - } - - if ($this->textQueueLength < 0) - { - if (is_array($this->textQueue)) - { - unset($this->textQueue); - $this->textQueue = array(); - } - $this->textQueueAdded = false; - return false; - } - - $bufferSize = $this->getClientConf("queuebuffer"); - - $bufferSize = $bufferSize <= 0 ? 0 : $bufferSize; - - $sendData = ""; - - $nextItem = array_shift($this->textQueue); - - if (trim($nextItem['TEXT']) != "") - { - $sendData .= $nextItem['TEXT'] . "\r\n"; - } - - unset($nextItem); - - $this->textQueueLength--; - - while ($this->textQueueLength > 0 && ((strlen($this->textQueue[0]['TEXT']) + strlen($sendData)) < $bufferSize)) - { - - $nextItem = array_shift($this->textQueue); - - if (trim($nextItem['TEXT']) != "") - { - $sendData .= $nextItem['TEXT'] . "\r\n"; - unset($nextItem); - } - - $this->textQueueLength--; - - } - - $this->stats['BYTESUP'] += strlen($sendData); - - $this->writeToSocket($sendData); - - unset($sendData); - - return true; - } - - - private function writeToSocket($sendData) - { - - if (DEBUG == 1) - { - $this->log($sendData); - } - - try - { - if ($this->socketClass->sendSocket($this->sockInt, $sendData) === false) - { - throw new SendDataException("Could not write to socket"); - } - } - catch (SendDataException $e) - { - $this->disconnect(); - $this->exception = $e; - $this->status = STATUS_ERROR; - } - - } - - - private function pushAfter($data) - { - $this->textQueueLength++; - $this->textQueue[] = $data; - - if ($this->textQueueAdded == false) - { - $this->timerClass->addTimer("queue_timer", $this, "doQueue", "", $this->getQueueTimeout(), true); - $this->textQueueAdded = true; - } - - } - - - private function pushBefore($data) - { - $this->textQueueLength++; - $this->textQueue = array_merge(array($data), $this->textQueue); - - if ($this->textQueueAdded == false) - { - $this->timerClass->addTimer("queue_timer", $this, "doQueue", "", $this->getQueueTimeout(), true); - $this->textQueueAdded = true; - } - } - - public function sendRaw($text, $force = false) - { - if ($force == false) - { - $format = $this->clientFormat($text); - $this->pushBefore($format); - } - else - { - $this->writeToSocket($text . "\r\n"); - } - } - - - public function privMsg($who, $msg, $queue = 1) - { - $text = array( 'USER' => $who, - 'TEXT' => 'PRIVMSG ' . $who . ' :' . $msg); - - if ($queue) - { - $this->pushAfter($text); - } - else - { - $this->pushBefore($text); - } - } - - - public function action($who, $msg, $queue = 1) - { - $text = array( 'USER' => $who, - 'TEXT' => 'PRIVMSG ' . $who . ' :' . chr(1) . 'ACTION ' .$msg . chr(1)); - - if ($queue) - { - $this->pushAfter($text); - } - else - { - $this->pushBefore($text); - } - } - - - public function notice($who, $msg, $queue = 1) - { - - $text = array( 'USER' => $who, - 'TEXT' => 'NOTICE ' . $who . ' :' . $msg); - - if ($queue) - { - $this->pushAfter($text); - } - else - { - $this->pushBefore($text); - } - } - - public function getClientIP($long = 1) - { - if ($long == 1) - { - return $this->clientLongIP; - } - else - { - return $this->clientIP; - } - } - - public function setClientIP($ip = "") - { - if ($ip == "") - { - $ip = $this->socketClass->getHost($this->sockInt); - } - - $this->clientIP = $ip; - - $this->clientLongIP = ip2long($this->clientIP); - - if ($this->clientLongIP <= 0) - { - $this->clientLongIP += pow(2,32); - } - } - - - - public function purgeTextQueue() - { - $this->textQueueTime = 0; - unset($this->textQueue); - $this->textQueue = array(); - $this->textQueueLength = 0; - } - - public function getTextQueueLength() - { - return $this->textQueueLength; - } - - public function log($data) - { - $network = $this->getServerConf('Network') == "" ? $this->getClientConf('server') : $this->getServerConf('Network'); - - if (DEBUG == 1) - { - echo "[".date("h:i:s")."] " . "({$this->nick}@$network) > " . $data . "\n"; - } - else - { - if ($this->getClientConf('logfile') != "") - { - error_log("[".date("h:i:s")."] " . "({$this->nick}@$network) > " . $data . "\n", 3, $this->getClientConf('logfile')); - } - } - } - - public function getUsageList() - { - return $this->usageList; - } - - public function floodCheck($line) - { - $host = $line['fromHost']; - - if (!array_key_exists($host, $this->usageList)) - { - $this->usageList[$host] = new usageLink; - $this->usageList[$host]->isBanned = false; - $this->usageList[$host]->lastTimeUsed = time(); - $this->usageList[$host]->timesUsed = 1; - $user = $this->usageList[$host]; - } - else - { - $user = $this->usageList[$host]; - - $floodTime = intval($this->getClientConf('floodtime')); - if ($floodTime <= 0) - { - $floodTime = 60; - } - - if ($user->isBanned == true) - { - if ($user->timeBanned > time() - $floodTime) - { - return STATUS_ALREADY_BANNED; - } - $user->isBanned = false; - } - - - if ($user->lastTimeUsed < time() - 10) - { - $user->timesUsed = 0; - } - $user->lastTimeUsed = time(); - $user->timesUsed++; - } - - $numLines = intval($this->getClientConf('floodlines')); - if ($numLines <= 0) - { - $numLines = 5; - } - - if ($user->timesUsed > $numLines) - { - $user->isBanned = true; - $user->timeBanned = time(); - $user->timesUsed = 0; - $user->lastTimeUsed = 0; - $this->removeQueues($line['fromNick']); - return STATUS_JUST_BANNED; - } - - return STATUS_NOT_BANNED; - } - - public static function myStrToLower($text) - { - $textA = strtolower($text); - - $textA = str_replace("\\", "|", $textA); - $textA = str_replace("[", "{", $textA); - $textA = str_replace("]", "}", $textA); - $textA = str_replace("~", "^", $textA); - - return $textA; - } - - public static function myStrToUpper($text) - { - $textA = strtoupper($text); - - $textA = str_replace("|", "\\", $textA); - $textA = str_replace("{", "[", $textA); - $textA = str_replace("}", "]", $textA); - $textA = str_replace("^", "~", $textA); - - return $textA; - } - - public static function randomHash() - { - return md5(uniqid(rand(), true)); - } - - private function getQueueTimeout() - { - $timeout = $this->getClientConf("queuetimeout"); - $timeout = $timeout <= 0 ? 0 : $timeout; - return $timeout; - } - - public function addQuery($host, $port, $query, $line, $class, $function) - { - $remote = new remote($host, $port, $query, $line, $class, $function, 8); - $remote->setIrcClass($this); - $remote->setTimerClass($this->timerClass); - $remote->setSocketClass($this->socketClass); - return $remote->connect(); - } - -} - diff --git a/ircbot/module.php b/ircbot/module.php deleted file mode 100644 index 0cdee92..0000000 --- a/ircbot/module.php +++ /dev/null @@ -1,126 +0,0 @@ - module class -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -abstract class module { - - public $title = ""; - public $author = "<author>"; - public $version = "<version>"; - public $dontShow = false; - - public $ircClass; - public $dccClass; - public $timerClass; - public $parserClass; - public $socketClass; - public $db; - - public function __construct() - { - //Nothing here... - } - - public function __destruct() - { - $this->ircClass = null; - $this->dccClass = null; - $this->timerClass = null; - $this->parserClass = null; - $this->socketClass = null; - $this->db = null; - //Nothing here - } - - public final function __setClasses($ircClass, $dccClass, $timerClass, $parserClass, - $socketClass, $db) - { - $this->ircClass = $ircClass; - $this->dccClass = $dccClass; - $this->timerClass = $timerClass; - $this->parserClass = $parserClass; - $this->socketClass = $socketClass; - $this->db = $db; - } - - public final function getModule($modName) - { - $mods = $this->parserClass->getCmdList("file"); - - if ($mods === false) - { - return false; - } - - if (isset($mods[$modName])) - { - return $mods[$modName]['class']; - } - - return false; - } - - public function handle($chat, $args) - { - } - - public function connected($chat) - { - } - - public function main($line, $args) - { - $port = $this->dccClass->addChat($line['fromNick'], null, null, false, $this); - - if ($port === false) - { - $this->ircClass->notice($line['fromNick'], "Error starting chat, please try again.", 1); - } - } - - public function init() - { - //Global.. this needs to be overwritten - } - - public function destroy() - { - //Global.. this needs to be overwritten - } - -} - -?> diff --git a/ircbot/modules/default/ads.ini b/ircbot/modules/default/ads.ini deleted file mode 100644 index e69de29..0000000 diff --git a/ircbot/modules/default/dcc_mod.conf b/ircbot/modules/default/dcc_mod.conf deleted file mode 100644 index 7caeedb..0000000 --- a/ircbot/modules/default/dcc_mod.conf +++ /dev/null @@ -1,81 +0,0 @@ -;+--------------------------------------------------------------------------- -;| PHP-IRC Internal DCC Function Configuration File -;| ======================================================== -;| by Manick -;| (c) 2001-2004 by http://phpbots.sf.net -;| Contact: manick@manekian.com -;| irc: #manekian@irc.rizon.net -;| ======================================== -;+--------------------------------------------------------------------------- -;| > This program is free software; you can redistribute it and/or -;| > modify it under the terms of the GNU General Public License -;| > as published by the Free Software Foundation; either version 2 -;| > of the License, or (at your option) any later version. -;| > -;| > This program is distributed in the hope that it will be useful, -;| > but WITHOUT ANY WARRANTY; without even the implied warranty of -;| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;| > GNU General Public License for more details. -;| > -;| > You should have received a copy of the GNU General Public License -;| > along with this program; if not, write to the Free Software -;| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -;+--------------------------------------------------------------------------- - -file dcc_mod modules/default/dcc_mod.php - -privmsg dcc_mod monitor_check -mode dcc_mod monitor_check -join dcc_mod monitor_check -kick dcc_mod monitor_check -part dcc_mod monitor_check - -;new feature in 2.2.0, section definitions -section standard "Standard Functions" -section channel "Channel Functions" -section dcc "DCC Functions" -section info "Information Functions" -section admin "Administrative Functions" -section comm "IRC/Communication Functions" - -dcc monitor ~; command text (typed in dcc iface) - 0 ~; number of required arguments - "<channel>" ~; argument descriptions <arg1> <arg2> (or however you damn well please to do it hehe ;) - "Show messages from channel in dcc chat interface" ~; description of command - true ~; must be admin to use this command? - dcc_mod ~; class name (see file import section above) - dcc_monitor ~; function name - channel ; section name - -dcc exit 0 "" "Exits the DCC interface" false dcc_mod dcc_exit standard -dcc raw 1 "<raw query>" "Sends raw query to server" true dcc_mod dcc_raw comm -dcc who 0 "" "See who\'s online" false dcc_mod dcc_who standard -dcc ignore 0 "" "View ignore list" true dcc_mod dcc_ignore admin -dcc rignore 1 "<host>" "Remove ignore for a specified host" true dcc_mod dcc_rignore admin -dcc clearqueue 0 "<user>" "Removes all text queues, or queues for a specified user." true dcc_mod dcc_clearqueue admin -dcc server 1 "<server> <port>" "Change server to specified server" true dcc_mod dcc_server admin -dcc chat 1 "<text>" "Sends message to all admin users using the DCC interface" true dcc_mod dcc_chat comm -dcc restart 0 "" "Reconnect to the current server" true dcc_mod dcc_restart admin -dcc say 2 "<channel> <text>" "Sends text to some channel" true dcc_mod dcc_say comm -dcc action 2 "<channel> <text>" "Sends text to some channel in /me format" true dcc_mod dcc_action comm -dcc users 0 "" "Shows users in all channels" true dcc_mod dcc_users info -dcc maintain 0 "<channel> <key>" "Shows maintained channels, and adds or removes one" true dcc_mod dcc_maintain channel -dcc help 0 "" "Get information about command(s)" false dcc_mod dcc_help standard -dcc join 1 "<channel>" "Join a channel" true dcc_mod dcc_join channel -dcc part 1 "<channel>" "Part a channel" true dcc_mod dcc_part channel -dcc rejoin 1 "<channel>" "Rejoin a channel" true dcc_mod dcc_rejoin channel -dcc status 0 "" "Get status of bot, same as 5 minute status update" true dcc_mod dcc_status info -dcc function 0 "<activate/deactivate> <function>" "See which functions are activated, or activate/deactivate a function" true dcc_mod dcc_function admin -dcc reloadfunc 0 "" "Reloads function definition file" true dcc_mod dcc_reloadfunc admin -dcc shutdown 0 "" "Shuts the bot down" true dcc_mod dcc_shutdown admin -dcc connect 0 "" "Force connection to server when disconnected" true dcc_mod dcc_connect admin -dcc rehash 0 "" "Reload the configuration file" true dcc_mod dcc_rehash admin -dcc send 2 "<nick> <file>" "Send a user a file" true dcc_mod dcc_send dcc -dcc dcc 0 "" "Check current dcc status" true dcc_mod dcc_dccs dcc -dcc close 1 "<id>" "Close a download, upload, or chat window" true dcc_mod dcc_close dcc -dcc upload 1 "<yes/no>" "Allow files to be sent to this bot" true dcc_mod dcc_upload dcc -dcc botinfo 0 "" "View information about the bot" true dcc_mod dcc_botinfo info -dcc timers 0 "" "View active timer information" true dcc_mod dcc_timers info -dcc listul 0 "" "List upload directory contents" true dcc_mod dcc_listul dcc -dcc modules 0 "" "List installed modules" true dcc_mod dcc_modules info -dcc spawn 1 "<config file>" "Spawn a new bot in this process" true dcc_mod dcc_spawn admin \ No newline at end of file diff --git a/ircbot/modules/default/dcc_mod.php b/ircbot/modules/default/dcc_mod.php deleted file mode 100644 index 68002d7..0000000 --- a/ircbot/modules/default/dcc_mod.php +++ /dev/null @@ -1,1057 +0,0 @@ -<?php -/* -+--------------------------------------------------------------------------- -| PHP-IRC v2.2.0 -| ======================================================== -| by Manick -| (c) 2001-2005 by http://phpbots.sf.net/ -| Contact: manick@manekian.com -| irc: #manekian@irc.rizon.net -| ======================================== -+--------------------------------------------------------------------------- -| > dcc_mod module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class dcc_mod extends module { - - public $title = "DCC Chat Utils"; - public $author = "Manick"; - public $version = "2.1.1"; - public $dontShow = true; - - public function init() - { - $this->timerClass->addTimer("dccstatus", $this, "sendStatus", "", 5*60); - } - - public function destroy() - { - $this->timerClass->removeTimer("dccstatus"); - } - - /* DCC Functions */ - - public $monitorList = array(); - - public function monitor_check($line, $args) - { - switch($line['cmd']) - { - case "PRIVMSG": - if (isset($this->monitorList[irc::myStrToLower($line['to'])])) - { - if (preg_match("/\1ACTION (.+?)\1/", $line['text'], $match)) - { - $this->dccClass->dccInform("CHAN: " . $line['to'] . ": * " . $line['fromNick'] . " " . $match[1]); - } - else - { - $this->dccClass->dccInform("CHAN: " . $line['to'] . ": <" . $line['fromNick'] . "> " . $line['text']); - } - } - break; - - case "MODE": - if ($line['fromNick'] != $this->ircClass->getNick()) - { - if (isset($this->monitorList[irc::myStrToLower($line['to'])])) - { - $this->dccClass->dccInform("CHAN: " . $line['to'] . ": *** " . $line['fromNick'] . " sets mode: ".$line['params']); - } - } - break; - - case "JOIN": - if ($line['fromNick'] != $this->ircClass->getNick()) - { - if (isset($this->monitorList[irc::myStrToLower($line['text'])])) - { - $this->dccClass->dccInform("CHAN: " . $line['text'] . ": *** " . $line['fromNick'] . " joined channel."); - } - } - break; - - case "PART": - if ($line['fromNick'] != $this->ircClass->getNick()) - { - if (isset($this->monitorList[irc::myStrToLower($line['to'])])) - { - $this->dccClass->dccInform("CHAN: " . $line['to'] . ": *** " . $line['fromNick'] . " parted channel."); - } - } - break; - - case "KICK": - if ($line['params'] != $this->ircClass->getNick()) - { - if (isset($this->monitorList[irc::myStrToLower($line['to'])])) - { - $this->dccClass->dccInform("CHAN: " . $line['to'] . ": *** " . $line['params'] . " was kicked by ".$line['fromNick']." (".$line['text'].")."); - } - } - - break; - - default: - break; - - } - } - - - public function dcc_botinfo($chat, $args) - { - - $chat->dccSend("PHP-IRC v" . VERSION . " [".VERSION_DATE."] by Manick (visit http://phpbots.sf.net/ to download)"); - $chat->dccSend("total running time of " . $this->ircClass->timeFormat($this->ircClass->getRunTime(), "%d days, %h hours, %m minutes, and %s seconds.")); - - $fd = @fopen("/proc/" . $this->ircClass->pid() . "/stat", "r"); - if ($fd !== false) - { - $stat = fread($fd, 1024); - fclose($fd); - - $stat_array = explode(" ", $stat); - - $pid = $stat_array[0]; - $comm = $stat_array[1]; - $utime = $stat_array[13]; - $stime = $stat_array[14]; - $vsize = $stat_array[22]; - $meminfo = number_format($vsize, 0, '.',','); - $u_time = number_format($utime / 100, 2,'.',','); - $s_time = number_format($stime / 100, 2,'.',','); - - $fd = @fopen("/proc/stat", "r"); - if ($fd !== false) - { - $stat = fread($fd, 1024); - fclose($fd); - - $stat = str_replace(" ", " ", $stat); - $stat_array_2 = explode(" ", $stat); - $totalutime = $stat_array_2[1]; - $totalstime = $stat_array_2[3]; - $u_percent = number_format($utime / $totalutime, 6,'.',','); - $s_percent = number_format($stime / $totalstime, 6,'.',','); - - $chat->dccSend("cpu usage: " . $u_time . "s user (" . $u_percent . "%), " . $s_time . "s system (" . $s_percent . "%)"); - } - - $chat->dccSend("memory usage: " . $meminfo . " bytes"); - - } - - $fd = @fopen("/proc/loadavg", "r"); - if ($fd !== false) - { - $loadavg = fread($fd, 1024); - $loadavg_array = explode(" ", $loadavg); - $loadavgs = $loadavg_array[0] . " " . $loadavg_array[1] . " " .$loadavg_array[2]; - fclose($fd); - - $chat->dccSend("cpu load averages: " . $loadavgs); - } - - $realname = $this->ircClass->getClientConf('realname') == "" ? "n/a" : $this->ircClass->getClientConf('realname'); - $upload = $this->ircClass->getClientConf('upload') == "yes" ? "yes" : "no"; - - $chat->dccSend("configured nick: " . $this->ircClass->getClientConf('nick') . ", " . - "actual nick: " . $this->ircClass->getNick() . ", realname: " . $realname); - - $chat->dccSend("upload is currently set to " . $upload); - - if ($this->ircClass->getStatusRaw() == STATUS_CONNECTED_REGISTERED) - { - $network = $this->ircClass->getServerConf('Network') == "" ? $this->ircClass->getClientConf('server') : $this->ircClass->getServerConf('Network'); - $chat->dccSend("current server: " . $network . "(" . $this->ircClass->getClientConf('server') . ") port: " . $this->ircClass->getClientConf('port')); - } - else - { - $chat->dccSend("current server: none"); - } - - $maintain = $this->ircClass->getMaintainedChannels(); - - $maintained = "n/a"; - - if (isset($maintain[0])) - { - $maintained = ""; - foreach ($maintain AS $chan) - { - $maintained .= $chan['CHANNEL'] . " "; - } - $maintained = trim($maintained); - $chat->dccSend("configured channels: " . $maintained); - } - - $channels = $this->ircClass->getChannelData(); - - foreach($channels AS $chanPtr) - { - $chat->dccSend("in channel " . strtoupper($chanPtr->name) . ": users: " . $chanPtr->count); - } - - $chat->dccSend("status line: " . $this->getStatus()); - $chat->dccSend("config file: " . $this->ircClass->getConfigFilename()); - - return; - - } - - public function dcc_connect($chat, $args) - { - $status = $this->ircClass->getStatusRaw(); - - if ($status == STATUS_ERROR) - { - $this->ircClass->reconnect(); - } - } - - - public function dcc_monitor($chat, $args) - { - if ($args['nargs'] == 0) - { - $chat->dccSend("The following channels are being monitored:"); - foreach ($this->monitorList AS $channel => $random) - { - $chat->dccSend($channel); - } - } - else - { - - $chan = irc::myStrToLower($args['arg1']); - - if (!isset($this->monitorList[$chan])) - { - $this->monitorList[$chan] = 1; - $chat->dccSend("The channel '" . $chan . "' is now being monitored."); - } - else - { - $chat->dccSend("The channel '" . $chan . "' was removed from the monitored list."); - unset($this->monitorList[$chan]); - } - } - - } - - - - public function dcc_who($chat, $args) - { - $dccList = $this->dccClass->getDccList(); - - $chat->dccSend("--- Users Online ---"); - $chat->dccSend("[id] <nick> <admin>"); - foreach ($dccList AS $chatBox) - { - if ($chatBox->type == CHAT) - { - $chat->dccSend("[" . $chatBox->id . "] " . $chatBox->nick . ($chatBox->isAdmin ? " (admin)" : "")); - } - } - } - - public function dcc_timers($chat, $args) - { - $timers = $this->timerClass->getTimers(); - - $chat->dccSend("Active Timers:"); - - if (count($timers) > 0) - { - $time = timers::getMicroTime(); - foreach ($timers AS $timer) - { - $interval = "interval(" . $timer->interval . " sec)"; - - $timeTillNext = round(($timer->nextRunTime - $time < 0 ? 0 : $timer->nextRunTime - $time), 0); - - $ttnext = irc::timeFormat($timeTillNext, "%m min, %s sec"); - - if (is_object($timer->class)) - { - $cName = get_class($timer->class); - } - else - { - $cName = ""; - } - - $tName = preg_replace("/([a-z0-9]){32}/", "", $timer->name); - if ($tName == "") - { - $tName = "(random hash)"; - } - - $cName = preg_replace("/_([a-z0-9]){32}/", "", $cName); - - $chat->dccSend("Timer " . BOLD . $tName . BOLD . ": func(" . $cName . "::" . $timer->func . ") " . $interval . ", Time till next run: " . $ttnext); - } - } - else - { - $chat->dccSend("There are currently no timers."); - } - - } - - public function dcc_reloadfunc($chat, $args) - { - if ($this->ircClass->getClientConf('functionfile') != "") - { - $stat = $this->parserClass->loadFuncs($this->ircClass->getClientConf('functionfile')); - $chat->dccSend("Function reload complete"); - if ($stat == true) - { - $chat->dccSend("There were errors loading a function file! Cached version may still be in use!"); - } - } - else - { - $chat->dccSend("No function file defined in config file."); - } - } - - public function dcc_rehash($chat, $args) - { - - $chat->dccSend("Rehashing main config file, please wait..."); - - $currConfig = $this->ircClass->getClientConf(); - $newConfig = bot::parseConfig($this->ircClass->getConfigFilename()); - - if ($newConfig == false) - { - $chat->dccSend("Could not find config file or IO error."); - return; - } - - $this->ircClass->setConfig($newConfig, $this->ircClass->getConfigFilename()); - - if ($currConfig['nick'] != $newConfig['nick']) - { - $chat->dccSend("Changing nick..."); - $this->ircClass->changeNick($newConfig['nick']); - } - - if ($currConfig['server'] != $newConfig['server']) - { - $chat->dccSend("Connecting to new server..."); - $this->ircClass->disconnect(); - $this->ircClass->reconnect(); - } - else - { - if (isset($currConfig['channel'])) - { - if (!is_array($currConfig['channel'])) - { - $currConfig['channel'] = array($currConfig['channel']); - } - if (!is_array($newConfig['channel'])) - { - $newConfig['channel'] = array($newConfig['channel']); - } - - foreach($currConfig['channel'] AS $chan) - { - if (!in_array($chan, $newConfig['channel'])) - { - $chan = trim($chan) . " "; - $chan = trim(substr($chan, 0, strpos($chan, chr(32)) + 1)); - $this->ircClass->sendRaw("PART " . $chan); - } - - } - } - } - - $this->ircClass->purgeMaintainList(); - - $chat->dccSend("Rehashing channel list..."); - bot::createChannelArray($this->ircClass); - - $chat->dccSend("Rehashing IP address..."); - if (isset($newConfig['natip'])) - { - if (isset($currConfig['natip'])) - { - if ($currConfig['natip'] != $newConfig['natip']) - { - $this->ircClass->setClientIP($newConfig['natip']); - } - } - else - { - $this->ircClass->setClientIP($newConfig['natip']); - } - } - else - { - if ($this->ircClass->getStatusRaw() != STATUS_CONNECTED_REGISTERED) - { - $chat->dccSend("NOTICE: Cannot reset IP address unless connected to server. No change made."); - } - else - { - $this->ircClass->setClientIP(); - } - } - - if (isset($newConfig['dccrangestart']) && $newConfig['dccrangestart'] != $currConfig['dccrangestart']) - { - $chat->dccSend("Updating TCP Range..."); - $this->socketClass->setTcpRange($newConfig['dccrangestart']); - } - - if (isset($newConfig['logfile']) && $newConfig['logfile'] != $currConfig['logfile']) - { - $chat->dccSend("Changing log file..."); - $this->ircClass->closeLog(); - } - - if (isset($newConfig['functionfile'])) - { - if ($newConfig['functionfile'] != $currConfig['functionfile']) - { - $this->parserClass->loadFuncs($newConfig['functionfile']); - } - } - else - { - $chat->dccSend("Fatal Error, functionfile directive not set. The performance of this bot is no longer guaranteed (please restart and fix your error)"); - return; - } - - $chat->dccSend("Main config rehash complete."); - - } - - public function dcc_join($chat, $args) - { - $chat->dccSend("Joining: " . $args['query']); - $this->ircClass->sendRaw("JOIN " . $args['query']); - } - - public function dcc_part($chat, $args) - { - $this->ircClass->sendRaw("PART " . $args['query']); - } - - public function dcc_rejoin($chat, $args) - { - $chanPtr = $this->ircClass->getChannelData($args['arg1']); - - if ($chanPtr == NULL) - { - $chat->dccSend("You are not on channel '" . $args['arg1'] . "'"); - } - else - { - $chat->dccSend("Rejoining: " . $args['arg1']); - $this->ircClass->sendRaw("JOIN " . $args['arg1']); - $this->ircClass->sendRaw("PART " . $args['arg1']); - } - } - - - public function dcc_shutdown($chat, $args) - { - $chat->dccSend("Shutting down, sending kill command to irc class."); - - if ($this->ircClass->getStatusRaw() == STATUS_CONNECTED_REGISTERED) - { - $time = $this->ircClass->timeFormat($this->ircClass->getRunTime(), "%dd%hh%mm%ss"); - $msg = "php-irc v" . VERSION . " by Manick, running ".$time; - $this->ircClass->sendRaw("QUIT :" . $msg); - } - - $chat->dccSend("Waiting for server queue to flush..."); - - $this->timerClass->addTimer("shutdown", $this->ircClass, "shutdown", "", 1); - } - - public function dcc_ignore($chat, $args) - { - $usageList = $this->ircClass->getUsageList(); - - $chat->dccSend("--- Usage List (* denotes active ignore) ---"); - - foreach($usageList AS $host => $user) - { - if (trim($host) != "") - { - if (intval($user->timeBanned) > 5) - { - $chat->dccSend(($user->isBanned == true ? "*" : "") . $host . ": " . (intval($user->timeBanned) > 5 ? date("m-d-y h:i:s a", $user->timeBanned) : "never banned")); - } - } - } - - - } - - public function dcc_rignore($chat, $args) - { - $usageList = $this->ircClass->getUsageList(); - - if (array_key_exists($args['arg1'], $usageList)) - { - $usageList[$args['arg1']]->isBanned = false; - $chat->dccSend("Ignore for " . $args['arg1'] . " successfully removed."); - } - else - { - $chat->dccSend("No such ignore."); - } - - } - - public function dcc_clearqueue($chat, $args) - { - if ($args['nargs'] > 0) - { - $this->ircClass->removeQueues($args['arg1']); - $chat->dccSend("All text queues for " . $args['arg1'] . " removed."); - } - else - { - $this->ircClass->purgeTextQueue(); - $chat->dccSend("All text queues purged."); - } - } - - - public function dcc_status($chat, $args) - { - $chat->dccSend($this->getStatus()); - } - - public function dcc_server($chat, $args) - { - $server = $args['arg1']; - $port = 6667; - - if ($args['nargs'] > 1) - { - $port = intval($args['arg2']); - if ($port == 0) - { - $port = 6667; - } - } - - $chat->dccSend("Changing server to: " . $server . ":" . $port); - $this->ircClass->setClientConfigVar('server', $server); - $this->ircClass->setClientConfigVar('port', $port); - $this->ircClass->disconnect(); - $this->ircClass->reconnect(); - } - - public function dcc_exit($chat, $args) - { - $this->dccClass->dccInform("DCC: " . $chat->nick . " logged off", $chat); - $chat->disconnect("User quit"); - } - - public function dcc_action($chat, $args) - { - $this->ircClass->action($args['arg1'], substr($args['query'], strlen($args['arg1']) + 1)); - } - - public function dcc_restart($chat, $args) - { - $this->ircClass->disconnect(); - } - - public function dcc_chat($chat, $args) - { - $this->dccClass->dccInform("CHAT: (" . $chat->nick . ")> " . $args['query'], $chat); - } - - public function dcc_raw($chat, $args) - { - $this->ircClass->sendRaw($args['query']); - } - - public function dcc_say($chat, $args) - { - $this->ircClass->privMsg($args['arg1'], substr($args['query'], strlen($args['arg1']) + 1)); - } - - public function dcc_users($chat, $args) - { - $chat->dccSend($this->ircClass->displayUsers()); - } - - public function dcc_upload($chat, $args) - { - $args['arg1'] = irc::myStrToLower($args['arg1']); - - if ($args['arg1'] == "yes") - { - $this->ircClass->setClientConfigVar('upload', 'yes'); - $chat->dccSend("Upload is now set to allow."); - } - else if ($args['arg1'] == "no") - { - $this->ircClass->setClientConfigVar('upload', 'no'); - $chat->dccSend("Upload is now set to deny."); - } - else - { - $chat->dccSend("Upload is currently set to: " . $this->ircClass->getClientConf('upload')); - $chat->dccSend("Valid syntax is 'yes' or 'no'."); - } - } - - - public function dcc_maintain($chat, $args) - { - if ($args['nargs'] == 0) - { - - $chat->dccSend("-- Maintained Channels --"); - $chans = $this->ircClass->getMaintainedChannels(); - - $num = 0; - foreach($chans AS $chan) - { - $chat->dccSend($chan['CHANNEL'] . - ($chan['KEY'] != "" ? " with key " . $chan['KEY'] : "")); - $num++; - } - - $chat->dccSend($num . " total channels"); - - } - else - { - $chanArg = irc::myStrToLower($args['arg1']); - - $chans = $this->ircClass->getMaintainedChannels(); - - $found = false; - foreach($chans AS $chan) - { - if ($chan['CHANNEL'] == $chanArg) - { - $found = true; - break; - } - } - - if ($found == true) - { - $this->ircClass->removeMaintain($chanArg); - $chat->dccSend("Channel " . $chanArg . " successfully removed from maintain list."); - } - else - { - $this->ircClass->maintainChannel($chanArg, ($args['nargs'] >= 2 ? $args['arg2'] : "")); - $chat->dccSend("Channel " . $chanArg . " is now being maintained" - . ($args['nargs'] >= 2 ? " with key " . $args['arg2'] : ".")); - - if ($this->ircClass->isOnline($this->ircClass->getNick(), $chanArg) == false) - { - $this->ircClass->joinChannel($chanArg . ($args['nargs'] >= 2 ? " " . $args['arg2'] : "")); - } - - } - - } - - - } - - public function dcc_help($chat, $args) - { - $cmdList = $this->parserClass->getCmdList('dcc'); - $sectionList = $this->parserClass->getCmdList('section'); - - if ($args['nargs'] > 0) - { - $cmd = $args['arg1']; - - if (isset($cmdList[$cmd])) - { - $chat->dccSend("Usage: " . $cmd . " " . $cmdList[$cmd]['usage']); - $chat->dccSend("Section: " . $sectionList[$cmdList[$cmd]['section']]['longname']); - $chat->dccSend("Description: " . $cmdList[$cmd]['help']); - } - else - { - $chat->dccSend("Invalid Command: " . $line['arg1']); - } - - return; - } - - $chat->dccSend("Commands:"); - - $sections = array(); - - foreach ($cmdList AS $cmd => $cmdData) - { - if (!$chat->isAdmin && $cmdData['admin'] == true) - { - continue; - } - - $sections[$cmdData['section']][] = strtoupper($cmd) . " - " . $cmdData['help']; - } - - foreach ($sections AS $section => $data) - { - $chat->dccSend($sectionList[$section]['longname']); - - foreach ($data AS $cmd) - { - $chat->dccSend("-- " . $cmd); - } - } - - $chat->dccSend("Use HELP <command> for a list of arguments"); - - - } - - public function dcc_modules($chat, $args) - { - $cmdList = $this->parserClass->getCmdList(); - - if (isset($cmdList['file'])) - { - $chat->dccSend("Installed Modules:"); - - foreach($cmdList['file'] AS $module) - { - $class = $module['class']; - - $chat->dccSend("-- " . $class->title . " " . $class->version . " by " . $class->author); - } - } - else - { - $chat->dccSend("There are no installed modules."); - } - } - - - public function dcc_close($chat, $args) - { - $dccList = $this->dccClass->getDccList(); - - foreach ($dccList AS $sockInt => $dcc) - { - if ($args['arg1'] == $dcc->id) - { - if ($dcc->type == CHAT && $dcc->isAdmin == true) - { - $chat->dccSend("Cannot close admin session!"); - return; - } - - $dcc->disconnect("Owner Requested Close"); - break; - } - } - } - - public function dcc_listul($chat, $args) - { - - $uldir = $this->ircClass->getClientConf('uploaddir'); - - if ($uldir != "") - { - $chat->dccSend("Directory Contents, " . $uldir); - - $dir = @scandir($uldir); - - $dirs = 0; - $files = 0; - - if (count($dir)) - { - - foreach ($dir AS $file) - { - if (is_dir($uldir . "/" . $file)) - { - $dirs++; - $chat->dccSend(BOLD . "dir: " . BOLD . $file); - } - else if (is_file($uldir . "/" . $file)) - { - $files++; - $chat->dccSend($file); - } - } - } - $chat->dccSend($dirs . " directories, " . $files . " files"); - - } - else - { - $chat->dccSend("Error, no uploaddir configuration directive set in config file."); - } - } - - - public function dcc_dccs($chat, $args) - { - $dccList = $this->dccClass->getDccList(); - $currDcc = false; - - foreach ($dccList AS $sockInt => $dcc) - { - if ($dcc->type == FILE) - { - $currDcc = true; - - if ($dcc->speed_lastavg == 0) - { - $percent = "0%"; - $eta = "n/a"; - $speed = 0.0; - } - else - { - $percent = round(($dcc->bytesTransfered/$dcc->filesize)*100, 1) . "%"; - $eta = $this->ircClass->timeFormat(round(($dcc->filesize - $dcc->bytesTransfered)/$dcc->speed_lastavg, 0), "%hh,%mm,%ss"); - $speed = irc::intToSizeString($dcc->speed_lastavg); - } - - if ($dcc->transferType == UPLOAD) - { - $chat->dccSend("Upload[{$dcc->id}]: " . $dcc->nick . " " . $dcc->filenameNoDir . " ".$percent." " . $speed . "/s eta:" . $eta); - } - else - { - $chat->dccSend("Download[{$dcc->id}]: " . $dcc->nick . " " . $dcc->filenameNoDir . " ".$percent." " . $speed . "/s eta:" . $eta); - } - } - } - - if ($currDcc == false) - { - $chat->dccSend("No dcc transfers in progress"); - } - } - - - public function dcc_send($chat, $args) - { - $filename = substr($args['query'], strlen($args['arg1']) + 1); - - $this->dccClass->addFile($args['arg1'], null, null, UPLOAD, $filename, null); - } - - public function dcc_function($chat, $args) - { - $cmdList = $this->parserClass->getCmdList(); - - if ($args['nargs'] == 0) - { - $chat->dccSend("-- All user-defined function status --"); - - $num = 0; - foreach ($cmdList['priv'] AS $cmd => $data) - { - $chat->dccSend($cmd . " => " . ($data['active'] == true ? "active" : "inactive") . ", Usage: " . $data['usage']); - $num++; - } - $chat->dccSend($num . " total functions."); - - } - else if ($args['nargs'] == 2) - { - if ($args['arg1'] == "activate") - { - if ($args['arg2'] == "all") - { - foreach($cmdList['priv'] AS $cmd => $data) - { - //$cmdList['priv'][$cmd]['active'] = true; - $this->parserClass->setCmdListValue('priv', $cmd, 'active', true); - } - $chat->dccSend("All functions activated."); - } - else - { - $cmdLower = irc::myStrToLower($args['arg2']); - - if (isset($cmdList['priv'][$cmdLower])) - { - $this->parserClass->setCmdListValue('priv', $cmdLower, 'active', true); - //$cmdList['priv'][$cmdLower]['active'] = true; - $chat->dccSend("Function " . $cmdLower . " activated."); - } - else - { - $chat->dccSend("Invalid function specified."); - } - } - } - else if ($args['arg1'] == "deactivate") - { - if ($args['arg2'] == "all") - { - foreach($cmdList['priv'] AS $cmd => $data) - { - if ($data['canDeactivate'] != false) - { - $this->parserClass->setCmdListValue('priv', $cmd, 'active', false); - //$cmdList['priv'][$cmd]['active'] = false; - } - } - $chat->dccSend("All functions deactivated."); - } - else - { - $cmdLower = irc::myStrToLower($args['arg2']); - - if (isset($cmdList['priv'][$cmdLower])) - { - if ($cmdList['priv'][$cmdLower]['canDeactivate'] != false) - { - $this->parserClass->setCmdListValue('priv', $cmdLower, 'active', false); - //$cmdList['priv'][$cmdLower]['active'] = false; - $chat->dccSend("Function " . $cmdLower . " deactivated."); - } - else - { - $chat->dccSend("Cannot modify read-only function " . $cmdLower . "."); - } - } - else - { - $chat->dccSend("Invalid function specified."); - } - } - } - else - { - $chat->dccSend("Invalid Syntax, use 'all', or specify a function name."); - } - - } - else - { - $chat->dccSend("Invalid Syntax, use 'activate' or 'deactivate'."); - } - } - - public function dcc_spawn($chat, $args) - { - $chat->dccSend("Spawning " . $args['query'] . "..."); - $result= bot::addBot($args['query']); - if($result === true) - $chat->dccSend($args['query'] . " successfully spawned"); - else - $chat->dccSend($args['query'] . " was not spawned"); - } - - private function getStatus() - { - $sqlCount = 0; - $bwStats = $this->ircClass->getStats(); - - if (is_object($this->db)) - { - $sqlCount = $this->db->numQueries(); - } - - $bwUp = irc::intToSizeString($bwStats['BYTESUP']); - $bwDown = irc::intToSizeString($bwStats['BYTESDOWN']); - - $fileBwUp = irc::intToSizeString($this->dccClass->getBytesUp()); - $fileBwDown = irc::intToSizeString($this->dccClass->getBytesDown()); - - $txtQueue = $this->ircClass->getTextQueueLength() + 1; - - $ircStat = $this->ircClass->getStatusString($this->ircClass->getStatusRaw()); - - $status = "Status: [" . $ircStat . "] ". $sqlCount . - " SQL, " . $txtQueue . " SrQ, (irc BW: " . $bwUp . " up, " . $bwDown . " down, file BW: " . $fileBwUp . " up, " . $fileBwDown . " down)"; - return $status; - } - - public function sendStatus() - { - $this->dccClass->dccInform($this->getStatus()); - return true; - } - -/* - NOTE: If you're reading this, you're really bored. Anyway, this is just something I'm keeping in here - in case I ever need it again. It was a debug mechanism for a hash class I wrote to replace the associative arrays - that the bot currently uses. - - dcc debug 1 "<chan/mem> [<channel>]" "Debug channel/member hash tables" true dcc_mod dcc_debug info - public function dcc_debug($chat, $args) - { - if ($args['arg1'] == "chan") - { - $chanData = $this->ircClass->getChannelData(); - - $chat->dccSend($chanData->getCount() . " total buckets"); - - foreach ($chanData->debug() AS $debug) - { - $chat->dccSend($debug); - } - } - else if ($args['arg1'] == "mem") - { - if ($args['nargs'] > 1) - { - $chanData = $this->ircClass->getChannelData(); - - $chanPtr = $chanData->find($args['arg2']); - - if ($chanPtr !== false) - { - $chat->dccSend($chanPtr->memberList->getCount() . " total buckets"); - - foreach ($chanPtr->memberList->debug() AS $debug) - { - $chat->dccSend($debug); - } - } - } - } - } -*/ -} -?> diff --git a/ircbot/modules/default/priv_mod.conf b/ircbot/modules/default/priv_mod.conf deleted file mode 100644 index a62cfd8..0000000 --- a/ircbot/modules/default/priv_mod.conf +++ /dev/null @@ -1,35 +0,0 @@ -;+--------------------------------------------------------------------------- -;| PHP-IRC Internal PRIVMSG Function Configuration File -;| ======================================================== -;| by Manick -;| (c) 2001-2004 by http://phpbots.sf.net -;| Contact: manick@manekian.com -;| irc: #manekian@irc.rizon.net -;| ======================================== -;+--------------------------------------------------------------------------- -;| > This program is free software; you can redistribute it and/or -;| > modify it under the terms of the GNU General Public License -;| > as published by the Free Software Foundation; either version 2 -;| > of the License, or (at your option) any later version. -;| > -;| > This program is distributed in the hope that it will be useful, -;| > but WITHOUT ANY WARRANTY; without even the implied warranty of -;| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -;| > GNU General Public License for more details. -;| > -;| > You should have received a copy of the GNU General Public License -;| > along with this program; if not, write to the Free Software -;| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -;+--------------------------------------------------------------------------- - -file priv_mod modules/default/priv_mod.php - -priv admin ~; text typed in the channel/pm (admin) - true ~; active command on statup? - false ~; inform admins in dcc chat iface if this command is used - false ~; can be deactivated with 'function' dcc command - 0 ~; times used.. just leave this 0 (its for stats). - priv_mod ~; class name (see file import section above) - priv_admin ; function name - -priv !ad true true true 0 priv_mod priv_ad \ No newline at end of file diff --git a/ircbot/modules/default/priv_mod.php b/ircbot/modules/default/priv_mod.php deleted file mode 100644 index 8aa76f5..0000000 --- a/ircbot/modules/default/priv_mod.php +++ /dev/null @@ -1,315 +0,0 @@ -<?php -/* -+--------------------------------------------------------------------------- -| PHP-IRC v2.2.0 -| ======================================================== -| by Manick -| (c) 2001-2005 by http://phpbots.sf.net/ -| Contact: manick@manekian.com -| irc: #manekian@irc.rizon.net -| ======================================== -+--------------------------------------------------------------------------- -| > priv_mod module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class priv_mod extends module { - - public $title = "Privmsg Utils"; - public $author = "Manick"; - public $version = "2.1.1"; - public $dontShow = true; - - private $ads; - - public function init() - { - $this->loadAds(); - } - - public function destroy() - { - $this->destroyAds(); - } - - private function loadAds() - { - $ads = new ini("./modules/default/ads.ini"); - - if ($ads->getError()) - { - return; - } - - $sections = $ads->getSections(); - - foreach ($sections AS $ad) - { - - $int = $ads->getIniVal($ad, "int"); - $channel = $ads->getIniVal($ad, "chan"); - $msg = $ads->getIniVal($ad, "msg"); - - $argArray = array('msg' => $msg, 'channel' => $channel); - - $this->timerClass->addTimer($ad, $this, "misc_adTimer", $argArray, $int); - - } - - $this->ads = $ads; - - } - - private function destroyAds() - { - $sections = $this->ads->getSections(); - - foreach ($sections AS $ad) - { - $this->timerClass->removeTimer($ad); - } - } - - // Misc Timer - - public function misc_adTimer($msg) - { - - $ad = DARK . "[" . BRIGHT . "Request" . DARK . "] - [" . BRIGHT . - $msg['msg'] . DARK . - "] - PHP-IRC v" . VERSION; - - $raw = "PRIVMSG " . $msg['channel'] . " :" . $ad; - - $this->ircClass->sendRaw($raw); - - return true; - } - - /* public Message/Channel Functions */ - - // This function is an example, it will display an add with timer - public function priv_ad($line, $args) - { - $channel = irc::myStrToLower($line['to']); - if ($channel == $this->ircClass->getNick()) - { - return; - } - if (!$this->ircClass->isMode($line['fromNick'], $channel, "o")) - { - return; - } - - if ($args['nargs'] == 0) - { - $timerString = ""; - $timers = $this->timerClass->getTimers(); - foreach ($timers AS $timer) - { - if (substr($timer->name, 0, 2) == "ad") - { - if ($timer->args['channel'] == $channel) - { - $timerString .= $timer->name . " "; - } - } - } - if ($timerString == "") - { - $this->ircClass->notice($line['fromNick'], "No ads currently for " . $channel . "."); - } - else - { - $this->ircClass->notice($line['fromNick'], "Current ads for " . $channel .":"); - $this->ircClass->notice($line['fromNick'], $timerString); - } - - $this->ircClass->notice($line['fromNick'], "Type !ad <interval(seconds)> <msg> to add an ad, or !ad <ad[id]> to view an ad."); - } - else if ($args['nargs'] >= 1) - { - if (substr($args['arg1'], 0, 2) == "ad" && strlen($args['arg1']) > 2) - { - $id = $args['arg1']; - - $timers = $this->timerClass->getTimers(); - foreach ($timers AS $timer) - { - if ($timer->name == $id) - { - break; - } - } - - if ($timer == null || $channel != $timer->args['channel']) - { - $this->ircClass->notice($line['fromNick'], "There is no ad by that id."); - } - else - { - if ($args['nargs'] >= 2) - { - if (irc::myStrToLower($args['arg2']) == "delete") - { - $this->ads->deleteSection($timer->name); - $this->ads->writeIni(); - - $this->timerClass->removeTimer($timer->name); - - $this->ircClass->notice($line['fromNick'], "Ad successfully deleted."); - } - else - { - $this->ircClass->notice($line['fromNick'], "Invalid option. Valid options: delete"); - } - } - else - { - $this->ircClass->notice($line['fromNick'], "Ad: " . $timer->name); - $this->ircClass->notice($line['fromNick'], $timer->args['msg']); - $this->ircClass->notice($line['fromNick'], "Use '!ad " . $timer->name . " delete' to delete this ad."); - } - } - - } - else - { - if ($args['nargs'] == 1) - { - $this->ircClass->notice($line['fromNick'], "You must specify a message!"); - } - else - { - $int = intval($args['arg1']); - - if ($int <= 5) - { - $this->ircClass->notice($line['fromNick'], "Invalid Interval. Interval must be greater than 5 seconds."); - } - else - { - $ad = substr($args['query'], strlen($args['arg1']) + 1); - - $argArray = array('msg' => $ad, 'channel' => $channel); - - //Find next id - $highest = 0; - $timers = $this->timerClass->getTimers(); - foreach ($timers AS $timer) - { - if (substr($timer->name, 0, 2) == "ad") - { - $id = intval(substr($timer->name, 2)); - if ($id > $highest) - { - $highest = $id; - } - } - } - $highest++; - - $this->timerClass->addTimer('ad' . $highest, $this, "misc_adTimer", $argArray, $int, true); - $this->ircClass->notice($line['fromNick'], "The ad was successfully added."); - - $this->ads->setIniVal('ad' . $highest, "int", $int); - $this->ads->setIniVal('ad' . $highest, "chan", $channel); - $this->ads->setIniVal('ad' . $highest, "msg", $ad); - $this->ads->writeIni(); - } - } - - } - - - } - } - - public function priv_admin($line, $args) - { - if ($args['nargs'] < 2) - { - return; - } - - if ($this->ircClass->getClientConf('dccadminpass') == "") - { - return; - } - - if (md5($args['arg1']) != $this->ircClass->getClientConf('dccadminpass')) - { - return; - } - - $query = substr($args['query'], strlen($args['arg1']) + 1); - $myArgs = parser::createLine($query); - - switch ($args['arg2']) - { - case "chatme": - $port = $this->dccClass->addChat($line['fromNick'], null, null, true, null); - if ($port === false) - { - $this->ircClass->notice($line['fromNick'], "Error starting chat, please try again.", 1); - } - break; - default: - $chat = new chat_wrapper($line['fromNick'], $this->ircClass); - - $cmdList = $this->parserClass->getCmdList(); - - $cmdLower = $myArgs['cmd']; - - if (isset($cmdList['dcc'][$cmdLower])) - { - - if ($myArgs['nargs'] < $cmdList['dcc'][$cmdLower]['numArgs']) - { - $chat->dccSend("Usage: " . $cmdLower . " " . $cmdList['dcc'][$cmdLower]['usage']); - break; - } - - $module = $cmdList['dcc'][$cmdLower]['module']; - $class = $cmdList['file'][$module]['class']; - $func = $cmdList['dcc'][$cmdLower]['function']; - - $class->$func($chat, $myArgs); - - $chat->dccSend("ADMIN " . irc::myStrToUpper($cmdLower) . " Requested"); - } - else - { - $chat->dccSend("Invalid Command: " . $myArgs['cmd']); - } - - break; - } - - } - - -} -?> diff --git a/ircbot/modules/lw/lw_mod.conf b/ircbot/modules/lw/lw_mod.conf deleted file mode 100644 index 44670c6..0000000 --- a/ircbot/modules/lw/lw_mod.conf +++ /dev/null @@ -1,21 +0,0 @@ -file lw_mod modules/lw/lw_mod.php - -priv !r true false false 0 lw_mod getRank -priv !rank true false false 0 lw_mod getRank - -priv !civ true false false 0 lw_mod getCivRank -priv !mil true false false 0 lw_mod getMilRank -priv !fin true false false 0 lw_mod getFinRank -priv !idr true false false 0 lw_mod getIDR - -priv !a true false false 0 lw_mod getAllianceRank -priv !arank true false false 0 lw_mod getAllianceRank - -priv !t true false false 0 lw_mod nextTick -priv !tick true false false 0 lw_mod nextTick - -priv !g true false false 0 lw_mod listGames -priv !games true false false 0 lw_mod listGames - -priv !h true false false 0 lw_mod help -priv !help true false false 0 lw_mod help diff --git a/ircbot/modules/lw/lw_mod.php b/ircbot/modules/lw/lw_mod.php deleted file mode 100644 index e8340c2..0000000 --- a/ircbot/modules/lw/lw_mod.php +++ /dev/null @@ -1,438 +0,0 @@ -<?php - - -class lw_mod extends module { - - public function init() { - } - - public function destroy() { - } - - public function nextTick($line, $args) { - $gameID = $args['nargs'] == 1 ? $args['query'] : null; - - // Get the game - $game = is_null($gameID) ? config::getDefaultGame() : config::getGame($gameID); - if (is_null($game)) { - $msg = "Game ID '" . BOLD . $gameID . BOLD . "' not found"; - } else { - // Try finding public ticks - $minTick = null; - foreach ($game->ticks as $tick) { - if (! $tick->definition->public) { - continue; - } - $tick->computeNext(); - if (is_null($tick->next)) { - continue; - } - if (is_null($minTick) || $minTick->next > $tick->next) { - $minTick = $tick; - } - } - - if (is_null($minTick)) { - $msg = "[" . BOLD . $game->text . BOLD . "] No more ticks on this game"; - } else { - $msg = "[" . BOLD . $game->text . BOLD . "] Next tick: " . BOLD - . $minTick->definition->getName('en') . BOLD . " at " . BOLD - . gmstrftime("%H:%M:%S", $minTick->next) . BOLD; - if (gmstrftime("%Y-%m-%d", $minTick->next) != gmstrftime("%Y-%m-%d", time())) { - $msg .= " on " . BOLD . gmstrftime("%d/%m/%Y", $minTick->next) . BOLD; - } - } - } - - if ($line['to'] == $this->ircClass->getClientConf('nick')) { - $to = $line['fromNick']; - } else { - $to = $line['to']; - } - - $this->ircClass->sendRaw("PRIVMSG $to :$msg"); - } - - public function listGames($line, $args) { - static $statusText = array( - "READY" => "open for registration", - "RUNNING" => "running", - "VICTORY" => "victory conditions reached", - "ENDING" => "being terminated", - "FINISHED" => "terminated" - ); - - $to = $line['fromNick']; - - dbConnect(); - foreach (config::getGames() as $game) { - if ($game->name == 'main' || $game->status() == 'PRE') { - continue; - } - - $msg = "(" . BOLD . $game->name . BOLD . ") " . BOLD . $game->text . BOLD . " - Status: " - . BOLD . $statusText[$game->status()] . BOLD; - if ($game->status() == "READY") { - $msg .= " - Starting at " . BOLD . gmstrftime("%H:%M:%S", $game->firstTick()) - . BOLD . " on " . BOLD . gmstrftime("%d/%m/%Y", $game->firstTick()) . BOLD; - } elseif ($game->status() == "ENDING") { - $msg .= " - Ending at " . BOLD . gmstrftime("%H:%M:%S", $game->lastTick()) - . BOLD . " on " . BOLD . gmstrftime("%d/%m/%Y", $game->lastTick()) . BOLD; - } - $this->ircClass->sendRaw("PRIVMSG $to :$msg"); - } - } - - public function getRank($line, $args) { - list($player, $game) = $this->getParams($line, $args); - - dbConnect(); - $rv = $this->fetchGenRank($player, $game); - dbClose(); - - if ($line['to'] == $this->ircClass->getClientConf('nick')) { - $to = $line['fromNick']; - } else { - $to = $line['to']; - } - - if (is_array($rv)) { - $msg = "[" . BOLD . $rv[0] . BOLD . "] Player " . BOLD . $player . BOLD - . ": " . BOLD . "#{$rv[1]['ranking']}" . BOLD . " (" . BOLD - . number_format($rv[1]['points']) . BOLD . " points)"; - if (! is_null($rv[2])) { - $msg .= " - Overall round ranking: " . BOLD . "#{$rv[2]['ranking']}" - . BOLD . " (" . BOLD . number_format($rv[2]['points']) - . BOLD . " points)"; - } - } elseif ($rv == 1) { - $msg = "Game ID '" . BOLD . $game . BOLD . "' not found"; - } elseif ($rv == 2) { - $msg = "Player " . BOLD . $player . BOLD . " not found"; - } - - $this->ircClass->sendRaw("PRIVMSG $to :$msg"); - } - - public function getCivRank($line, $args) { - list($player, $game) = $this->getParams($line, $args); - - dbConnect(); - $rv = $this->fetchDetRank($player, $game, 'p_civ'); - dbClose(); - - if ($line['to'] == $this->ircClass->getClientConf('nick')) { - $to = $line['fromNick']; - } else { - $to = $line['to']; - } - - if (is_array($rv)) { - $msg = "[" . BOLD . $rv[0] . BOLD . "] Player " . BOLD . $player . BOLD - . " (civilisation): " . BOLD . "#{$rv[1]['ranking']}" . BOLD . " (" . BOLD - . number_format($rv[1]['points']) . BOLD . " points)"; - } elseif ($rv == 1) { - $msg = "Game ID '" . BOLD . $game . BOLD . "' not found"; - } elseif ($rv == 2) { - $msg = "Player " . BOLD . $player . BOLD . " not found"; - } - - $this->ircClass->sendRaw("PRIVMSG $to :$msg"); - } - - public function getFinRank($line, $args) { - list($player, $game) = $this->getParams($line, $args); - - dbConnect(); - $rv = $this->fetchDetRank($player, $game, 'p_financial'); - dbClose(); - - if ($line['to'] == $this->ircClass->getClientConf('nick')) { - $to = $line['fromNick']; - } else { - $to = $line['to']; - } - - if (is_array($rv)) { - $msg = "[" . BOLD . $rv[0] . BOLD . "] Player " . BOLD . $player . BOLD - . " (financial): " . BOLD . "#{$rv[1]['ranking']}" . BOLD . " (" . BOLD - . number_format($rv[1]['points']) . BOLD . " points)"; - } elseif ($rv == 1) { - $msg = "Game ID '" . BOLD . $game . BOLD . "' not found"; - } elseif ($rv == 2) { - $msg = "Player " . BOLD . $player . BOLD . " not found"; - } - - $this->ircClass->sendRaw("PRIVMSG $to :$msg"); - } - - public function getMilRank($line, $args) { - list($player, $game) = $this->getParams($line, $args); - - dbConnect(); - $rv = $this->fetchDetRank($player, $game, 'p_military'); - dbClose(); - - if ($line['to'] == $this->ircClass->getClientConf('nick')) { - $to = $line['fromNick']; - } else { - $to = $line['to']; - } - - if (is_array($rv)) { - $msg = "[" . BOLD . $rv[0] . BOLD . "] Player " . BOLD . $player . BOLD - . " (military): " . BOLD . "#{$rv[1]['ranking']}" . BOLD . " (" . BOLD - . number_format($rv[1]['points']) . BOLD . " points)"; - } elseif ($rv == 1) { - $msg = "Game ID '" . BOLD . $game . BOLD . "' not found"; - } elseif ($rv == 2) { - $msg = "Player " . BOLD . $player . BOLD . " not found"; - } - - $this->ircClass->sendRaw("PRIVMSG $to :$msg"); - } - - public function getIDR($line, $args) { - list($player, $game) = $this->getParams($line, $args); - - dbConnect(); - $rv = $this->fetchDetRank($player, $game, 'p_idr'); - dbClose(); - - if ($line['to'] == $this->ircClass->getClientConf('nick')) { - $to = $line['fromNick']; - } else { - $to = $line['to']; - } - - if (is_array($rv)) { - $msg = "[" . BOLD . $rv[0] . BOLD . "] Player " . BOLD . $player . BOLD - . " (inflicted damage): " . BOLD . "#{$rv[1]['ranking']}" . BOLD . " (" . BOLD - . number_format($rv[1]['points']) . BOLD . " points)"; - } elseif ($rv == 1) { - $msg = "Game ID '" . BOLD . $game . BOLD . "' not found"; - } elseif ($rv == 2) { - $msg = "Player " . BOLD . $player . BOLD . " not found"; - } - - $this->ircClass->sendRaw("PRIVMSG $to :$msg"); - } - - - private function getParams($line, $args) { - if ($args['nargs'] == 0) { - $player = $line['fromNick']; - $game = null; - } else { - $query = explode(' ', trim(preg_replace('/\s+/', ' ', $args['query']))); - if (preg_match('/^{[a-z0-9]+}$/', $query[0], $matches)) { - $game = preg_replace('/[{}]/', '', array_shift($query)); - } else { - $game = null; - } - $player = join(' ', $query); - if ($player == '') { - $player = $line['fromNick']; - } - } - return array($player, $game); - } - - - private function fetchGenRank($player, $gameID) { - // Get the game - $game = is_null($gameID) ? config::getDefaultGame() : config::getGame($gameID); - if (is_null($game)) { - return 1; - } - - // Access the rankings library - $rLib = $game->getLib('main/rankings'); - - // Get player ranking - $rType = $rLib->call('getType', 'p_general'); - $genRank = $rLib->call('get', $rType, $player); - if (is_null($genRank['points'])) { - return 2; - } - - // Try getting the overall round rankings - $rType = $rLib->call('getType', 'p_round'); - $orRank = $rLib->call('get', $rType, $player); - if (is_null($orRank['points'])) { - $orRank = null; - } - return array($game->text, $genRank, $orRank); - } - - - private function fetchDetRank($player, $gameID, $type) { - // Get the game - $game = is_null($gameID) ? config::getDefaultGame() : config::getGame($gameID); - if (is_null($game)) { - return 1; - } - - // Access the rankings library - $rLib = $game->getLib('main/rankings'); - - // Get player ranking - $rType = $rLib->call('getType', $type); - $rank = $rLib->call('get', $rType, $player); - if (is_null($rank['points'])) { - return 2; - } - return array($game->text, $rank); - } - - - public function getAllianceRank($line, $args) { - list($alliance, $game) = $this->getParams($line, $args); - - dbConnect(); - $rv = $this->fetchDetRank($alliance, $game, 'a_general'); - dbClose(); - - if ($line['to'] == $this->ircClass->getClientConf('nick')) { - $to = $line['fromNick']; - } else { - $to = $line['to']; - } - - if (is_array($rv)) { - $msg = "[" . BOLD . $rv[0] . BOLD . "] Alliance " . BOLD . $alliance . BOLD - . ": " . BOLD . "#{$rv[1]['ranking']}" . BOLD . " (" . BOLD - . number_format($rv[1]['points']) . BOLD . " points)"; - } elseif ($rv == 1) { - $msg = "Game ID '" . BOLD . $game . BOLD . "' not found"; - } elseif ($rv == 2) { - $msg = "Alliance " . BOLD . $alliance . BOLD . " not found"; - } - - $this->ircClass->sendRaw("PRIVMSG $to :$msg"); - } - - public function help($line, $args) { - $help = array( - "" => array( - "This bot allows you to get some information from the", - "Legacy Worlds game directly here, on IRC!", - " ", - "You can use any of the following commands:", - " ", - " " . BOLD . "Displaying rankings" . BOLD, - " " . BOLD . "rank" . BOLD . " - displays players' general and round rankings", - " " . BOLD . "civ" . BOLD . " - displays players' civilian rankings", - " " . BOLD . "mil" . BOLD . " - displays players' military rankings", - " " . BOLD . "fin" . BOLD . " - displays players' financial rankings", - " " . BOLD . "idr" . BOLD . " - displays players' inflicted damage rankings", - " " . BOLD . "arank" . BOLD . " - displays alliances' rankings", - " ", - " " . BOLD . "General information" . BOLD, - " " . BOLD . "games" . BOLD . " - lists available games", - " " . BOLD . "tick" . BOLD . " - displays the time and date of the next tick", - " " . BOLD . "help" . BOLD . " - help access", - " ", - "All commands must start with the '!' character. To get more", - "information on a specific command, type '!help <command>'" - ), - "arank" => array( - "Syntax: " . BOLD . "!arank [{game}] tag", - " " . BOLD . "!a [{game}] tag", - " ", - "This command gives information about an alliance's ranking.", - " ", - "It is possible to select the game by adding the game's ID between", - "brackets just before the player's name.", - ), - "rank" => array( - "Syntax: " . BOLD . "!rank [{game}] [player]", - " " . BOLD . "!r [{game}] [player]", - " ", - "This command gives information about a player's general ranking", - "as well as his round ranking if he has one.", - " ", - "Using the command without parameters will cause the bot to look", - "for your current nick, if it's the same as your in-game name.", - " ", - "It is possible to select the game by adding the game's ID between", - "brackets just before the player's name.", - " ", - "Examples: !r TSeeker", - " -> Displays TSeeker's rankings in the default game", - " !r {b5m2}", - " -> Displays your rankings in Match 2", - ), - "civ" => array( - "Syntax: " . BOLD . "!civ [{game}] [player]", - " ", - "This command gives information about a player's civilisation", - "ranking.", - " ", - "Using the command without parameters will cause the bot to look", - "for your current nick, if it's the same as your in-game name.", - " ", - "It is possible to select the game by adding the game's ID between", - "brackets just before the player's name.", - " ", - "See also: " . BOLD . "!help rank" . BOLD - ), - "mil" => array( - "Syntax: " . BOLD . "!mil [{game}] [player]", - " ", - "This command gives information about a player's military", - "ranking.", - " ", - "Using the command without parameters will cause the bot to look", - "for your current nick, if it's the same as your in-game name.", - " ", - "It is possible to select the game by adding the game's ID between", - "brackets just before the player's name.", - " ", - "See also: " . BOLD . "!help rank" . BOLD - ), - "fin" => array( - "Syntax: " . BOLD . "!fin [{game}] [player]", - " ", - "This command gives information about a player's financial", - "ranking.", - " ", - "Using the command without parameters will cause the bot to look", - "for your current nick, if it's the same as your in-game name.", - " ", - "It is possible to select the game by adding the game's ID between", - "brackets just before the player's name.", - " ", - "See also: " . BOLD . "!help rank" . BOLD - ), - "tick" => array( - "Syntax: " . BOLD . "!tick [game]", - " " . BOLD . "!t [game]", - " ", - "This command displays the next tick.", - " ", - "It is possible to select the game by adding the game's ID", - "after the command.", - ), - "games" => array( - "Syntax: " . BOLD . "!games", - " " . BOLD . "!g", - " ", - "This command displays the list of available games.", - ), - ); - - $topic = $args['query']; - if (! array_key_exists($topic, $help)) { - $topic = ""; - } - - $to = $line['fromNick']; - for ($i = 0; $i < count($help[$topic]); $i ++) { - $this->ircClass->privMsg($to, $help[$topic][$i]); - } - } -} - -?> - diff --git a/ircbot/modules/more_mods.txt b/ircbot/modules/more_mods.txt deleted file mode 100644 index c176cd7..0000000 --- a/ircbot/modules/more_mods.txt +++ /dev/null @@ -1 +0,0 @@ -For More Modules, see the website: http://www.phpbots.org \ No newline at end of file diff --git a/ircbot/modules/seen/seen_mod.conf b/ircbot/modules/seen/seen_mod.conf deleted file mode 100644 index 40becc1..0000000 --- a/ircbot/modules/seen/seen_mod.conf +++ /dev/null @@ -1,11 +0,0 @@ - -file seen_mod modules/seen/seen_mod.php - -privmsg seen_mod seen -;notice seen_mod seen -join seen_mod seen -kick seen_mod seen -part seen_mod seen -quit seen_mod seen - -priv !seen true true true 0 seen_mod priv_seen \ No newline at end of file diff --git a/ircbot/modules/seen/seen_mod.php b/ircbot/modules/seen/seen_mod.php deleted file mode 100644 index fb0c31b..0000000 --- a/ircbot/modules/seen/seen_mod.php +++ /dev/null @@ -1,234 +0,0 @@ -<?php -/* -+--------------------------------------------------------------------------- -| PHP-IRC v2.2.0 -| ======================================================== -| by Manick -| (c) 2001-2005 by http://phpbots.sf.net/ -| Contact: manick@manekian.com -| irc: #manekian@irc.rizon.net -| ======================================== -+--------------------------------------------------------------------------- -| > Seen Mod -| > Module written by Manick -| > Module Version Number: 0.1 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class seen_mod extends module { - - public $title = "Seen Mod"; - public $author = "Manick"; - public $version = "0.1"; - - private $seen; - - public function init() - { - $this->timerClass->addTimer("seen_mod_updateini", $this, "seen_update", "", 60*15, false); - $this->seen = new ini("modules/seen/seen.ini"); - } - - public function destroy() - { - $this->timerClass->removeTimer("seen_mod_updateini"); - } - - // Write to file - public function seen_update($args) - { - if ($this->seen->getError()) - { - return; - } - - $this->seen->writeIni(); - $this->dccClass->dccSend("Updated Seen Mod ini database file"); - - return true; - } - - // Update actions - public function seen($line, $args) - { - if ($this->seen->getError()) - { - if (DEBUG == 1) - { - echo "Seen error!\n"; - } - return; - } - - if (strtolower($line['cmd']) == "join") - { - $line['text'] = ""; - } - - if (strtolower($line['cmd']) == "kick") - { - $offsetA = strpos($line['params'], chr(32)); - - $act = "kick"; - $user = substr($line['params'], $offsetA + 1); - - $this->addLast($user, $act, $line['text']); - - } - else - { - $this->addLast($line['fromNick'], strtolower($line['cmd']), $line['text']); - } - - $this->getLast($line['fromNick']); - } - - private function getLast($user) - { - $user = irc::myStrToLower($user); - - if (!$this->seen->sectionExists("seen")) - { - return; - } - - $var = $this->seen->getIniVal("seen", $user); - - if ($var == false) - { - return false; - } - - $offsetA = strpos($var, "="); - $offsetB = strpos($var, "=", $offsetA + 1); - $offsetC = strpos($var, "=", $offsetB + 1); - - $info = array(); - - $info['user'] = substr($var, 0, $offsetA); - $info['time'] = substr($var, $offsetA + 1, $offsetB - $offsetA - 1); - $info['act'] = substr($var, $offsetB + 1, $offsetC - $offsetB - 1); - $info['txt'] = substr($var, $offsetC + 1); - - return $info; - } - - private function addLast($user, $act, $txt) - { - $Suser = irc::myStrToLower($user); - - $tAction = $user . "=" . time() . "=" . irc::myStrToLower($act) . "=" . $txt; - $this->seen->setIniVal("seen", $Suser, $tAction); - } - - // User interface - public function priv_seen($line, $args) - { - if ($this->seen->getError()) - { - $this->ircClass->notice($line['fromNick'], "There was an error while attempting to access the seen database."); - return; - } - - if ($line['to'] == $this->ircClass->getNick()) - { - return; - } - - if ($args['nargs'] <= 0) - { - $this->ircClass->notice($line['fromNick'], "Usage: !seen <nick>"); - return; - } - - $user = irc::myStrToLower($args['arg1']); - - if ($user == irc::myStrToLower($line['fromNick'])) - { - $this->ircClass->privMsg($line['to'], $line['fromNick'] . ", umm... O..kay..."); - $this->ircClass->action($line['to'], "points at " . $line['fromNick'] . "..."); - return; - } - - $data = $this->getLast($user); - - if ($data === false) - { - $this->ircClass->privMsg($line['to'], $line['fromNick'] . ", I have never seen " . $args['arg1'] . " before."); - return; - } - - $time = time() - $data['time']; - - if ($time > 3600*24) - { - $timeString = irc::timeFormat($time, "%d days %h hours %m min %s sec"); - } - else if ($time > 3600) - { - $timeString = irc::timeFormat($time, "%h hours %m min %s sec"); - } - else if ($time > 60) - { - $timeString = irc::timeFormat($time, "%m min %s sec"); - } - else - { - $timeString = irc::timeFormat($time, "%s sec"); - } - - $action = ""; - - switch ($data['act']) - { - case "privmsg": - $action = "saying in a channel"; - break; - case "notice": - $action = "noticing a channel"; - break; - case "join": - $action = "joining a channel"; - break; - case "kick": - $action = "being kicked from a channel"; - break; - case "part": - $action = "parting a channel"; - break; - case "quit": - $action = "quitting"; - break; - } - - if ($data['txt'] != "") - { - $action .= ": " . $data['txt']; - } - - $this->ircClass->privMsg($line['to'], $line['fromNick'] . ", I last saw " . $data['user'] . " " . $timeString . " ago " . $action . "."); - - } -} - -?> diff --git a/ircbot/modules/template.txt b/ircbot/modules/template.txt deleted file mode 100644 index 4afaeb7..0000000 --- a/ircbot/modules/template.txt +++ /dev/null @@ -1,39 +0,0 @@ -<?php -/* - -Change: - -'class_name' to the name of your module (specified in function.conf) - -Add: - -Your functions after "//Methods here:" - -Add: - -Timer declarations and other general startup stuff to be run when the bot starts up in the init() function - -*/ - -class class_name extends module { - - public $title = "<title>"; - public $author = "<author>"; - public $version = "<version>"; - - public function init() - { - // Add your timer declarations and whatever - // else here... - } - - public function destroy() - { - // Put code here to destroy the timers that you created in init() - // and whatever else cleanup code you want. - } - - //Methods here: -} - -?> \ No newline at end of file diff --git a/ircbot/parser.php b/ircbot/parser.php deleted file mode 100644 index f8311c2..0000000 --- a/ircbot/parser.php +++ /dev/null @@ -1,1143 +0,0 @@ -<?php -/* -+--------------------------------------------------------------------------- -| PHP-IRC v2.2.1 Service Release -| ======================================================== -| by Manick -| (c) 2001-2005 by http://www.phpbots.org/ -| Contact: manick@manekian.com -| irc: #manekian@irc.rizon.net -| ======================================== -+--------------------------------------------------------------------------- -| > parser module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class parser { - - private $cmd; - private $args; - private $timers = array(); - - private $cmdList = array(); - private $cmdTypes = array(); - - private $fileModified = array(); - private $loadDefError = false; - - //Classes - private $ircClass; - private $dccClass; - private $timerClass; - private $socketClass; - private $db; - -/* Part of easy alias idea I've been working on..., look below for large bit of commented out code - for info... - - private $aliasArray = array( "notice" => "ircClass", - "privMsg" => "ircClass", - "action" => "ircClass", - "sendRaw" => "ircClass", - "getNick" => "ircClass", - "isOnline" => "ircClass", - "isMode" => "ircClass", - "isChanMode" => "ircClass", - "sendFile" => "dccClass", - "dccInform" => "dccClass", - "addTimer" => "timerClass", - "addListener" => "socketClass", - "removeTimer" => "timerClass", - ); -*/ - - public function __construct() { - $this->fileModified = array(); - } - - public function init() - { - - if ($this->ircClass->getClientConf('functionfile') != "") - { - $this->loadFuncs($this->ircClass->getClientConf('functionfile')); - } - - } - - public function setDccClass($class) - { - $this->dccClass = $class; - } - - public function setIrcClass($class) - { - $this->ircClass = $class; - } - - public function setTimerClass($class) - { - $this->timerClass = $class; - } - - public function setSocketClass($class) - { - $this->socketClass = $class; - } - - public function setDatabase($class) - { - $this->db = $class; - } - - public function getCmdList($type = "") - { - if ($type == "") - { - return $this->cmdList; - } - else - { - if (isset($this->cmdList[$type])) - { - return $this->cmdList[$type]; - } - else - { - return false; - } - } - } - - public function destroyModules() - { - if (is_array($this->cmdList) && count($this->cmdList) > 0) - { - if (isset($this->cmdList['file']) && is_array($this->cmdList['file'])) - { - foreach ($this->cmdList['file'] AS $index => $data) - { - if (is_object($data['class'])) - { - $data['class']->destroy(); - } - } - } - } - } - - private function readFile($file) - { - - $configRaw = file_get_contents($file); - - if ($configRaw === false) - { - if (DEBUG == 1) - { - echo "Could not find function file '$file' or error.\n"; - } - $this->dccClass->dccInform("Could not find function file '$file' or error."); - return false; - } - - return $configRaw; - - } - - public function include_recurse($file) - { - $configRaw = $this->readFile($file); - - if ($configRaw === false) - { - return false; - } - - $configRaw = preg_replace("/;(.*\n?)?/", "\n", $configRaw); - $configRaw = preg_replace("/~.*\n/", "", $configRaw); - - $configRaw = trim($configRaw); - - $lines = explode("\n", $configRaw); - - $num = 0; - $lineNo = 1; - $extra = 0; - $fullLine = ""; - foreach ($lines as $line) - { - $line = trim($line); - - if ($line == "") - { - $lineNo++; - continue; - } - - $line = trim($fullLine . " " . $line); - - $newLine = $this->parseFunc($file, $lineNo, $line); - - $lineNo += $extra + 1; - $extra = 0; - $fullLine = ""; - - if ($newLine === false) - { - continue; - } - - if ($newLine['type'] == "type") - { - $this->cmdTypes[$newLine['typeArray']['name']]['numArgs'] = count($newLine['typeArray']); - $this->cmdTypes[$newLine['typeArray']['name']]['args'] = $newLine['typeArray']; - } - else if ($newLine['type'] == "include") - { - if (isset($newLine['typeArray'][0])) - { - $num += $this->include_recurse($newLine['typeArray'][0]); - } - else - { - if (DEBUG == 1) - { - echo "Malformed include line on line " . $lineNo . " of function file: " . $file . "\n"; - } - $this->dccClass->dccInform("Malformed include line on line " . $lineNo . " of function file: " . $file); - } - } - else - { - if (!isset($newLine['typeArray']['name'])) - { - $name = irc::randomHash() . "_" . rand(1,1024); - } - else - { - $name = $newLine['typeArray']['name']; - } - - unset($newLine['typeArray']['name']); - - $this->cmdList[$newLine['type']][$name] = $newLine['typeArray']; - - if (isset($this->cmdList[$newLine['type']][$name]['usage'])) - { - if (isset($oldCmdList[$newLine['type']][$name]['usage'])) - { - $this->cmdList[$newLine['type']][$name]['usage'] = $oldCmdList[$newLine['type']][$name]['usage']; - } - } - - } - - $num++; - } - - return $num; - } - - - - - public function loadFuncs($file) - { - $error = false; - - clearstatcache(); - - $this->destroyModules(); - - $oldCmdList = $this->cmdList; - if (!is_array($oldCmdList)) - { - $oldCmdList = array(); - } - - unset($this->cmdList); - unset($this->cmdTypes); - $this->cmdList = array(); - $this->cmdTypes = array(); - - $this->dccClass->dccInform("Rehashing Function File, please wait..."); - if (DEBUG == 1) - { - echo "Rehashing Function File, please wait...\n"; - } - - //Read in main function file - $num = $this->include_recurse($file); - - //Book keeping - foreach ($this->cmdList AS $cmd => $data) - { - ksort($this->cmdList[$cmd]); - } - - if (isset($this->cmdList['file'])) - { - foreach ($this->cmdList['file'] AS $file => $data) - { - - $classDef = $this->loadClassDef($data['filename'], $file); - - if ($this->loadDefError == true) - { - $error = true; - } - $this->loadDefError = false; - - if ($classDef === false) - { - continue; - } - - //require_once($data['filename']); - - $this->cmdList['file'][$file]['class'] = new $classDef; - - $this->cmdList['file'][$file]['class']->__setClasses( $this->ircClass, - $this->dccClass, - $this->timerClass, - $this, - $this->socketClass, - $this->db - ); - $this->cmdList['file'][$file]['class']->init(); - } - } - - $this->dccClass->dccInform("Successfully loaded " . $num . " functions into memory."); - if (DEBUG == 1) - { - echo "Successfully loaded " . $num . " functions into memory.\n"; - } - - return $error; - - } - - private function loadClassError($filename, $msg) - { - $this->ircClass->log("Error loading $filename: $msg"); - $this->dccClass->dccInform("Error loading $filename: $msg"); - } - - /* Okay.. - * This method is really freaking cool. It loads a module file with fopen, then - * it finds the classname, and gives it a random name (changes it) so that you can - * include functions you've changed multiple times without having to restart the bot! - * Also, easier names than having to use $this->ircClass->blah() all the time, you can - * just use blah()... These are defined in an array somewhere... I'm not sure where yet... - * because I haven't written that yet!!!!!!!!!!!!111oneone. - */ - - private function loadClassDef($filename, $classname) - { - - $stat = stat($filename); - - if ($stat === false) - { - $this->loadClassError($filename, "Could not find function file"); - return false; - } - - $modified = $stat['mtime']; - - if (isset($this->fileModified[$filename])) - { - if ($modified == $this->fileModified[$filename]['modified']) - { - return $this->fileModified[$filename]['classdef']; - } - } - - $fileData = file_get_contents($filename); - - if ($fileData === false) - { - $this->loadClassError($filename, "Could not find function file"); - return false; - } - - //Okay, we have the module now.. now we need to find some stuff. - - if (!preg_match("/class[\s]+?".$classname."[\s]+?extends[\s]+?module[\s]+?{/", $fileData)) - { - $this->loadClassError($filename, "Could not find valid classdef in function file"); - return false; - } - - //Okay, our module is in the file... replace it with random hash. - - $newHash = irc::randomHash(); - - $newClassDef = $classname . "_" . $newHash; - - $fileData = preg_replace("/(class[\s]+?)".$classname."([\s]+?extends[\s]+?module[\s]+?{)/", "\\1" . $newClassDef . "\\2", $fileData); - - /* Interesting idea, but lets leave it out for now - foreach($this->aliasArray AS $func => $class) - { - $fileData = preg_replace("/([=\n\(\t\s]+?)".$func."[\s\t\n\r]*?\(/s", "\\1\$this->" . $class . "->" . $func . "(", $fileData); - } - */ - - $success = eval("?>" . $fileData . "<?php "); - - if ($success === false) - { - $this->loadClassError($filename, "Error in function file"); - - /* Attempt to fallback on a previous revision that worked! */ - if (isset($this->fileModified[$filename])) - { - $this->loadClassError($filename, "Using a cached version of the class definition"); - $this->loadDefError = true; - return $this->fileModified[$filename]['classdef']; - } - - return false; - } - - $this->fileModified[$filename]['modified'] = $modified; - $this->fileModified[$filename]['classdef'] = $newClassDef; - - return $newClassDef; - - } - - //Used to show array, as there seems to be some crazy bug in var_dump/print_r that - //shows EVERY variable in my program when I do var_dump($this->cmdList) or use print_r the same way - //This isn't used anywhere in the production copy of this script. (DEBUG ONLY!) - private function show_all($title, $array, $level) - { - echo $title . " = array(" . "\r\n"; - - foreach($array AS $index => $val) - { - for ($i = 0; $i < $level; $i++) - { - echo " "; - } - - if (is_array($val)) - { - $this->show_all($index, $val, $level + 1); - } - else if (is_object($val)) - { - echo "[$index] => [object]\r\n"; - } - else - { - echo "[$index] => [$val]\r\n"; - } - } - - for ($i = 0; $i < $level; $i++) - { - echo " "; - } - - echo ")\r\n"; - - } - - public function setCmdListValue($type, $cmd, $var, $value) - { - if (isset($this->cmdList[$type][$cmd][$var])) - { - $this->cmdList[$type][$cmd][$var] = $value; - return true; - } - return false; - } - - private function parseFunc($file, $lineNo, $line) - { - $strings = array(); - $line = str_replace("\t", " ", $line); - - $quotes = array("'", "\""); - - foreach($quotes AS $quote) - { - $currPos = 0; - $extraPos = 0; - while (($firstPos = strpos($line, $quote, $currPos)) !== false && substr($line, strpos($line, $quote, $currPos)-1, 1) != "\\") - { - - while (($secondPos = strpos($line, $quote, $firstPos + 1 + $extraPos)) !== false && substr($line, strpos($line, $quote, $firstPos + 1 + $extraPos)-1, 1) == "\\") - { - $extraPos = $secondPos; - } - - if ($secondPos === false) - { - if (DEBUG == 1) - { - echo "Syntax Error on line " . $lineNo . " of function file: " . $file . ". Expected '".$quote."', got end of line.\n"; - } - $this->dccClass->dccInform("Syntax Error on line " . $lineNo . " of function file: " . $file . ". Expected '".$quote."', got end of line."); - return false; - } - - $strings[$quote][] = substr($line, $firstPos + 1, $secondPos - $firstPos - 1); - $currPos = $secondPos + 1; - } - } - - foreach ($strings AS $string) - { - $line = str_replace($string, "", $line); - } - - $lineElements = explode(chr(32), $line); - - $type = ""; - $currElement = 0; - $typeArray = array(); - - foreach($lineElements AS $element) - { - if (trim($element) == "") - { - continue; - } - - $currElement++; - - if ($currElement == 1) - { - $element = irc::myStrToLower($element); - - if ($element == "type") - { - $type = "type"; - } - else if ($element == "include") - { - $type = "include"; - } - else - { - if (isset($this->cmdTypes[$element])) - { - $type = $element; - } - else - { - if (DEBUG == 1) - { - echo "Error: Undefined type, '" . $element . "' on line " . $lineNo . " of function file: " . $file . "\n"; - } - $this->dccClass->dccInform("Error: Undefined type, '" . $element . "' on line " . $lineNo . " of function file: " . $file . ""); - return false; - } - } - continue; - } - - if ($element == "\"\"") - { - $element = array_shift($strings["\""]); - } - else if ($element == "''") - { - $element = array_shift($strings["'"]); - } - - $element = str_replace("\\" . "'", "'", $element); - $element = str_replace("\\" . '"', '"', $element); - - if ($type == "type") - { - if ($currElement == 2) - { - $typeArray['name'] = $element; - } - else - { - $typeArray[] = $element; - } - } - else if ($type == "include") - { - $typeArray[] = $element; - } - else - { - if ($currElement > $this->cmdTypes[$type]['numArgs']) - { - if (DEBUG == 1) - { - echo "Error on line " . $lineNo . " of function file: " . $file . ", too many arguments\n"; - } - $this->dccClass->dccInform("Error on line " . $lineNo . " of function file: " . $file . ", too many arguments"); - return false; - } - - $element = (irc::myStrToLower($element) == "true" ? true : $element); - $element = (irc::myStrToLower($element) == "false" ? false : $element); - - $typeArray[$this->cmdTypes[$type]['args'][ $currElement - 2 ]] = $element; - } - - - } - - if ($type != "type" && $type != "include") - { - if ($currElement < $this->cmdTypes[$type]['numArgs']) - { - if (DEBUG == 1) - { - echo "Error on line " . $lineNo . " of function file: " . $file . ", not enough arguments\n"; - } - $this->dccClass->dccInform("Error on line " . $lineNo . " of function file: " . $file . ", not enough arguments"); - return false; - } - } - - return array('type' => $type, 'typeArray' => $typeArray); - - } - - - - public function parseDcc($chat, $handler) - { - - $chat->readQueue = str_replace("\r", "", $chat->readQueue); - -// if (!($offSet = strpos($chat->readQueue, "\n"))) -// { -// return false; -// } -// $rawLine = trim(substr($chat->readQueue, 0, $offSet)); -// $chat->readQueue = substr($chat->readQueue, $offSet + 1); - - $rawLine = $chat->readQueue; - $chat->readQueue = ""; - - $this->ircClass->log("DCC Chat(" . $chat->nick . "): " . $rawLine); - - $line = $this->createLine($rawLine); - - if ($line == false) - { - return; - } - - if ($handler != false) - { - if (is_object($handler)) - { - $handler->handle($chat, $line); - return; - } - } - - if ($chat->isAdmin == true && $chat->verified == false) - { - if (md5($line['cmd']) == $this->ircClass->getClientConf('dccadminpass')) - { - $this->dccClass->dccInform("DCC: " . $chat->nick . " has successfully logged in."); - $chat->verified = true; - $chat->dccSend("You have successfully logged in."); - - } - else - { - $chat->dccSend("Invalid password, bye bye."); - $this->dccClass->disconnect($chat); - } - return; - } - - $cmdLower = irc::myStrToLower($line['cmd']); - - if (isset($this->cmdList['dcc'][$cmdLower])) - { - if ($this->cmdList['dcc'][$cmdLower]['admin'] == 1 && !$chat->isAdmin) - { - $chat->dccSend("Request Denied. You must have admin access to use this function."); - return; - } - - if ($line['nargs'] < $this->cmdList['dcc'][$cmdLower]['numArgs']) - { - $chat->dccSend("Usage: " . $cmdLower . " " . $this->cmdList['dcc'][$cmdLower]['usage']); - return; - } - - $module = $this->cmdList['dcc'][$cmdLower]['module']; - $class = $this->cmdList['file'][$module]['class']; - $func = $this->cmdList['dcc'][$cmdLower]['function']; - - $class->$func($chat, $line); - - if ($chat->isAdmin) - { - $chat->dccSend("ADMIN " . irc::myStrToUpper($cmdLower) . " Requested"); - } - else - { - $chat->dccSend("CLIENT " . irc::myStrToUpper($cmdLower) . " Requested"); - } - } - else - { - $chat->dccSend("Invalid Command: " . $line['cmd']); - } - - } - - - public static function createLine($rawLine) - { - - $line = array(); - $rawLineArray = explode(chr(32), $rawLine); - $lineCount = count($rawLineArray); - - if ($lineCount < 1) - { - return false; - } - else if ($lineCount == 1) - { - $line['cmd'] = irc::myStrToLower($rawLine); - $line['nargs'] = 0; - $line['query'] = ""; - } - else - { - $line['nargs'] = 0; - $line['cmd'] = irc::myStrToLower(array_shift($rawLineArray)); - while (($arg = array_shift($rawLineArray)) !== NULL) // NULL fixed contributed by cortex, 05/01/05 - { - if (trim($arg) == "") - { - continue; - } - - $line['arg' . ++$line['nargs']] = $arg; - if ($line['nargs'] > MAX_ARGS-1) - { - break; - } - } - $line['query'] = trim(substr($rawLine, strlen($line['cmd']) + 1)); - } - - return $line; - - } - - public function parseLine($line) - { - if (DEBUG==1) - { - //print_r($line); - } - - if ($this->ircClass->checkIgnore($line['from'])) - { - return; - } - - switch($line['cmd']) - { - case "PRIVMSG": - $args = $this->createLine($line['text']); - $cmdLower = irc::myStrToLower($args['cmd']); - if (isset($this->cmdList['priv'][$cmdLower])) - { - if ($this->cmdList['priv'][$cmdLower]['active'] == true) - { - $theCase = $this->ircClass->floodCheck($line); - - switch ($theCase) - { - case STATUS_NOT_BANNED: - if ($this->cmdList['priv'][$cmdLower]['inform'] == true) - { - $this->dccClass->dccInform("Sending " . irc::myStrToUpper($line['text']) . " to " . $line['fromNick']); - } - $this->cmdList['priv'][$cmdLower]['usage']++; - $func = $this->cmdList['priv'][$cmdLower]['function']; - $module = $this->cmdList['priv'][$cmdLower]['module']; - $class = $this->cmdList['file'][$module]['class']; - - if ($this->ircClass->getTextQueueLength() > 5) - { - $this->ircClass->notice($line['fromNick'], "Request Queued. Please wait " . $this->ircClass->getTextQueueLength() . " seconds for your data.", 0); - } - - $class->$func($line, $args); - break; - case STATUS_JUST_BANNED: - $this->ircClass->notice($line['fromNick'], "Flood Detected. All of your queues have been discarded and you have been banned from using this bot for ". $this->ircClass->getClientConf('floodtime') . " seconds."); - $this->dccClass->dccInform("BAN: (*!". irc::myStrToUpper($line['fromHost']) . "): " . $line['fromNick'] . " is on ignore for " . $this->ircClass->getClientConf('floodtime') . " seconds."); - break; - case STATUS_ALREADY_BANNED: - break; - } - } - else - { - $this->dccClass->dccInform("FUNCTION: " . $line['fromNick'] . " attempted to use deactivated command '" . $cmdLower . "'"); - } - } - else - { - if ($line['to'] == $this->ircClass->getNick()) - { - if (strpos($line['text'], chr(1)) !== false) - { - $this->ircClass->floodCheck($line); - $this->parseCtcp($line); - } - else - { - $this->dccClass->dccInform("PRIVMSG: <" . $line['fromNick'] . "> " . $line['text']); - } - } - else - { - if (strpos($line['text'], chr(1)) !== false) - { - $this->parseCtcp($line, "CHAN: " . $line['to']); - } - else - { - $chanData = $this->ircClass->getChannelData($line['to']); - - if ($chanData == NULL) - { - $this->dccClass->dccInform("CHAN PRIVMSG [".$line['to']."]: <" . $line['fromNick'] . "> " . $line['text']); - } - } - } - } - break; - - case "MODE": - break; - - case "NOTICE": - $chan = $line['to'] != $this->ircClass->getNick() ? ":" . $line['to'] : ""; - $this->dccClass->dccInform("NOTICE: <" . ($line['fromNick'] == "" ? $line['from'] : $line['fromNick']) . $chan . "> " . $line['text']); - break; - - case "JOIN": - if ($line['fromNick'] == $this->ircClass->getNick()) - { - $this->dccClass->dccInform("Joined: " . irc::myStrToUpper($line['text'])); - } - break; - - case "PART": - if ($line['fromNick'] == $this->ircClass->getNick()) - { - $this->dccClass->dccInform("Parted: " . irc::myStrToUpper($line['to'])); - } - break; - - case "KICK": - if ($line['params'] == $this->ircClass->getNick()) - { - $this->dccClass->dccInform("Kicked: " . $line['fromNick'] . " kicked you from " . $line['to']); - } - break; - - case "ERROR": - $this->dccClass->dccInform("Server Error: " . $line['text']); - break; - - case "366": - $params = explode(chr(32), $line['params']); - $channel = $params[0]; - $this->dccClass->dccInform("Finished receiving NAMES list for " . $channel); - break; - - case "005": - if ($this->ircClass->getServerConf("NETWORK") != "") - { - //Only show this once... - if (strpos($line['params'],"NETWORK") !== false) - { - $this->dccClass->dccInform("Parsing IRC-Server specific configuration..."); - $this->dccClass->dccInform("Network has been identified as " . $this->ircClass->getServerConf("NETWORK") . - "(" . $line['from'] . ")"); - } - } - break; - - case "315": - $params = explode(chr(32), $line['params']); - $this->dccClass->dccInform("Finished receiving WHO list for: " . $params[0]); - break; - - case "368": - $params = explode(chr(32), $line['params']); - $this->dccClass->dccInform("Finished receiving ban list for: " . $params[0]); - break; - - case "433": - $this->dccClass->dccInform("Nick collision! Unable to change your nick. Nickname already in use!"); - break; - - default: - break; - - } - - // Lets alias 004 to CONNECT, for the n00bs - - if ($line['cmd'] == "004") - { - $line['cmd'] = "connect"; - } - if ($line['cmd'] == "error") - { - $line['cmd'] = "disconnect"; - } - - // Action type handler - if (isset($this->cmdList['action']) && strtolower($line['cmd']) == "privmsg") - { - if (substr($line['text'], 0, 8) == chr(1) . "ACTION ") - { - $newLine = $line; - $newLine['text'] = substr($line['text'], 8, strlen($line['text']) - 9); - - $sArgs = $this->createLine($newLine['text']); - - foreach($this->cmdList['action'] AS $item) - { - $func = $item['function']; - $class = $this->cmdList['file'][$item['module']]['class']; - $class->$func($newLine, $sArgs); - } - } - } - - // Raw type handler - if (isset($this->cmdList['raw'])) - { - if (!isset($args)) - { - $args = $this->createLine($line['text']); - } - - foreach($this->cmdList['raw'] AS $item) - { - $func = $item['function']; - $class = $this->cmdList['file'][$item['module']]['class']; - $class->$func($line, $args); - } - } - - - // Here we will call any type - - if (isset($this->cmdList[irc::myStrToLower($line['cmd'])])) - { - if (!isset($args)) - { - $args = $this->createLine($line['text']); - } - - foreach($this->cmdList[irc::myStrToLower($line['cmd'])] AS $item) - { - $func = $item['function']; - $class = $this->cmdList['file'][$item['module']]['class']; - $class->$func($line, $args); - } - } - - if (isset($args)) - { - unset($args); - } - - } - - - /* Misc Functions */ - - private function parseCtcp($line, $msgs = "PRIVMSG") - { - $cmd = str_replace(chr(1), "", $line['text']) . " "; - $query = trim(substr($cmd, strpos($cmd, chr(32)) + 1)); - $cmd = substr(irc::myStrToLower($cmd), 0, strpos($cmd, chr(32))); - - $msg = ""; - - switch($cmd) - { - case "version": - $this->dccClass->dccInform("CTCP VERSION: " . $line['fromNick'] . " versioned us."); - break; - - case "time": - $this->dccClass->dccInform("CTCP TIME: " . $line['fromNick'] . " requested the time."); - break; - - case "uptime": - $this->dccClass->dccInform("CTCP UPTIME: " . $line['fromNick'] . " requested our uptime."); - break; - - case "ping": - $this->dccClass->dccInform("CTCP PING: " . $line['fromNick'] . " pinged us."); - break; - - case "dcc": - $vars = explode(chr(32), $query); - $this->dccParse($line, $vars, $query); - break; - - } - - if ($msg != "") - { - $this->notice($this->lVars['fromNick'], chr(1) . $msg . chr(1)); - } - - if (isset($this->cmdList['ctcp'][$cmd])) - { - $func = $this->cmdList['ctcp'][$cmd]['function']; - $class = $this->cmdList['file'][$this->cmdList['ctcp'][$cmd]['module']]['class']; - $args = $this->createLine($cmd . " " . $query); - $class->$func($line, $args); - } - - } - - function dccParse($line, $vars, $txt) - { - $cVars = count($vars); - - if ($cVars < 1) - { - return; - } - - $cmd = irc::myStrToUpper($vars[0]); - - switch ($cmd) - { - case "CHAT": - if ($cVars == 4) - { - $iplong = long2ip( (double) $vars[2]); - $port = $vars[3]; - $this->dccClass->addChat($line['fromNick'], $iplong, (int) $port, false, null); - } - break; - case "SEND": - if ($this->ircClass->getClientConf('upload') != 'yes') - { - $this->ircClass->notice($line['fromNick'], "DCC: I do not accept dcc transfers at this time.", 0); - break; - } - if ($cVars >= 5) - { - //Some bastard sent a file with spaces. Shit. Ass. - if (strpos($query, chr(34)) !== false) - { - $first = strpos($query, chr(34)); - $second = strpos($query, chr(34), $first + 1); - $filename = substr($query, $first + 1, $second - $first - 1); - $query = str_replace("\"".$filename."\"", "file.ext", $query); - $vars = explode(chr(32), $query); - } - else - { - $filename = $vars[1]; - } - - $iplong = long2ip( (double) $vars[2]); - $port = $vars[3]; - $filesize = $vars[4]; - - $this->dccClass->addFile($line['fromNick'], $iplong, (int) $port, DOWNLOAD, $filename, $filesize); - } - break; - case "ACCEPT": - if ($cVars == 4) - { - $port = $vars[2]; - $bytes = $vars[3]; - $this->dccClass->dccAccept($port, $bytes); - } - break; - case "RESUME": - if ($cVars == 4) - { - $port = $vars[2]; - $bytes = $vars[3]; - $this->dccClass->dccResume($port, $bytes); - } - break; - } - - } - -} - -/* Used to access dcc admin commands via private message */ -class chat_wrapper { - - public $nick; - private $ircClass; - public $isAdmin; - - public function __construct($nick, $ircClass) - { - $this->nick = $nick; - $this->ircClass = $ircClass; - $this->isAdmin = 1; - } - - public function dccSend($data, $to = null) - { - $this->ircClass->privMsg($this->nick, "--> " . $data); - } - - public function disconnect($msg = "") - { - $this->ircClass->privMsg($this->nick, "Right........"); - } - -} - -?> diff --git a/ircbot/queue.php b/ircbot/queue.php deleted file mode 100644 index e41101c..0000000 --- a/ircbot/queue.php +++ /dev/null @@ -1,339 +0,0 @@ -<?php -/* -+--------------------------------------------------------------------------- -| PHP-IRC v2.2.1 Service Release -| ======================================================== -| by Manick -| (c) 2001-2005 by http://www.phpbots.org/ -| Contact: manick@manekian.com -| irc: #manekian@irc.rizon.net -| ======================================== -+--------------------------------------------------------------------------- -| > queue module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -/* This module is my response to a big problem. PHP-IRC, on idling, would use - * 2.0% or more of the CPU on a 500mhz machine. This annoyed me, and I decided - * to do something about it. So, I changed the way that PHP-IRC works, from a - * "round-robin" approach to an "interrupt" type approach. Whenever something - * happens, say, new data is read from a socket, a process Queue is added with - * a pointer to the function that reads input for that socket; or for - * another example, if a file transfer is in effect, and new data is read from - * that socket, but we also have a dcc chat going, we will only handle data for - * the file transfer, instead of wasting CPU cycles on the dcc chat, like is - * currently done in <=2.1.1. I've learned a bit more about timers and socket - * timeouts since then. Also, we have to handle timers in a different way now. - * There will still be a "timers" class, for re-occuring processes, but the - * next timer is inserted into this process queue, and the callback for the timer - * will be a pointer to the timer class which handles the timer. Then, the timer - * class will do the appropriate stuff for the timer, and then add the next timer - * into the process Queue. --Manick - * - * P.S.; I never knew this would change so much code... I figured adding in select() - * timeouts would be a piece of cake... until I realized that my whole framework - * was incompatible with the idea. What a pain in the ass -_-. - */ - - /* Module Written 11/30/04 by Manick */ - -class processQueue { - - private $numQueued; - private $queuedItems; - private $currProc; - - function __construct() - { - $this->queuedItemsArray = array(); - $this->queuedItems = NULL; - $this->currProc = NULL; - $this->numQueued = 0; - } - - public function getNumQueued() - { - return $this->numQueued; - } - - public static function getMicroTime() - { - return microtime(true); - } - - /* Only allow removal of entire irc class (as in we shut down the bot.. otherwise, we don't - want to deal with shutting down specific queues during the queueing process. Have the callbacks - handle that themselves. We only have to worry when the callbacks won't exist anymore, as when an - irc bot is shut down, and the ircclass is discarded - */ - public function removeOwner($class) - { - $next = NULL; - - for ($queue = $this->queuedItems; $queue != NULL; ) - { - $next = $queue->next; - - if ($queue->owner === $class) - { - $this->removeQueue($queue); - } - - $queue = $next; - - } - } - - /* Remove reference to queued item, let PHP5 do the rest */ - private function removeQueue($item) - { - if ($item->prev == NULL) - { - $this->queuedItems = $item->next; - - if ($item->next != NULL) - { - $item->next->prev = NULL; - } - } - else - { - $item->prev->next = $item->next; - - if ($item->next != NULL) - { - $item->next->prev = $item->prev; - } - } - - $item->removed = true; - - unset($item->args); - unset($item->owner); - unset($item->callBack_class); - unset($item->next); - unset($item->prev); - - unset($item); - - $this->numQueued--; - } - - /* Add an item to the process queue */ - public function addQueue($owner, $class, $function, $args, $nextRunTime) - { -// echo "Queue Added: $function with $nextRunTime\n"; - - if ($function == "" || $function == NULL) - { - return false; - } - - if (!is_object($class)) - { - $class = null; - } - - $nextRunTime = floatval($nextRunTime); - - $queue = new queueItem; - - $queue->args = $args; - $queue->owner = $owner; - $queue->removed = false; - $queue->callBack_class = $class; - $queue->callBack_function = $function; - $queue->nextRunTime = self::getMicroTime() + $nextRunTime; - - //Now insert as sorted into queue - - $prev = NULL; - - for ($item = $this->queuedItems; $item != NULL; $item = $item->next) - { - if ($queue->nextRunTime < $item->nextRunTime) - { - break; - } - - $prev = $item; - } - - if ($item == NULL) - { - if ($prev == NULL) - { - $queue->next = NULL; - $queue->prev = NULL; - $this->queuedItems = $queue; - } - else - { - $queue->next = NULL; - $queue->prev = $prev; - $prev->next = $queue; - } - } - else - { - if ($item->prev == NULL) - { - $queue->next = $this->queuedItems; - $queue->prev = NULL; - - $item->prev = $queue; - $this->queuedItems = $queue; - } - else - { - $queue->next = $item; - $queue->prev = $item->prev; - - $item->prev = $queue; - $queue->prev->next = $queue; - } - } - - //Okay, we're inserted, return true; - - $this->numQueued++; - - return true; - } - - public function displayQueue() - { - //Used for debug - echo "Current Time: " . self::getMicroTime() . "\n"; - - echo "\n\n"; - for ($i = $this->queuedItems; $i != NULL; $i = $i->next) - { - echo $i->callBack_function . "-" . $i->nextRunTime . "\n"; - echo "---" . "Prev: " . $i->prev . " Next: " . $i->next . " Me: " . $i . "\n"; - } - echo "\n\n"; - } - - /* Handle the process queue, return the time until the next item */ - public function handle() - { - // Handle all items with $queue->nextRunTime < getMicroTime(), then return with time until next item must - // be run - - // Populate a runQueue with all current items that need to be run. We need to do this because some of these - // callback functions might add another process to the queue, and if the runtime is < 0, we would run that item - // instead of timing out before we do. If we have something like a file transfer, this could be a bad thing. - $runQueue = array(); - - $time = self::getMicroTime(); - - for ($item = $this->queuedItems; $item != NULL; $item = $item->next) - { - if ($item->nextRunTime <= $time) - { - $runQueue[] = $item; - } - else - { - break; - } - } - - //Okay, now run each item. - - foreach ($runQueue AS $index => $item) - { - if (!is_object($item) || $item->removed === true) - { - if (is_object($item)) - { - unset($item); - } - continue; - } - - self::handleQueueItem($item); - } - - unset($runQueue); - - //Return time until next item needs to be run, or true if there are no queued items - //Hmm, true returned here, means we'll just sleep for like an hour or something until data - //is recieved from the sockets, because we have no active timers - if ($this->queuedItems == null) - { - return true; - } - - //Get new time - $time = self::getMicroTime(); - - $timeTillNext = $this->queuedItems->nextRunTime - $time; - - if ($timeTillNext < 0) - { - $timeTillNext = 0; - } - - //When zero is returned, we'll always sleep at least 50000 usec in the socket class anyway - return $timeTillNext; - - } - - /* Specific function to deal with queued items */ - private function handleQueueItem($item) - { - $this->currTimer = $item; - - $class = $item->callBack_class; - $func = $item->callBack_function; - - //Call the callback function! Now the callback function will check all possible triggers, - //such as socket input, etc, and add new queued items if it needs more processing/other processing - - if ($class == null) - { - $status = $func($item->args); - } - else - { - $status = $class->$func($item->args); - } - - //If true is returned from the function, then keep the bitch in the queue. This is useful when a - //function has not completed processing (i.e., irc->connection waiting on socket class to return - //the fact that its connected. - - if ($item->removed !== true && $status !== true) - { - self::removeQueue($item); - } - - } - -} - -?> diff --git a/ircbot/readme.txt b/ircbot/readme.txt deleted file mode 100644 index 69de0ae..0000000 --- a/ircbot/readme.txt +++ /dev/null @@ -1,1364 +0,0 @@ -+--------------------------------------------------------------------------- -| PHP-IRC v2.2.1 Service Release -| ======================================================== -| by Manick -| (c) 2001-2006 by http://www.phpbots.org/ -| Contact: manick@manekian.com -| irc: #manekian@irc.rizon.net -| ======================================== -| Special Contributions were made by: -| cortex -+--------------------------------------------------------------------------- -| > Documentation -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- - -NOTE! Please enable word-wrap to view this file. -NOTE! PLEASE READ SECTION '3. Installation - A few things to consider' BEFORE USING. - -Please visit our new mods/forums website here: http://www.phpbots.org/ - -Table of Contents ------------------ - -1. Introduction and Release Notes -1-a. What's new in 2.2.1! -1-b. Features -2. Included -3. Installation - A few things to consider -3-a. Quick Install -3-b. Installing PHP 5 -3-c. Using alternate PHP.INI (PHP Configuration) file -3-d. Installing PHP-IRC -4. Configuration -5. Running -6. Remote Administration (via DCC and Private Message) -7. File Transfer -7-a. File Transfer behind a firewall or NAT -8. Modules and User-defined functions -8-a. Submitting modules for others to download -9. Querying outside servers (alternative to fopen, fsockopen, etc) READ THIS if you need this functionality! -9-a. Basic Queries, using the addQuery() function -9-b. Intro to Connection Class, Advanced Queries -10. Custom DCC Chat Sessions -10-a. Custom DCC Chat Example: Simple File Server (SFS) -11. Database support -11-a. Mysql Database -11-b. Postgre Database -11-c. Serverless, mIRC compatible ini-file based Database -12. Timers -13. Multiple servers under one process -14. Provided Sample Modules -14-a. IMDB Parser -14-b. Quotes mod with mysql/ini file system -14-c. Simple http server -14-d. Bash.org Parser -14-e. News System/Rules Script -14-f. Seen System (beta!) -14-g. Request Ads System -15. Function Reference -16. Special Thanks - -================================= -1. Introduction and Release Notes -================================= -Please visit our new website: http://www.phpbots.org/ for support and user-submitted modules. - -PHP-IRC is a totally php based irc bot meant to automate some applications related to irc. I've personally programmed several modules which I currently use on irc.rizon.net. This version is my attempt at bringing such a device to the public. I hope you find it as useful as I do. I have begun work on a module submission site which will be hosted at http://www.phpbots.org once finished. I have already recieved modules from serveral enthusiastic people wishing to contribute in some way to the project. Thank you for your time and effort. - -It has always been my opinion that IRC scripting has long needed a simple programming interface that people with already existent skills could utilize. There are two main reasons that PHP was selected as the primary language. First off, I wanted to provide novice programmers a way to code their own functions and algorithms into a powerful platform without having to worry about such things as memory management and compilers. Secondly, I wanted to do something that no one has done before--create a fully featured bot in php. I don't know if I will ever complete the second objective, but I will keep on developing, as it will always be the main goal of this project. - -If I have left out information in this file, or there is something I said that confused you, please email me your concerns at manick@manekian.com, and I will try to clarify where you were confused. This will also help me determine what I need to fix in this file for the next version. - - -========================= -1-a. What's new in 2.2.1! -========================= -As this is a service update and not a full release, the readme file included below has not been altered from the 2.2.0 version. Version 2.2.1 brings several bug fixes (which are viewable in changes.txt). - -Development on PHP-IRC is not halted, simply stalled, as I am approaching the culmination of my college career. Thank you for your continued interest in PHP-IRC. - -We have a new website! Please view it here: http://www.phpbots.org/ - -============= -1-b. Features -============= -For a full list of current major features, please visit: http://www.phpbots.org/ - -=========== -2. Included -=========== - -Core Files: - ============== - Config Files - -------------- - bot.conf - function.conf - typedefs.conf (added 2.2.0) - modules/default/priv_mod.conf (added 2.2.0) - modules/default/dcc_mod.conf (added 2.2.0) - ============== - Readme Files - -------------- - readme.txt - modules/template.txt (added 2.1) - gpl.txt (added 2.1) - command_reference.txt (added 2.1.1) - changes.txt (added 2.1.1) - upgrade-2.1.1-2.2.0.txt (added 2.2.0) - install.txt (added 2.2.0) - ============== - Source code - -------------- - bot.php - chat.php (added 2.1) - connection.php (added 2.2.0) - dcc.php - defines.php (added 2.0.1/2) - error.php - file.php (added 2.1) - irc.php - module.php (added 2.2.0) - parser.php - queue.php (added 2.2.0) - remote.php (added 2.2.0) - socket.php - timers.php - modules/default/dcc_mod.php (added 2.1) - modules/default/priv_mod.php (added 2.1) - -========================================== -3. Installation - A few things to consider -========================================== - -I've been getting a lot of emails and private messages on rizon about how to run this bot via a web browser. However, most webhosts do not compile php with socket support enabled, and for that matter, most web hosts don't have php5 as of yet. Even so, in order to start the bot, you have to specify a config file on the command line. Thus, running this bot from a web browser without modification is impossible. I will not make this possible, so in other words, please stop asking. - -Another thing that might deter people from using this script is the enourmous memory requirement by php to keep -a script loaded in memory. PHP5 loads all of the program and everything it could possibly use into memory. This can take up quite a bit of space! I've had a bot use 8 megs of ram on the low end, and up to 15 megs on the high end. If you don't mind dropping 15 megs of ram for this bot, then continue on. Otherwise, don't whine to me that its a resource hog. I believe the advantages far outweigh the disadvantages--how else could I have gotten this far? - -In order to run this bot, you must have shell access to the box you will be running it on. For instructions on how to install php5 for use with this bot, please see the next section, "Installing PHP 5". - -A note about errno constants: ------------------------------ - -In unix/windows/etc, when trying to write or read from a socket sometimes (a socket is the connection between your computer and another computer), errors occur. In order to be able to determine what these errors are, all systems have something called 'errno' constants. Unfortunatly, PHP5 does not know these constants, so we have to set them manually in order for this program to run. In the defines.php file, I have set common values for windows, freebsd, linux, and unix. If you are using one of these systems, an autodetection script should take care of detecting which system you are running the bot on, and set the appropriate values. If this does not work, and you cannot connect to a server, you may need to set your OS type to either "windows", "freebsd", "linux", or "unix". If you do not experience problems with this, then skip down to "Installing PHP 5". Otherwise, keep reading. - -I have run this successfully on Windows XP, Mandrake 9.0 Linux, and Debian. If this program does not work with any of the os settings for OS in defines.php, you need to find the correct values for EAGAIN, EINPROGRESS, EALREADY, and EISCONN(these are those error constants that I was talking about earlier) for your system. - -They are usually in /usr/include. You can find them by using a command sequence such as this: - -------------------------------------------------------------------------------- -grep -r 'EAGAIN' /usr/include/* -grep -r 'EINPROGRESS' /usr/include/* -grep -r 'EALREADY' /usr/include/* -grep -r 'EISCONN' /usr/include/* -------------------------------------------------------------------------------- - -After doing this, you'll get a line that looks like this: - -------------------------------------------------------------------------------- -/usr/include/asm/errno.h:#define EISCONN 106 /* Transport endpoint is already connected */ -------------------------------------------------------------------------------- - -The constant we are looking for is 106. Now, after finding all those numbers, go into defines.php. Set your OS type to "unknown"; then, scroll down a bit till you find this code: - -------------------------------------------------------------------------------- -if ($OS == 'unknown') -{ - define('EAGAIN', 0); /* Try again */ - define('EISCONN', 0); /* Transport endpoint is already connected */ - define('EALREADY', 0); /* Operation already in progress */ - define('EINPROGRESS', 0); /* Operation now in progress */ -} -------------------------------------------------------------------------------- - -Now, change the numbers, etc, with the corresponding values you got when you found the constants above. Do this with all four constants, and then move on to the next section. - -================== -3-a. Quick Install -================== - -Running php-irc consists of 6 general steps (EXPERTS ONLY!): - -1) Download and unpack, compile the php 5 5.0.2+ package with sockets and pcntl. -2) Edit the php.ini file following the steps in section 3-b (bottom half of section under "First, locate this line in the file:") -3) Unzip php irc -4) If the bot does not start up and connect to the server, you may have to set the OS parameter in the defines.php file. Read the previous section. -5) Change server/port information in bot.conf. You can run php-irc with the -c switch to get an md5 password hash to set dccadminpass with. -6) run php-irc with: /path/to/php/php.exe bot.php bot.conf from the php-irc directory, or edit the shebang line and change it to reflect your php location, (also use -c switch to specify php.ini location), and then chmod the bot.php file 755, and run with ./bot.php bot.conf - -Of course, I recommend that you read the rest of this file, as it provides some very important information. - -===================== -3-b. Installing PHP 5 -===================== - -Please read the following notices before continuing to install: - -Notice 1: ---------- -Do not use this bot with alpha/beta versions of php5. I have successfully run it on rc2/rc3, however. - -Notice 2: ---------- -Do not use this bot with php 5.0.0 or 5.0.1. These versions have a bug which makes it work incorrectly. If you would like to find out more about this bug, view this page: http://bugs.php.net/bug.php?id=28892 - -Installation: (see below for installations on linux) - ---------------------- -Installing on Windows ---------------------- -Download PHP5 from this location: 'http://www.php.net/downloads.php'. Select the latest PHP 5 zip package under "Windows Binaries". Unzip this to a folder, c:\php, for instance. - -Then, copy the included 'php.ini-dist' file in the c:\php directory to 'c:\windows\php.ini'. Open this file with notepad or your favorite text editor. (Usually, you can right click the file and hit 'open with'). - -First, locate this line in the file: ---------------------------------------------------------------------------- -; This directive tells PHP whether to declare the argv&argc variables (that ---------------------------------------------------------------------------- - -A few lines below this, you'll see this directive: --------------------------------- -register_argc_argv --------------------------------- -Make sure that this line says: --------------------------------- -register_argc_argv = On --------------------------------- - -Now, locate this line: --------------------------------- -extension_dir = "./" --------------------------------- -Change this to: --------------------------------- -extension_dir = "./ext" --------------------------------- - -If you are going to use a mysql database, find: ------------------------- -;extension=php_mysql.dll ------------------------- -And change to: ------------------------- -extension=php_mysql.dll ------------------------- - -Then find: --------------------------------- -;extension=php_sockets.dll --------------------------------- -And change to: --------------------------------- -extension=php_sockets.dll --------------------------------- - -You are now set to run PHP-IRC. See section "Configuration" for information related to configuring the bot. - -------------------- -Installing on Linux -------------------- -Download php from php website, here: 'http://www.php.net/downloads.php'. Select the latest php5 tar.gz package under "Complete Source Code". - -Extract this file. To do this, copy the file to your home directory. Then, extract it using this command: - -tar -zxf php-<your version>.tar.gz - -Replace <your version> with your version of PHP. Make sure it is 5.0.2 or greater! -Now, run this command: - -cd php-<your version>/ - -Also make sure to replace <your version> with your php5 version. -Now, we have a few things to consider here. Do you want to run a mysql database or not? If you do, then use this command: - -./configure --enable-sockets --enable-pcntl --with-mysql - -However, if you do not have mysql installed on your system, do this: - -./configure --enable-sockets --enable-pcntl - -If for any reason this fails, please read below. If it does not, skip these next few paragraphs. - -Usually the configure script fails when it cannot find a module or package it needs to compile. Sometimes I have had it fail with the 'XML LIB' package, saying it could not be found. In order to rectify this, use this command: - -./configure --help - -And then search through the output, looking for the package that failed. See if there is a --disable-<package> option that you can add to the ./configure command above, which will make it skip that package. Then, run the configure command again, until you remove all packages that do not work with your system. - -Continuing on -------------- - -Now, after you see the "Thanks for using PHP" message, run the following command: - -make - -After this is completed, you are all done installing php! You will need to copy the binary to a usable and NON WEB ACCESSABLE directory, by using this command: - -cp sapi/cli/php /<my directory>/ - -Where <my directory> is the directory you wish to copy it to. When I say NON WEB ACCESSABLE, I mean that you could not access this file directly from the web. - -You are now set to run PHP-IRC. See section "Configuration" for information related to configuring the bot. - -===================================================== -3-c. Using alternate PHP.INI (PHP Configuration) file -===================================================== - -You may be running another version of php on the server that you run this on specifically for apache, or some other purpose. In this case, you already have a php.ini file in /etc. You can use an alternate php.ini file by using this syntax when running php: - -/path/to/php.exe -c /dir/of/php.ini/ bot.php bot.conf - -If on linux, you can also chmod bot.php 755, and then edit the #! line at the top of the file to look like this: - -#!/path/to/php -c /dir/of/php.ini/ - -And then you can run php-irc like this: - -./bot.php bot.conf - -======================= -3-d. Installing PHP-IRC -======================= -If you are reading this file, you have already downloaded and unpacked the source package from sourceforge.net. Good, the hard part is out of the way. Continue on to the next section. - - -================ -4. Configuration -================ - -PHP5 ----- -Please see above, our guide to "installing php 5" for configuration options to php.ini. - -defines.php ------------ -The main things you need to look at in here is DEBUG mode and OS. DEBUG 1 will make it so everything that happens to the bot is printed in the main window. DEBUG 0 will instead print it to a logfile specified in bot.conf. Make sure that you set your OS to either linux, unix, windows or bsd, otherwise your bot won't run (if autodetection fails). - -The lines you need to change are: - -define('DEBUG', 1); - -and: - -define('OS', 'windows'); - -You might also want to change the name of the PID file that is written when you run the bot in background mode. You can edit that filename with this line: - -define('PID', "bot.pid"); - -bot.conf --------- -Edit this file and change all the options to your liking. Of special interest should be natip, which allows you to work from behind a nat. Also, as of 2.1, pay special attention to the 'upload' and 'uploaddir' parameters. You can accept file transfers with those. Please also look at dccadminpass. You will need to set this in order to use dcc chat or private message administration of your bot. You will need to run 'bot.php -c password' to generate an md5 password hash of 'password'. - -function.conf -------------- -This file is a little more complicated. php-irc will respond to various text typed in a channel (triggers). You can configure those triggers in this file. Please see the section titled "Modules and User-defined functions" for help with this file. - -At this point, you should be able to start up your bot--although it won't do much. See the section "Modules and User-defined functions" for information about adding functionality. - - -========== -5. Running -========== -Running this bot is rather simple. - -Windows: --------- - -Run the bot with the following command: - -c:\php\php.exe bot.php bot.conf - -Make sure that this is the correct path that php is in. You may need to change 'c:\php' to the directory where your php5's php.exe resides. Make sure, also, that you are located in your php-irc main directory when you start the bot. i.e., - -cd <my php-irc directory> - -I have a little trick. I make a windows shortcut (.lnk file) to php.exe, and put it in my php-irc directory. Then I edit the shortcut and make sure that my working directory is my php-irc directory. Then, I can run the bot as such: - -php.lnk bot.php bot.conf - -Linux: ------- -The basic syntax is: - -/path/to/php5/php bot.php bot.conf - -If you followed my php5 installation instructions, /path/to/php5/ would be the <my directory> that we talked about earlier. - -Linux Alternative: - -You can edit the #! line in bot.php to reflect your php cgi binary location, and 'chmod 755 bot.php'. This will make 'bot.php' executable. You can then run it as such: - -./bot.php bot.conf - -You can also run several different configurations under the same process. Simply make another bot.conf file and then run it like this: - -./bot.php bot.conf bot2.conf - -If you are on linux/unix, you can also run in the background by using the -b switch: -./bot.php -b bot.conf -However, in order for this to work, you need to set DEBUG mode to 0 in defines.php. (otherwise your bot won't spawn) Also keep in mind that errors will not be displayed when in background mode. Although text is logged to log.txt or whatever file you choose, the errors are not. I will work on this for future versions. However, if you're going to be doing a lot of debugging and are going to want to see all errors, you may want to keep DEBUG=1 and then use a program such as nohup to start the bot: - -nohup ./bot.php bot.conf - -If this doesn't work as expected, delete the 'fclose(STDOUT)' line in bot.php and try running it like this: - -nohup ./bot.php bot.conf -b - - -====================================================== -6. Remote Administration (via DCC and Private Message) -====================================================== - -You can administer your bot via private messages (i.e., /msg php-irc <command>), or via dcc chat interface. However, in order to use these features, make sure that the 'dccadminpass' setting in bot.conf is uncommented, (remove the ';'), and make sure that you change the password to something people can't guess. You need to specify a password hash here, and you can do that by running: - -Windows -------- -drive:\path\to\php.exe bot.php -c <password> - -*nix ----- -/path/to/php bot.php -c <password> - -Where <password> is your password you wish to use. This will generate an md5 hash of '<password>', and you can replace the dccadminpass setting in bot.conf with this value. - -Via private message, you can access admin commands like so (if you are using mIRC): - -/msg <mybot> admin <mypass> <command> - -Where <mybot> is the nick of your bot, <mypass> is the password you selected for dccadminpass, and <command> is the command you will use. You can get a list of commands by using the command 'help'. - -To use the dcc chat administration interface, use: - -/msg <mybot> admin <mypass> chatme - -The bot should then send you a dcc chat request. You will have to type in your password to validate your session, which is just the password you set with dccadminpass again. Then, you can type 'help' for a list of commands. - - -================ -7. File Transfer -================ - -This bot supports file transfers now. I will implement a speed capping system in a later version. For right now, you can send/recieve files at your max bw potential. Really fast transfers (in the line of 100 mbit) take up nearly 99% of your CPU, however. The system supports resume, as well as the mIRC File Server protocol (see below for configuration) - -To send someone a file, use: - -SEND <nick> /path/to/file - -You can use 'DCC' for speed/eta, although it doesn't work very well. Its based off of 3 second averages. Oh, and you can use 'CLOSE id' to close a specific transfer. These id's are the numbers between the brackets ([ and ]) when you run the 'DCC' command. - -NOTE! This may be a security risk, as people with admin access could send themselves any file on your computer with it. You may want to disable this function in the function.conf file if you feel this may be a problem. (just comment it out by putting a ';' in front of the line, or removing the line completely) - -=========================================== -7-a. File Transfer behind a firewall or NAT -=========================================== - -To setup the bot to work behind a NAT (i.e., you are a computer behind a router, and you do not have a net-accessable IP, like 192.168.1.100), you can use the 'natip' setting in bot.conf. Then, you can set the 'dccrangestart' item to choose what port file transfers will use for outsiders to connect. Normally, the bot will use port 1024+, but if you are using forwarded ports, you can set this setting to use those ports. - -If you are behind a firewall, and cannot use the natip feature: -This bot also supports the mIRC reverse dcc protocol. The mIRC File Server protocol can be turned on by uncommeting the 'mircdccreverse' setting in bot.conf. The 59 there is just the port that you will connect to. Common numbers are 59 and 212. - -===================================== -8. Modules and User-defined functions -===================================== - -Modules are what add the functionality to php-irc. You can run php-irc by itself, and it may come with some pre-programmed features, but other than that it doesn't do much. You need to extend it by adding modules that other people have written, or by writing modules yourself. In this section, I will attempt to guide you through the process of doing just that. - -Modules reside in the 'modules/' directory. I have several modules in this directory already, and you can read about them in the section "Provided Sample Modules". - -A php-irc module is a user defined class inside of a file in the modules/ directory. See "template.txt" in the modules/ directory for instructions on how to setup a class. The basic declaration of a module class is as follows: - -class class_name extends module { - - //Other stuff, can be found in template.txt - -} - -This declaration syntax is INCREDIBLY important. You MUST have the format: - -class[space]class_name[space]extends[space]{ - -In order for the dynamic module support in PHP-IRC 2.2.0 to work, class definitions for modules must be defined in this way. If you have outside classes to include, you must include them with "require_once()", instead of "require()". - -Now, say that we created a module; we copied template.txt to my_mod.php, and changed "class_name" to "my_mod" inside my_mod.php. Now, we will have to declare this module inside function.conf. - -function.conf -------------- -There are three main types of directives that you can set in this file. Types, Commands, and Includes. A "Type" statement is a statement which declares a format for a "Command" to use. - -For instance, if I had a type, "notice", and I wanted it to have the arguments "module", and "function", I would do this as follows: - -type notice module function - -Now, I can create commands that use type "notice". Here is an example of a command that uses type "notice": - -notice my_mod my_function - -Thus, whenever a "notice" event took place on IRC, the function "my_function" in "my_mod" would be run with various useful parsed parameters passed. (Discussed Later) - -Note the "module" and "function" arguments. These are required arguments. This means for every single type declared, there must be a "module" and "function" argument specified, because if these didn't exist, what would be the point of catching the event? - -"Include" statements specify external function files to include into the main function.conf file. They are useful when packaging a module with several function.conf statements. Instead of copying/pasting all the statements on installation of the module, one need only to instruct a user to include a statement such as this: - -include modules/my_mod.conf - -Now to get a little more complicated: -------------------------------------- -In addition to parsing standard irc messages and events and defining functions to parse them, the bot comes with 4 standard types. These types are "priv", "dcc", "ctcp", and "file". The "file" type is used to include module files and their associated functions into the bots runtime code. The "ctcp" type makes parsing mIRC's "/ctcp" commands simpler. This could also be done by using a "privmsg" type and then parsing the line manually (to remove the ctcp characters), but its simpler to just do it this way. The "priv" type handles text typed in a channel. Thus, we can capture "!ad" or other triggers with this. The "dcc" type handles text typed in the standard user and admin dcc chat interface. - -file ----- -You use this to declare and include modules into php-irc. The syntax is as follows: - -file - the type -name - the module (or name of the class in the file) -filename - the filename to include (the file that the class resides in) - -Example: - -file priv_mod modules/priv_mod.php - -Filenames with spaces can be enclosed with quotes: - -file priv_mod "modules/My totally kick ass mod.php" - -priv ----- -The "priv" type comes with several parameters, each explained below: - -priv - the type -name - the trigger typed into the channel, i.e., "!ad" -active - whether this particular function is active (can be triggered) - when the bot starts up -inform - Inform the administrator (through dcc chat interface, when the admin - is logged in) that someone used this function. -canDeactivate - admin can deactivate this function using FUNCTION command in dcc interface -usage - how many times this function was used -module - the module that the function is located in -function - the function in the module specified above that is run - -An example of a command that uses the "priv" type is defined below: - -priv !ad true true true 0 priv_mod priv_ad - -The "!ad" command uses the function "priv_ad" in the "priv_mod" module. So whenever someone types in a channel: - -!ad <some arguments> - -The priv_ad function in priv_mod will be called to handle the arguments and respond to the user. - -dcc ---- -The "dcc" type comes with several parameters, each explained below: - -dcc - the type -name - the command typed, i.e., "HELP" -numArgs - the expected number of arguments for this command -usage - a string containing an overview of arguments, i.e., "<id> <nick>" -help - a string containing information about what the command does -admin - whether this command is only available in the admin interface, or can be used in the standard user dcc chat interface -module - the module that the function is located in -function - the function in the module specified above that is run -section - the section the command is displayed in in dcc chat interface (explained below) - -An example of a command that uses the "dcc" type is defined below: - -dcc raw 1 "<raw query>" "Sends raw query to server" true dcc_mod dcc_raw standard - -You might also notice that in this case we used quotes. Quotes can be used for any string longer than 1 word. Single and Double quotes are allowed. Escape double/single quotes inside the quotes with a backslash: i.e., "Who\'s there?". This does not follow the standard convention for escaping quotes. So, even if you use double quotes to specify a multi-word string, you must still escape single quotes. - -section -------- -In the dcc command above, the "section" argument was used, and specified as "standard". PHP-IRC 2.2.0 comes with a new ability to package dcc commands with sections. Thus, when someone types "Help" in dcc chat, all of the functions are organized by category. - -A section can be declared with the following arguments: - -name - a small idname to be used in 'dcc' statements -longname - a usually quoted string which speicfies this sections title - -PHP-IRC comes with a few pre-defined sections which include 'standard', 'channel', 'dcc', 'info', 'admin', and 'comm'. The declaration for the standard section type is shown below: - -section standard "Standard Functions" - -You can of course specify your own sections in the same manner; say, for a custom module perhaps. - -ctcp ----- -This is a shortcut to parsing commands sent to this bot with mIRC's /ctcp command. The format is as follows: - -ctcp - the type -name - the trigger, i.e., "files" (see fileserver example in function.conf) -module - the module that the function is located in -function - the function in the module specified above that is run - -See the fileserver ctcp command in modules/fileserver/fileserver.conf for an example. - -Now that you know what function.conf is and how it works: ---------------------------------------------------------- - -Suppose we have a random function in a module we've written, such as the one defined in the next section titled "Querying Outside Servers" named "query". Having the functon is all fine and dandy, but how do we access it? That is where function.conf comes in. We will specify a trigger which can be used to access the query function during runtime. First, we have to include our module: - -file my_mod modules/my_mod.php - -We'll pretend that this is where the 'query' function resides for the moment. Now, lets say we want to run that function every time someone types '!info' in the channel. To do this, we would add (below all the type declarations, and below the 'file' declaration we just made above): - -priv !info true true true 0 my_mod query - -Thus, every time someone typed !info in the channel, the function 'query' would run. This is the main basis for php-irc. It is the heart of its purpose--responding to triggers. - -Creating Functions to Respond to Triggers ------------------------------------------ -Now that you know how to create modules, and specify them in function.conf, we will now cover writing your own functions to handle these triggers. There are four main types of functions that you will write. "timer" functions, "standard" functions, "query" functions, and "dcc" functions. - -standard --------- -Standard functions are the functions which handle all the non-dcc type command statements declared in function.conf. Remember our example earlier, when a user could type '!info' in the channel. This triggered the 'query' function in the module 'my_mod'. A sample declaration of this function could be: - - public function query($line, $args) - { - //your code - } - -Notice the "$line, $args". The declarations for 'query', 'dcc', and 'timer' functions all use different values here. They are shown below: - - public function standard($line, $args) - public function query($line, $args, $result, $response) - public function timer($arguments) - public function dcc($chat, $args) - -Definitions of variables ------------------------- - -$line ------ -Line is an array containing a parsed version of the raw line sent from the server. A raw line sent from the server could look like this: - -:Manick!~bugs@Rizon-2EFC6E17.resnet.purdue.edu PRIVMSG #manekian :!ad - -We need to parse this into meaningful parts in order to do anything with the bot. The $line array does that: -from => full nick/ident/host, in this case: "Manick!~bugs@Rizon-2EFC6E17.resnet.purdue.edu" -fromNick => only nick, in this case, "Manick" -fromHost => only host, in this case, "Rizon-2EFC6E17.resnet.purdue.edu" -fromIdent => The Ident of the user, in this case, "~bugs" -cmd => irc command used, (i.e., PRIVMSG, NOTICE, 366, 353, etc), in this case "PRIVMSG" -to => who this command was directed at (channel or your nick), in this case, "#manekain" -text => everything after : in the line; basically the text of what someone says, in this case, "!ad" -params => useful when parsing 'mode' commands etc. in this case, ":!ad" -raw => the full untouched line. - -To access an element in $line, reference it as such: $line['element'], such as: - -$line['fromNick'] - -This would return "Manick", in this case. Sometimes these variables are not populated perfectly. In a particular circumstance, you can use: - -print_r($line); - -by itself to to print the contents of the $line variable to the screen while in debug mode. - -$args ------ -This is a simple array created from the $line['text'] variable. It contains the following data: - -nargs => the number of arguments -cmd => the command used -arg1 => present if there are 1 arguments or more -arg2 => present if there are 2 arguments or more -arg3 => present if there are 3 arguments or more -arg4 => present if there are 4 arguments or more -query => The full text (all of args put together) -(there are no more after arg4..) - -So, if I typed "!ad 60 Here is an ad that I want to talk about...": - -nargs would be "4" (yes, 4) -cmd would be "!ad" -arg1 would be "60" -arg2 would be "Here" -arg3 would be "is" -arg4 would be "an" -query would be "60 Here is an ad that I want to talk about..." - -The maximum arguments can be set by the MAX_ARGS define in the defines.php. It was chosen to be four for performance reasons. - -$result -------- -This is discussed in the next section "Querying Remote Servers" - -$response ---------- -This is discussed in the next section "Querying Remote Servers" - -$arguments ----------- -When creating a timer, you can specify one argument, whether it be a string, array, or object, to send to a timer function every time that timer runs. Timers are discussed in a later section. - -$chat ------ -This is the object containing the current session of the user who typed the command in the dcc chat window. $args for dcc functions is the same as $args above. - -Sending messages and responding to users ----------------------------------------- - -After you've received a query and processed it, you might want to send back information. There are several functions that can be used to do just that: - -$this->ircClass->sendRaw($text); //send raw data to server -$this->ircClass->notice($line['fromNick'], $text, $queue = 1); // (where $queue defaults to 1.. meaning its not - // sent right away. -$this->ircClass->privMsg($line['fromNick'], $text, $queue = 1); // $line['fromNick'] can also be the channel - // which is usually $line['to']. -$this->ircClass->action($line['fromNick'], $text, $queue = 1); // does the '/me' thing that mIRC does - -To send data to dcc users, use: - -$chat->dccSend("text here"); - -To send a CTCP messege, do this: - -$cmd = "VERSION"; -$msg = ""; -$this->ircClass->privMsg($line['fromNick'], chr(1) . trim(strtoupper($cmd) . " " . $msg) . chr(1)); - -Where $cmd is the command, like "VERSION", or "ACTION", and $msg is the parameters to the command. - -$queue ------- -php-irc maintains a text queue, so that it does not flood the server with text. This is not a perfect system, and still fails ocassionaly, but works for the most part. If $queue is set to 1, or not specified at all, then $text will be appened to the end of the queue waiting to be sent to the server. Otherwise, if you set it to 0, it will be prepended to the beginning of the text queue. - - -Now you should know all you need to know to write your own modules for php-irc. - - - - -============================================== -8-a. Submitting modules for others to download -============================================== - -I am currently working on a site to submit modules. This site will be http://www.phpbots.org when finished. - -=========================== -9. Querying outside servers -=========================== - -You may need to read the section titled: "Modules and User-defined functions" before reading this. - -Sometimes when programming a module, you might find it necessary to parse some webpage to return some data to a user requesting it. Your first impression might be to use "fopen" or "fsockopen" to make a connection to the webserver and get the data. - -Consider something for a moment. This bot is running on one process, one thread. Say that you were sending a file to someone, and you also went to query a webpage. What if the webpage was extremely bogged down with traffic? The query would block, and the file transfer would stall. To rectify this, I implemented a few procedures for querying outside servers, including webservers. This eliminates the blocking problem, as the connections are handled by php-irc. - -There are two basic ways to communicate with the outside world easily in PHP-IRC. - -1) Use $this->ircClass->addQuery() -2) Utilize the connection class manually - -The addQuery() method is a specialized way of using the 'connection' class to get the job done. In other words, you could write your own connection.php class method that does exactly what addQuery does, or even more if you wanted. The irc bot itself uses the connection class to connect to irc servers, run dcc chats, and even run file transfers. You can even use the connection class to start a listening socket, which can be used to write servers such as http servers, ftp servers, or pretty much anything that uses a tcp socket. - -================================================= -9-a. Basic Queries, using the addQuery() function -================================================= - -This method is used mostly for retrieving data from http servers. It's main advantage is that it is incredibly easy to use, but the main disadvantage is that you can only send one query per connection, and then data related to that query is returned before the connection is terminated. - -The basic procedure is this: You will run a function with a query, and specify what function to run when data has been recieved from that server. Then, the function, using a specifically defined prototype, will have access to all the data + results from the server as soon as the query is complete. - -Functions used in this process are: - -irc::addQuery($host, $port, $query, $line, $class, $function) -socket::generateGetQuery($query, $host, $path, $httpVersion = "1.0") <-- $httpVersion can be omitted -socket::generatePostQuery($query, $host, $path, $httpVersion = "1.0") <-- $httpVersion can be omitted - -These functions, (addQuery, generateGetQuery, and generatePostQuery) are outlined in the command_reference.txt file. But here is how it works: - -For instance, if you wanted to parse data at animenfo.com, you would do this: - -Define a function in your module file. We'll call it "query" for now. Also, see the previous section for information about how to make this method accessable (by editing function.conf) - - public function query($line, $args) - { - $query = "search=naruto&queryin=anime_titles&action=Go&option=smart"; - $getQuery = socket::generateGetQuery($query, "www.animenfo.com", "/search.php"); - $this->ircClass->addQuery("www.animenfo.com", 80, $getQuery, $line, $this, "queryTwo"); - } - -Notice the "queryTwo". Now define another function in your module file. We'll call it "queryTwo". - - public function queryTwo($line, $args, $result, $response) - { - - } - -The function, "queryTwo" will be run as soon as a response is recieved from the server, and the response will be stored in the '$response' variable. The result of the query will be stored in the '$result' variable. For instance, if there was an error on query, $result will equal QUERY_ERROR, and the error message will be stored in $response. If there is no error, $result will equal QUERY_SUCCESS. - -Notice ------- -As of version 2.1.1, the socket::httpGetQuery, and socket::httpPostQuery functions were removed. They were replaced with the addQuery function. - -================================================ -9-b. Intro to Connection Class, Advanced Queries -================================================ - -As the development of PHP-IRC 2.2.0 continued, a need for a connection layer to the socket class appeared. Code was being repeated often in the irc bot class, the dcc class, and other places; in addition, it was becoming quite cluttered and hard to understand. Also, the old way just simply didn't work anymore with the process queue method implmented in 2.2.0. Therefore, the connection class was implemented to solve this problem. - -The connection class serves as a layer between the socket class and the user. A user can create a connection, specify a host and port, and the connection class will do everything else automatically; connect, send read/write events, accept connections, close connections, and much more. This works by specifying a callback class, with pre-named, user-defined functions to accept events from the socket class. Say, for example, whenever data is read for a specifc socket, that sockets user-assigned connection class will notify the callback class of an event, say, onRead(), and then the onRead() function in the callback class can read the data. - -Here's a simple schematic: - -+--------------+ +------------------+ +----------------+ -| Socket Class |->Triggers->| Connection Class |->Triggers->| Callback Class | -+--------------+ +------------------+ +----------------+ - -The callback class can then use socket class functions, such as getQueueLine(), or what have you, to retrieve data from the socket read queue, or send data using the appropriate function. - -General Overview ----------------- -There are two specific ways to run the connection class: - -1) Open connection to other server specifying host and port -2) Listen for connections on a specific or random port, accepting new connections - -The ins and outs of the callback class will then be explained. - -Method One - Connecting to another server ------------------------------------------ -For this method, one needs 3 things, with the fourth being optional: - -1) Host -2) Port -3) Connection timeout -4) Transfer timeout - -The connection timeout is how long before the connection class will think that it cannot connect to the server before timing out, and the transfer timeout is how long (after a connection has connected) before the connection class believes the connection to have failed after no activity. - -Say you wanted to connect to "www.animenfo.com" on port "80". First, you need to declare a new connection: - - $conn = new connection("www.animenfo.com", "80", CONNECT_TIMEOUT); - -CONNECT_TIMEOUT is just the default connect timeout used by the irc class. You can use whatever integer/float number you want. - - $this->conn = $conn; - -You need some way of remembering this connection; in this case, the call back class will be the one that the connection is created in. In most cases, you will need to make a whole new class because of the need for unique functions to handle the events of any general connection. - - $conn->setSocketClass($this->socketClass); - $conn->setIrcClass($this->ircClass); - $conn->setTimerClass($this->timerClass); - -The connection class needs access to these three classes, socket class, irc class, and timer class. - - $conn->setCallbackClass($this); - -This is probably the most important call of all. Whenever an event happens for this connection, specific functions in this class will be called to handle the event. This is explained more thouroughly below in the "Ins and Outs" of the callback class sub-section. - - $conn->init(); - -This will try to create the socket with the socket class. - -Also, optionally here you can specify transfer timeout. That would look like this: - - $conn->setTransTimeout($timeout); - -Where $timeout is in seconds or fractions of seconds. - - if ($conn->getError()) - { - $this->ircClass->notice($line['fromNick'], "Error connecting: " . $conn->getErrorMsg() ); - } - -If there was a problem init()'ing the connection, then $conn->getError() will be true, and $conn->getErrorMsg() will be why. - - $this->sockInt = $conn->getSockInt(); - -The sockInt is necessary to use socket class functions for this socket. - - $conn->connect(); - -The final step, this will start the connection process to the server. - -Method Two - Listening for Connections --------------------------------------- -This method follows reletively the same method as for connecting to a server. There are two slight differences: - -1) Specify the host as null when creating a connection, and specify the connect timeout as zero. - - $conn = new connection(null, "80", 0); - -You can change the "80" to null to listen on a random port. - -2) Do not run $conn->connect(); - -This function is used ONLY when connecting to a server. It has no purpose otherwise. - -The Ins and Outs of the Callback Class --------------------------------------- -Okay, so now we know how to create a listening connection or a connect connection. Now what do we do with it? We have to have some way of responding to the events. A callback class must have seven pre-named functions: - -class my_class { - - public function onTransferTimeout($connection) - { - } - - public function onConnectTimeout($connection) - { - } - - public function onConnect($connection) - { - } - - public function onRead($connection) - { - return true; (or return false;) - } - - public function onWrite($connection) - { - } - - public function onAccept($listener, $newConnection) - { - } - - public function onDead($connection) - { - } - -} - -Each function is pretty self explanitory. The only one that might cause some confusion is onRead() or onAccept(). - -onRead() --------- -This function returns true if not all data has been read from the socket (i.e., you used socketClass->getQueueLine() but want to give other processes a chance to run before you continue processing). This will make the function run immediately again. Otherwise, returning false will signal to the connection class that you don't need to run this function again. - -onAccept() ----------- -Listener is the connection that was listening for new connections, and $newConnection is the new connection. $newConnection is another object of type connection class, and all one needs to do is call getSockInt() on it to get the socket identifier. The callback class is automatically its parents callback class ($listener's callback class). This can be changed by runing the setCallbackClass() function again with a different class. - -Closing a connection --------------------- -This is very important. The connection class will, under no circumstances, close a connection. Even if the onDead() function is called, for instance, the callback class MUST close the connection. If you have a connection, $conn, and you want to close it, you would run: - -$conn->disconnect(); - -This kills the socket, and removes it from the socket class. From this point on, it is completely inactive. - -What if I want to accept a connection, but close the parent connection in the process? --------------------------------------------------------------------------------------- -The dcc class is a sample class that does just this. - - public function onAccept($oldConn, $newConn) - { - $this->conn = $newConn; - //We just want to use $newConn from now on - - $this->sockInt = $newConn->getSockInt(); - //Get $newConn's sockint - - $oldConn->disconnect(); - //Close our old connection - - $this->onConnect($newConn); - //Trigger the onConnect event - } - -============================ -10. Custom DCC Chat sessions -============================ - -A custom dcc chat handler is where you send out a chat request to a user, and instead of php-irc's default dcc interface handling and parsing the input, you will handle and parse the input yourself. Just follow the template.txt in the modules directory to create your handler. However, in addition, you need to do a few extra things. - -You will need to include these functions: - - public function main($line, $args) - { - $port = $this->dccClass->addChat($line['fromNick'], null, null, false, $this); - - if ($port === false) - { - $this->ircClass->notice($line['fromNick'], "Error starting chat, please try again.", 1); - } - } - - public function handle($chat, $args) - { - } - - public function connected($chat) - { - } - - //Following function added for 2.2.1 - public function disconnect($chat) - { - } - -'main' function ---------------- -This is the function that your trigger in function.conf will call to initiate the chat - -'handle' function ------------------ -Whenever something is typed in the dcc chat window, it will be passed to this function in the '$args' array. See the previous section for the general definition of this array. - -'connected' function --------------------- -Use this function to do any "upon connection" tasks, as in setup the session or whatever you want. - -fileserver.php is a module that uses a custom dcc chat handler, and is detailed below. - - -'disconnected' function ------------------------ -This is called when a dcc chat session is closed. - -============================== -10-a. Simple File Server (SFS) -============================== - -I've include a small, not-to-complex fileserver which you can use as an example to create your own modules. This particular one is a custom dcc chat handler (refer to previous section). To activate, uncomment the 'ctcp files' section and 'file fileserver' section in the function.conf (you can change 'files' to whatever you want, its your trigger). Then edit these variables in fileserver.php: - -private $vDir = "F:/BT/"; (use forward slashes, with a trailing slash as shown) -private $maxSends = 3; -private $maxQueues = 15; -private $queuesPerPerson = 1; -private $sendsPerPerson = 1; - -vDir is the root directory of the fileserver. I haven't beta tested this too much. If it breaks, tell me I guess. It was meant as a demonstration rather than something to actually be used. - -==================== -11. Database support -==================== - -PHP-IRC offers ever increasing database support. It currently offers a tried and tested mysql database abstraction layer(dba), and a beta postgre dba. There is also a new "ini" database type which operates out of ini files. This is similar to mIRC's /writeini and $readini functions. - -===================== -11-a. MySQL Database -===================== - -To use a mysql database, you will need to uncomment and fill out the database settings in bot.conf. You will also want to make sure that you have php set to use mysql. View the "Installing PHP 5" section for more information about this. - -You will need to set 'usedatabase' in bot.conf to this: - -usedatabase mysql - -INPORTANT DATABASE INFO: ------------------------- -Because PHP does not escape input from sockets as it does with get/post/cookies (from http), you need to escape your database information before you put it into the database. Therefore, if you have a table with 3 fields like ... name, password, email, then the safest way to put this information into the database using the db class provided in the bot would be: - -$fieldArray = array("Somebody's Name", "somePass", "something@something.com"); - -$this->db->query("INSERT INTO sometable (name,password,email) values ('[1]','[2]','[3]')", $fieldArray); - -This ensures that the data is safe to put into the database. The [1] etc will be replaced with their place in the array above in real time. Of course, you are free to do it however you wish. - -====================== -11-b. Postgre Database -====================== - -You will need to set 'usedatabase' in bot.conf to this: - -usedatabase postgre - -Also, read "IMPORTANT DATABASE INFO" above for more information. Support for this dba is SKETCHY at best. - -========================================================= -11-c. Serverless, mIRC compatible ini-file based Database -========================================================= - -INI-file support compliments the database system provided by PHP-IRC. Say you have a simple module which only needs to store a few data to file. Instead of having to have a mysql database, you can achieve this feat with ini files. They are basically identical to mIRC ini files--so, if you have any experience with $readini or /writeini, you will be pretty well off. - -To use ini files, there are several functions you can perform: - -1) Declaring, Creating, or Opening an INI file -2) Setting ini values -3) Retrieving ini values -4) Writing changes to ini file -5) Miscellaneous ini-file functions. - -1 - Declaring, Creating, or Opening an INI file ------------------------------------------------ -Creating or opening an ini file is incredibly simple. In fact, they consist of the same step: - -$myIni = new ini("somefile.ini"); - -Thats it! Then: - -if ($myIni->getError()) -{ - //some code to handle ini file error -} - -If this is false, then the ini file cannot be created. In this case, you need to check the permissions on the directory you're attempting to create this file. (It may be that you don't have read access either.) - -Now you are ready to import/export data. One idea you may use is saving the $myIni variable in a global variable in your module, and then using it just as if it was a database, running queries and updating data occasionally. - -2 - Setting ini values ----------------------- -INI files consist of three types of data. Sections, Variables, and Values. They look somewhat like this: - -[section] -variable=value -another_variable=value -[section2] - -etc.... - -To set an ini value on ini-object "$myIni", use the following function: - -$myIni->setIniVal($section, $variable, $value); - -None of these arguments may contain a newline character. - -3 - Retrieving ini values -------------------------- -There are many many ways of retrieving data from an ini object. To assist, there are around ten helper functions: - -1) getSections() //get all section names -2) sectionExists() //check whether a section exists -3) getSection() //get all vars in a section, associative array form -4) randomSection() //get a random section -5) randomVar() //get a random variable in a section -6) searchSections() //see command_reference.txt -7) searchVars() //see command_reference.txt ... etc -8) searchSectionsByVar() -9) searchVals() -10) numSections() -11) numVars() -12) getVars() - -Perhaps the most important function is getIniVal($section, $var). See command_reference.txt for more detailed function information. - -4 - Writing changes to ini file -------------------------------- -When you want to finalize changes to an ini database, and write the data to a file, call this command: - -$myIni->writeIni(); - -This will write the ini file. You can continue editing, and then use this function again as many times as you wish. - - -5 - Miscellaneous ini-file functions ------------------------------------- -There are some other useful functions. See command_reference.txt for more info. - -1) deleteVar($section, $var) -2) deleteSection($section) -3) getSection($section) - -========== -12. Timers -========== - -Timers allow you to run some procedure or function later, but not have to actually "run" it later. You specify a delay, and the script will run it in the interval selected. Timers are used all over php-irc. The point here is that you can also use them. - -Timer functions look like this: - - public function myfunc($arguments) - { - return true/false; - } - -This form is declared more readily in the section titled "Modules and User-defined functions". By default, a timer will expire upon running, and will not be run again. To change this so that the timer runs again in another interval, the timer function MUST return 'true': - -return true; - -This will signal the timer class to run the timer again after 'interval'. Otherwise, the timer is removed. - -If I wanted to create a timer to run a function in sixty seconds, I would do this: - -$this->timerClass->addTimer("my_timer", $this, "myfunc", "", 60, false); - -The arguments are as follows: -$name - The timer's name. Used with removeTimer to remove the timer -$class - pointer to class with function, usually '$this' -$function - the function that you will want to run after the interval expires -$args - the arguments you want to send to the timer -$interval - duh, in seconds and fractions of seconds (i.e., 5.2) -$runRightAway - whether this timer should run as soon as it is added, or wait until after the interval. 'true' or 'false'. - -A few notes: ------------- - -$name ------ -If you want to create a random name to send as timer title, with least chance for name collision, use: - -irc::randomHash(); - -This function will generate a string which should be unique. - -$args ------ -This can be anything you want, from a class, to an array, to an object. I have the 'argClass' defined in defines.php which I use to send multiple variables to my timers: - -$args = new argClass; - -$args->arg1 = "blah"; -etc... - -Otherwise, you could just send an associative array. - -Removing Timers ---------------- -In order to remove a timer, you will need to use this function: - -$this->timerClass->removeTimer($name); - -The "$name" variable is the same as the name variable declared with addTimer above. Make sure that you specify unique timer names. Also, make sure that you keep track of the timer name if you are going to want to delete it. You can usually do this by sending it via the $args variable. - -Instead of relying on removeTimer, I many times simply return false instead of true when the timer is next run. That is also possible. - -=================================== -13. Multiple bots under one process -=================================== - -This script supports running multiple bots under one process. In order to do this, create another bot.conf file, say, bot2.conf, and just specify it when starting the bot: - -./bot.php bot.conf bot2.conf bot3.conf - -etc. See the "Running" section for more information. Performance of multiple bots has been significantly increased in 2.2.0. - - -=========================== -14. Provided Sample Modules -=========================== -To foster continued support of PHP-IRC; I have included some basic module examples in this release. Please note that a parser can and will fail when the html of a site is changed, so some of these releases may NOT work at future dates. They all worked previous to 01/14/05, however. - -================= -14-a. IMDB Parser -================= -This module parses the internet movie database, http://www.imdb.com - -To use, uncomment the following line from function.conf - -;include modules/imdb/imdb_mod.conf - -The command is "!imdb". You can do a search by using "!imdb <query>". If multiple dates were found for your query, you can do: "!imdb <title> (date)" to see it's results. Note that the parenthesis on the date must be there. - -Note, as this is a parser, it may not work out of the box, as imdb might have changed their site. - -=========================================== -14-b. Quotes mod with mysql/ini file system -=========================================== -Possibily the most usable feature of any bot, this bot comes with two different forms of quote systems. You can either utilize a mysql database, or use the onboard ini file database. - -Mysql ------ -To use, uncomment in function.conf: - -;include modules/quotes_sql/quote_mod.conf - -You must also set the database information in bot.conf, and run this query in the database: - -create table quotes (id int default null, deleted tinyint(1) default 0, author varchar(50) default "", quote text, channel varchar(100) default "", time int, key(id)); - -See modules/quotes_sql/quotes_mod.conf for usable commands. - -Ini ---- -To use, uncomment in function.conf: - -;include modules/quotes_ini/quote_mod.conf - -Quotes are stored in the included "quotes_database" directory. - -See modules/quotes_ini/quotes_mod.conf for usable commands. - -======================== -14-c. Simple http server -======================== -Alright, this is more of a proof of concept than something actually usable. This shows off the use of PHP-IRC's new "connection" class to handle incoming http connections in an event based way. - -I really know just about nothing about the http protocol, thus I give no support or instructions for this module. I have had it display pages and images with much success. - -To use, uncomment in function.conf: - -;include modules/httpd/httpd_mod.conf - -Then, the bot will listen on the port specified in modules/httpd/http.ini which defaults to 5050. - -===================== -14-d. Bash.org Parser -===================== -This will allow users to display random, searched, or specific quotes from http://bash.org - -The commands are: - -!bash - random quote -!bash + - random positive quote -!bash search - search for a quote, will display the first result containing 'search' -!bash id - will return the specific quote with id 'id'. - -To use, uncomment in function.conf: - -;include modules/bash/bash_mod.conf - -============================== -14-e. News System/Rules Script -============================== -This is a small standard script where users can type a trigger and information will come back to them. It can be used to generate !rules scripts, !news scripts, or pretty much anything you can think of. To use it, uncomment the appropriate line (referring to news_mod.conf) in function.conf. Then, you can use the default trigger, !news, to add stuff. You must be opped/admined to add/delete items. - -Here are the commands: - -!news <command> <arguments> - -command: -add - add a new item to end of list. You can also add to a specific line number, by doing add <num> <stuff> -del - delete a line number: del <num> -show - show line numbers with their respective lines, so you can use del. -clear - clear out all lines for a specific channel. - -Running the command with no arguments is available to everyone, and will show the lines in order of line number. - -The usefulness of this mod is very apparent. However, to make it even more useful, I've added another feature. Say that you have these two items in news_mod.conf: - -priv !news true true true 0 news_mod priv_news -priv !requests true true true 0 news_mod priv_news - -Both of these are pointing to the same function/module, but they will both access separate database files. Thats right, separate. That is because any call to the function will make the function open the database that is of the same name as the trigger. For instance, doing: - -!news add Hello! This is some news! - -This will add the line to the news database. And doing: - -!requests add Some Request - -This will add the line to the requests database, but they use the same module/function! Cool huh :) - -=========================== -14-f. Seen System (beta!) -=========================== -This is a very beta mod which I wrote like 15 minutes prior to releasing this version of php-irc. Basically, it works as a normal seen mod would, you type !seen <user> and it tells you the last time it saw that person. It uses the ini file system to store information. This mod is VERY BETA!!! I haven't even tested 85% of it. I ran it once and thought, "heh, interesting", and never looked at it again. I will not support this mod until either someone updates it and sends me a better revision, or I get the time to make it better. - -======================== -14-g. Request Ads System -======================== -This has been around since the early days of php-irc. It is the classic example. Except in 2.2.0, it now utilizes the ini file system, so ads that are added are saved and restarted when the bot process is killed and restarted. The "!ad" trigger is on by default. - -====================== -15. Function Reference -====================== -Please view the "command_reference.txt" file for a complete indepth look at all the functions that you can use while writing your modules. diff --git a/ircbot/remote.php b/ircbot/remote.php deleted file mode 100644 index a6868c0..0000000 --- a/ircbot/remote.php +++ /dev/null @@ -1,213 +0,0 @@ -<?php -/* -+--------------------------------------------------------------------------- -| PHP-IRC v2.2.1 Service Release -| ======================================================== -| by Manick -| (c) 2001-2005 by http://www.phpbots.org/ -| Contact: manick@manekian.com -| irc: #manekian@irc.rizon.net -| ======================================== -+--------------------------------------------------------------------------- -| > remote class module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -/* Remote, a class to handle addQuery connection from ircClass */ - -class remote { - - //External Classes - private $socketClass; - private $ircClass; - private $timerClass; - - //Internal variables - private $host; - private $port; - private $query; - private $line; - private $class; - private $function; - private $connTimeout; - private $transTimeout; - private $sockInt; - private $connection; - private $connected; - - //Output internal variables - private $response; - private $type; - - function __construct($host, $port, $query, $line, $class, $function, $transTimeout) - { - $this->host = $host; - $this->port = $port; - $this->query = $query; - $this->line = $line; - $this->class = $class; - $this->function = $function; - $this->transTimeout = $transTimeout; - $this->response = ""; - $this->connected = false; - $this->type = QUERY_SUCCESS; - } - - public function setSocketClass($class) - { - $this->socketClass = $class; - } - - public function setIrcClass($class) - { - $this->ircClass = $class; - } - - public function setTimerClass($class) - { - $this->timerClass = $class; - } - - public function connect() - { - if ($this->host == null || $this->port == null) - { - return false; - } - - if (!is_object($this->socketClass)) - { - return false; - } - - if (!is_object($this->ircClass)) - { - return false; - } - - $conn = new connection($this->host, $this->port, CONNECT_TIMEOUT); - - $conn->setSocketClass($this->socketClass); - $conn->setIrcClass($this->ircClass); - $conn->setCallbackClass($this); - $conn->setTimerClass($this->timerClass); - - /* Set Timeouts */ - $conn->setTransTimeout($this->transTimeout); - - $conn->init(); - - if ($conn->getError()) - { - $this->setError("Could not allocate socket"); - return false; - } - - $this->sockInt = $conn->getSockInt(); - $conn->connect(); - - $this->connection = $conn; - - return true; - } - - public function disconnect() - { - $this->connection->disconnect(); - $this->setError("Manual disconnect"); - } - - /* Specific handling functions */ - - public function onTransferTimeout($conn) - { - $this->connection->disconnect(); - $this->setError("The connection timed out"); - } - - public function onConnectTimeout($conn) - { - $this->connection->disconnect(); - $this->setError("Connection attempt timed out"); - } - - public function onConnect($conn) - { - $this->connected = true; - $this->socketClass->sendSocket($this->sockInt, $this->query); - } - - public function onRead($conn) - { - $this->response .= $this->socketClass->getQueue($this->sockInt); - } - - public function onWrite($conn) - { - // do nothing, we really don't care about this - } - - public function onDead($conn) - { - $this->connection->disconnect(); - - if ($this->connected === true) - { - $this->doCallback(); - } - else - { - $this->setError($this->connection->getErrorMsg()); - } - - } - - /* Error handling */ - - private function setError($msg) - { - $this->response = $msg; - $this->type = QUERY_ERROR; - $this->doCallback(); - } - - private function doCallback() - { - if ($this->line != null && is_array($this->line) && isset($this->line['text'])) - { - $lineArgs = parser::createLine($this->line['text']); - } - else - { - $lineArgs = array(); - } - - $func = $this->function; - $this->class->$func($this->line, $lineArgs, $this->type, $this->response); - } - -} - -?> diff --git a/ircbot/socket.php b/ircbot/socket.php deleted file mode 100644 index b92fafd..0000000 --- a/ircbot/socket.php +++ /dev/null @@ -1,1010 +0,0 @@ -<?php -/* -+--------------------------------------------------------------------------- -| PHP-IRC v2.2.1 Service Release -| ======================================================== -| by Manick -| (c) 2001-2005 by http://www.phpbots.org/ -| Contact: manick@manekian.com -| irc: #manekian@irc.rizon.net -| ======================================== -+--------------------------------------------------------------------------- -| > socket module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -class socket { - - private $rawSockets; //array of raw sockets to be used by select - private $socketInfo; //index by intval($rawSockets[socket]) - private $numSockets; //number of sockets currently in use - private $writeSocks; //sockets that have write buffers queued - private $numWriteSocks; - - private $readQueueSize = 0; - - private $tcpRangeStart = 1025; - private $timeoutSeconds = 0; - private $timeoutMicroSeconds = 0; - - private $myTimeout = 0; - - private $procQueue; - - public function __construct() - { - $this->connectSockets = array(); - $this->rawSockets = array(); - $this->socketInfo = array(); - $this->writeSocks = array(); - $this->readQueueSize = 0; - $this->numSockets = 0; - $this->numWriteSocks = 0; - } - - public function setProcQueue($class) - { - $this->procQueue = $class; - } - - public function getNumSockets() - { - return $this->numSockets; - } - - public function setTcpRange($range) - { - if (intval($range) != 0) - { - $this->tcpRangeStart = $range; - } - } - - public function getHost($sockInt) - { - $status = socket_getsockname($this->socketInfo[$sockInt]->socket, $addr); - - if ($status == false) - { - return false; - } - - return $addr; - - } - - public function getRemoteHost($sockInt) - { - $status = socket_getpeername($this->socketInfo[$sockInt]->socket, $addr); - - if ($status == false) - { - return false; - } - - return $addr; - - } - - public function setTimeout($time) - { - $sec = intval($time); - $msec = intval(($time - $sec)*1e6); - - if ($sec == 0) - { - $msec = $msec < $this->myTimeout ? $this->myTimeout : $msec; - } - - if ($sec < $this->timeoutSeconds) - { - $this->timeoutSeconds = $sec; - $this->timeoutMicroSeconds = $msec; - } - else if ($sec == $this->timeoutSeconds) - { - if ($msec < $this->timeoutMicroSeconds) - { - $this->timeoutMicroSeconds = $msec; - } - } - } - - public function setHandler($sockInt, $owner, $class, $function) - { - if (!isset($this->socketInfo[$sockInt])) - { - return false; - } - - $sock = $this->socketInfo[$sockInt]; - - $sock->owner = $owner; - $sock->class = $class; - $sock->func = $function; - - return true; - } - - /* For debug... */ - public function showSocks($read, $write) - { - echo "\n\nRead:\n"; - if (is_array($read)) - { - foreach($read AS $sock) - { - echo $sock . "\n"; - } - } - echo "\nWrite:\n"; - if (is_array($write)) - { - foreach($write AS $sock) - { - echo $sock . "\n"; - } - } - echo "\n"; - } - - public function handle() - { - //For debug - //echo "Read: " . $this->readQueueSize . " Write: " . $this->writeQueueSize . "\n"; - //echo "timeout: " . $this->timeoutSeconds . "-" . $this->timeoutMicroSeconds . "\n"; - - if ($this->numSockets < 1) - { - if ($this->timeoutSeconds > 0) - { - sleep($this->timeoutSeconds); - } - - if ($this->timeoutMicroSeconds > 0) - { - usleep($this->timeoutMicroSeconds); - } - - $this->timeoutSeconds = 1000; - return; - } - - if ($this->numSockets < 1) - { - $sockArray = NULL; - $except = NULL; - } - else - { - $sockArray = $this->rawSockets; - $except = $this->rawSockets; - } - - if ($this->numWriteSocks < 1) - { - $writeArray = NULL; - } - else - { - $writeArray = $this->writeSocks; - } - - //For debug - //$this->showSocks($sockArray, $writeArray); - - $newData = socket_select($sockArray, $writeArray, $except, $this->timeoutSeconds, $this->timeoutMicroSeconds); - - $this->timeoutSeconds = 1000; - - if ($newData === false) - { - die("socket_select error"); // need to change this to handle errors - return; - } - - if (!$newData) - { - return; - } - - if (count($sockArray) != 0) - { - foreach($sockArray AS $socket) - { - $sockIntval = intval($socket); - - switch($this->socketInfo[$sockIntval]->status) - { - case SOCK_CONNECTED: - $this->readSocket($sockIntval); - break; - case SOCK_LISTENING: - $this->acceptSocket($sockIntval); - break; - case SOCK_CONNECTING: - $this->connectSocket($sockIntval); - break; - default: - break; - } - } - - } - - if (count($writeArray) != 0) - { - foreach ($writeArray AS $socket) - { - $sockIntval = intval($socket); - $this->sendSocketQueue($sockIntval, 1); - } - } - - if (count($except) != 0) - { - foreach($except AS $socket) - { - $sockIntval = intval($socket); - $this->markDead($sockIntval); - } - } - - } - - - private function callBack($sockIntval, $msg) - { - //Schedule the callback to run - if ($this->socketInfo[$sockIntval]->func != "" && - $this->socketInfo[$sockIntval]->func != null) - { - $this->procQueue->addQueue( $this->socketInfo[$sockIntval]->owner, - $this->socketInfo[$sockIntval]->class, - $this->socketInfo[$sockIntval]->func, - $msg, - .01); - } - } - - private function readSocket($sockIntval) - { - - if ($this->isDead($sockIntval)) - { - return; - } - - if ($this->socketInfo[$sockIntval]->status != SOCK_CONNECTED) - { - return; - } - - $dataRead = false; - - $socket = $this->socketInfo[$sockIntval]->socket; - //Read in 4096*30 bytes - - for ($i = 0; $i < 30; $i++) - { - $response = @socket_read($socket, 8192, PHP_BINARY_READ); - - $respLength = strlen($response); - - if ($response === false) - { - $err = socket_last_error($this->socketInfo[$sockIntval]->socket); - - if ($err != EALREADY && $err != EAGAIN && $err != EINPROGRESS) - { - $this->markDead($sockIntval); - } - break; - } - else if ($respLength === 0) - { - if ($i == 0) - { - $this->markDead($sockIntval); - } - break; - } - - $dataRead = true; - - $this->readQueueSize += $respLength; - $this->socketInfo[$sockIntval]->readLength += $respLength; - $this->socketInfo[$sockIntval]->readQueue .= $response; - - } - - if ($dataRead == true) - { - if ($this->socketInfo[$sockIntval]->readScheduled == false) - { - $this->callBack($sockIntval, CONN_READ); - $this->socketInfo[$sockIntval]->readScheduled = true; - } - } - } - - - private function sendSocketQueue($sockIntval, $queued = 0) - { - $socket = $this->socketInfo[$sockIntval]->socket; - - if ($this->isDead($sockIntval)) - { - return; - } - - if (($bytesWritten = @socket_write($socket, $this->socketInfo[$sockIntval]->writeQueue)) === false) - { - - $socketError = socket_last_error($socket); - - switch ($socketError) - { - case EAGAIN: - case EALREADY: - case EINPROGRESS: - break; - default: - $this->markDead($sockIntval); - break; - } - - } - else - { - $this->socketInfo[$sockIntval]->writeQueue = substr($this->socketInfo[$sockIntval]->writeQueue, $bytesWritten); - $this->socketInfo[$sockIntval]->writeLength -= $bytesWritten; - - //Queue Empty, Remove socket from write - if ($this->socketInfo[$sockIntval]->writeLength == 0 && $queued == 1) - { - $this->removeWriteSocketFromArray($sockIntval); - } - - if ($this->socketInfo[$sockIntval]->writeLength == 0) - { - unset($this->socketInfo[$sockIntval]->writeQueue); - $this->socketInfo[$sockIntval]->writeQueue = ""; - } - - //Callback after we wrote to socket - - if ($this->socketInfo[$sockIntval]->writeScheduled == false) - { - $this->callBack($sockIntval, CONN_WRITE); - $this->socketInfo[$sockIntval]->writeScheduled = true; - } - - } - - } - - private function createSocket() - { - $socket = socket_create(AF_INET, SOCK_STREAM, 0); - - socket_set_option($socket,SOL_SOCKET,SO_REUSEADDR,1); - - if ($socket == false) - { - return false; - } - - socket_clear_error($socket); - - if (socket_set_nonblock($socket) == false) - { - @socket_close($socket); - return false; - } - - return $socket; - } - - public function bindIP($sockInt, $ip) - { - if (!isset($this->socketInfo[$sockInt])) - { - return; - } - - $sockData = $this->socketInfo[$sockInt]; - - if ($sockData->status != SOCK_CONNECTING) - { - return; - } - - socket_bind($sockData->socket, $ip); - } - - public function addSocket($host, $port) - { - $listening = false; - - if ($host == null) - { - $host = false; - $listening = true; - } - - $socket = $this->createSocket(); - - if ($socket == false) - { - return false; - } - - if ($listening == true) - { - $boundError = false; - $currentPort = $this->tcpRangeStart; - - if ($port !== null) - { - $boundError = @socket_bind($socket, 0, $port); - if ($boundError === false) - { - return false; - } - } - else - { - while ($boundError === false) - { - $boundError = @socket_bind($socket, 0, $currentPort); - $currentPort++; - - if ($currentPort > $this->tcpRangeStart + HIGHEST_PORT) - { - return false; - } - } - - $port = $currentPort - 1; - } - - - if (socket_listen($socket) === false) - { - return false; - } - - - if (DEBUG == 1) - { - echo "Socket Listening: " . intval($socket) . "\n"; - } - - - } - else - { - if (DEBUG == 1) - { - echo "Socket Opened: " . intval($socket) . "\n"; - } - } - - $newSock = new socketInfo; - - $newSock->socket = $socket; - $newSock->owner = null; - $newSock->class = null; - $newSock->func = null; - $newSock->readQueue = ""; - $newSock->writeQueue = ""; - $newSock->readLength = 0; - $newSock->writeLength = 0; - $newSock->host = $host; - $newSock->port = $port; - $newSock->newSockInt = array(); - $newSock->readScheduled = false; - $newSock->writeScheduled = false; - - $this->socketInfo[intval($socket)] = $newSock; - - if ($listening == true) - { - $newSock->status = SOCK_LISTENING; - } - else - { - $newSock->status = SOCK_CONNECTING; - } - - $this->numSockets++; - $this->rawSockets[] = $socket; - - return intval($socket); - } - - public function clearReadSchedule($sockInt) - { - if (!isset($this->socketInfo[$sockInt])) - { - return false; - } - - $this->socketInfo[$sockInt]->readScheduled = false; - - return true; - } - - public function clearWriteSchedule($sockInt) - { - if (!isset($this->socketInfo[$sockInt])) - { - return false; - } - - $this->socketInfo[$sockInt]->writeScheduled = false; - - return true; - } - -/* - public function beginConnect($sockInt) - { - $this->procQueue->addQueue(null, $this, "connectSocketProcess", $sockInt, 0); - } -*/ - - //process to connect the socket $sockInt - public function connectSocketTimer($sockInt) - { - if (!isset($this->socketInfo[$sockInt])) - { - return false; - } - - if ($this->socketInfo[$sockInt]->status != SOCK_CONNECTING) - { - return false; - } - - $this->connectSocket($sockInt); - - return true; - } - - - //Remove all sockets from a specific irc bot - public function removeOwner($class) - { - foreach($this->socketInfo AS $sockInt => $data) - { - if ($class === $data->owner) - { - $this->killSocket($sockInt); - $this->removeSocket($sockInt); - } - } - } - - public function killSocket($sockInt) - { - if (DEBUG == 1) - { - echo "Killing socket: " . $sockInt . "\n"; - } - - if ($this->socketInfo[$sockInt]->status == SOCK_ACCEPTED) - { - $this->acceptedSockets--; - } - - if ($this->socketInfo[$sockInt]->status != SOCK_DEAD) - { - $this->removeReadSocketFromArray($sockInt); - $this->removeWriteSocketFromArray($sockInt); - $this->socketInfo[$sockInt]->status = SOCK_DEAD; - } - - if (is_resource($this->socketInfo[$sockInt]->socket)) - { - if (DEBUG == 1) - { - echo "Closed socket: " . $sockInt . "\n"; - } - - socket_clear_error($this->socketInfo[$sockInt]->socket); - socket_close($this->socketInfo[$sockInt]->socket); - } - else - { - if (DEBUG == 1) - { - echo "Socket already closed: " . $sockInt . "\n"; - } - } - } - - public function removeSocket($socketIntval) - { - - $this->readQueueSize -= $this->socketInfo[$socketIntval]->readLength; - - unset($this->socketInfo[$socketIntval]->class); - unset($this->socketInfo[$socketIntval]->owner); - unset($this->socketInfo[$socketIntval]); - } - - private function removeReadSocketFromArray($socketIntval) - { - foreach ($this->rawSockets AS $index => $socket) - { - if ($socket === $this->socketInfo[$socketIntval]->socket) - { - unset($this->rawSockets[$index]); - $this->numSockets--; - break; - } - } - } - - private function removeWriteSocketFromArray($socketIntval) - { - - foreach ($this->writeSocks AS $index => $rawSocket) - { - if ($rawSocket === $this->socketInfo[$socketIntval]->socket) - { - unset($this->writeSocks[$index]); - $this->numWriteSocks--; - break; - } - } - } - - public function sendSocket($sockInt, $data) - { - if ($this->isDead($sockInt)) - { - return; - } - - if ($this->socketInfo[$sockInt]->status != SOCK_CONNECTED) - { - return; - } - - $inQueue = $this->socketInfo[$sockInt]->writeLength > 0 ? true : false; - - $len = strlen($data); - $this->socketInfo[$sockInt]->writeQueue .= $data; - $this->socketInfo[$sockInt]->writeLength += $len; - - if (!$inQueue) - { - $this->sendSocketQueue($sockInt, 0); - - if ($this->socketInfo[$sockInt]->status == SOCK_CONNECTED) - { - if ($this->socketInfo[$sockInt]->writeLength > 0) - { - $this->writeSocks[] = $this->socketInfo[$sockInt]->socket; - $this->numWriteSocks++; - } - } - } - - return $len; - } - - private function acceptSocket($sockInt) - { - $sockData = $this->socketInfo[$sockInt]; - - $newSock = @socket_accept($sockData->socket); - socket_set_nonblock($newSock); - - if ($newSock === false) - { - return false; - } - - $newSockInt = intval($newSock); - - if (DEBUG == 1) - { - echo "Accepted new connection on: " . $newSockInt . "\n"; - } - - - $this->socketInfo[$newSockInt] = clone $sockData; - $this->socketInfo[$newSockInt]->socket = $newSock; - $this->socketInfo[$newSockInt]->status = SOCK_ACCEPTING; /* fix a onRead done before onAccept */ - - $this->numSockets++; - $this->rawSockets[] = $newSock; - - $this->socketInfo[$sockInt]->newSockInt[] = $newSockInt; - - //Schedule the callback to run - $this->callBack($sockInt, CONN_ACCEPT); - - return true; - } - - private function connectSocket($sockInt) - { - if (!isset($this->socketInfo[$sockInt])) - { - return; - } - - if ($this->socketInfo[$sockInt]->status == SOCK_CONNECTED) - { - return; - } - - if (@socket_connect($this->socketInfo[$sockInt]->socket, - $this->socketInfo[$sockInt]->host, - $this->socketInfo[$sockInt]->port) === true) - { - $this->socketInfo[$sockInt]->status = SOCK_CONNECTED; - $this->callBack($sockInt, CONN_CONNECT); - } - else - { - $socketError = socket_last_error($this->socketInfo[$sockInt]->socket); - - switch ($socketError) - { - case 10022: - if (OS != 'windows') - { - $this->markDead($sockInt); - } - break; - case EISCONN: - $this->socketInfo[$sockInt]->status = SOCK_CONNECTED; - $this->callBack($sockInt, CONN_CONNECT); - break; - case EAGAIN: - case EALREADY: - case EINPROGRESS: - break; - default: - $this->markDead($sockInt); - break; - } - } - - return; - } - - public function getSockStatus($sockInt) - { - return (isset($this->socketInfo[$sockInt]) ? $this->socketInfo[$sockInt]->status : false); - } - - public function getSockData($sockInt) - { - return (isset($this->socketInfo[$sockInt]) ? $this->socketInfo[$sockInt] : false); - } - - public function alterSocket($sockInt, $level, $opt, $val) - { - return socket_set_option($this->socketInfo[$sockInt]->socket, $level, $opt, $val); - } - - public function getSockError($sockInt) - { - return socket_last_error($this->socketInfo[$sockInt]->socket); - } - - public function getSockStringError($sockInt) - { - $strErr = "[" . self::getSockError($sockInt) . "]:" . socket_strerror(socket_last_error($this->socketInfo[$sockInt]->socket)); - $strErr = str_replace("\n", "", $strErr); - return $strErr; - } - - public function hasAccepted($sockInt) - { - if (!isset($this->socketInfo[$sockInt])) - { - return false; - } - - $newSockInt = array_shift($this->socketInfo[$sockInt]->newSockInt); - - $this->socketInfo[$newSockInt]->status = SOCK_CONNECTED; - - return $newSockInt; - } - - private function markDead($sockInt) - { - if (DEBUG == 1) - { - echo "Marking socket dead: " . $sockInt . "\n"; - } - - $this->removeReadSocketFromArray($sockInt); - $this->removeWriteSocketFromArray($sockInt); - $this->socketInfo[$sockInt]->status = SOCK_DEAD; - $this->callBack($sockInt, CONN_DEAD); - } - - public function isDead($sockInt) - { - $socket = $this->socketInfo[$sockInt]->socket; - - if (!is_resource($socket)) - { - $this->markDead($sockIntval); - return true; - } - - if (!isset($this->socketInfo[$sockInt])) - { - return true; - } - - switch ($this->socketInfo[$sockInt]->status) - { - case SOCK_DEAD: - return true; - break; - default: - return false; - break; - } - } - - public function hasWriteQueue($sockInt) - { - if ($this->socketInfo[$sockInt]->writeLength > 0) - { - return $this->socketInfo[$sockInt]->writeLength; - } - else - { - return false; - } - } - - public function getQueue($sockInt) - { - $this->readQueueSize -= $this->socketInfo[$sockInt]->readLength; - $queue = $this->socketInfo[$sockInt]->readQueue; - unset($this->socketInfo[$sockInt]->readQueue); - $this->socketInfo[$sockInt]->readQueue = ""; - $this->socketInfo[$sockInt]->readLength = 0; - return $queue; - } - - public function hasQueue($sockInt) - { - if ($this->socketInfo[$sockInt]->readLength > 0) - { - return true; - } - - return false; - } - - - public function hasLine($sockInt) - { - if (strpos($this->socketInfo[$sockInt]->readQueue, "\n") !== false) - { - return true; - } - return false; - } - - public function getQueueLine($sockInt) - { - $readQueue =& $this->socketInfo[$sockInt]->readQueue; - - if (!$this->hasLine($sockInt)) - { - return false; - } - - $crlf = "\r\n"; - $crlfLen = 2; - - $lineEnds = strpos($readQueue, $crlf); - - if ($lineEnds === false) - { - $crlf = "\n"; - $crlfLen = 1; - $lineEnds = strpos($readQueue, $crlf); - } - - $line = substr($readQueue, 0, $lineEnds); - $readQueue = substr($readQueue, $lineEnds + $crlfLen); - - $this->readQueueSize -= ($lineEnds + $crlfLen); - $this->socketInfo[$sockInt]->readLength -= ($lineEnds + $crlfLen); - - if ($readQueue == "") - { - unset($this->socketInfo[$sockInt]->readQueue); - $this->socketInfo[$sockInt]->readQueue = ""; - } - - return $line; - } - - - - /* Misc HTTP Functions */ - - public static function generatePostQuery($query, $host, $path, $httpVersion = "1.0") - { - if ($query != "" && substr($query, 0, 1) != "?") - { - $query = "?" . $query; - } - - if ($path == "") - { - $path = "/"; - } - - $postQuery = "POST " . $path . " HTTP/".$httpVersion."\r\n"; - $postQuery .= "Host: " . $host . "\r\n"; - $postQuery .= "Content-type: application/x-www-form-urlencoded\r\n"; - $postQuery .= "Content-length: " . strlen($query) . "\r\n\r\n"; - $postQuery .= $query; - - return $postQuery; - } - - public static function generateGetQuery($query, $host, $path, $httpVersion = "1.0") - { - if ($path == "") - { - $path = "/"; - } - - if ($query != "" && substr($query, 0, 1) != "?") - { - $query = "?" . $query; - } - - $getQuery = "GET " . $path . $query . " HTTP/".$httpVersion."\r\n"; - $getQuery .= "Host: " . $host . "\r\n"; - $getQuery .= "Connection: close\r\n"; - $getQuery .= "\r\n"; - - return $getQuery; - } - -} - -?> diff --git a/ircbot/timers.php b/ircbot/timers.php deleted file mode 100644 index ac85b99..0000000 --- a/ircbot/timers.php +++ /dev/null @@ -1,235 +0,0 @@ -<?php -/* -+--------------------------------------------------------------------------- -| PHP-IRC v2.2.1 Service Release -| ======================================================== -| by Manick -| (c) 2001-2005 by http://www.phpbots.org/ -| Contact: manick@manekian.com -| irc: #manekian@irc.rizon.net -| ======================================== -+--------------------------------------------------------------------------- -| > timers module -| > Module written by Manick -| > Module Version Number: 2.2.0 -+--------------------------------------------------------------------------- -| > This program is free software; you can redistribute it and/or -| > modify it under the terms of the GNU General Public License -| > as published by the Free Software Foundation; either version 2 -| > of the License, or (at your option) any later version. -| > -| > This program is distributed in the hope that it will be useful, -| > but WITHOUT ANY WARRANTY; without even the implied warranty of -| > MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -| > GNU General Public License for more details. -| > -| > You should have received a copy of the GNU General Public License -| > along with this program; if not, write to the Free Software -| > Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. -+--------------------------------------------------------------------------- -| Changes -| =======------- -| > If you wish to suggest or submit an update/change to the source -| > code, email me at manick@manekian.com with the change, and I -| > will look to adding it in as soon as I can. -+--------------------------------------------------------------------------- -*/ - -/* - * Redesigned 12/22/04... Yes... this file sucks. I basically am going to - * do a few things here. I have been stuck on this file for the past 2 weeks, - * trying to come up with some ideas to handle the hopeless situation which - * faced me. With the new queue system, this timer class became very interesting - * to handle. I had to decide how I would add proc queues to the queue class - * to handle specific timers in this file. Say, for instance, that a timer - * is added, and then another is added that has a shorter time than that one. - * The first one will have a proc queue added into the queue class, but then - * the second one will have to add another proc queue. But hold on a second, - * the way this works right now, after a timer is done running, the next one - * is added to the process queue. I handled this by keeping track of how - * many processes were in the queue, and didn't add one if there were more than - * one, and the call to setCurrentTimer was from handle(). This worked, unless - * you have a timer that repeats. Then the problem comes in, as it will not be - * added to the proc queue until the next timer is complete. To just handle - * this problem, I'm just going to add a proc to the queue for every timer - * that is added, and then every timer will have a queue in the procqueue. - * that way, we don't have to worry about anything. - * - * Also, I added a "timerStack" so that I could have reserved names and what - * not. Each timer gets a unique name or ID, and that is added to the stack, - * as well as sorted into the timerList. - * - * Okay, way that timers are handled... has changed, if you want a timer to - * repeat, you must return true from the timer, runOnce was removed. - * - * Ooohh oohh ohh! Idea. screw linked lists and shit. I'll just add each - * timer to the proc queue, and then have them call handle() with the timer - * referenced! This solves all problems, and is incredibly more efficient! - * This officially takes the last linked list out of my bot. I have NO IDEA - * why I even used them in the first place, as php already has associative arrays - * which are a lot better! GEEZ! - */ - -class timers { - - //Local variables - private $timerStack = array(); //list of all timers indexed by name - - //External Classes - private $procQueue; - private $socketClass; - private $ircClass; - - //Private list of reserved php-irc timer names (please do not - //use these names) - private $reserved = array( "listening_timer_[0-9]*", - "check_nick_timer", - "check_channels_timer", - "check_ping_timeout_timer", - ); - - public function __construct() - { - $this->time = time(); - $this->timerStack = array(); - } - - public function setSocketClass($class) - { - $this->socketClass = $class; - } - - public function setIrcClass($class) - { - $this->ircClass = $class; - } - - public function setProcQueue($class) - { - $this->procQueue = $class; - } - - public static function getMicroTime() - { - return microtime(true); - } - - public function getTimers() - { - return $this->timerStack; - } - - public function handle($timer) - { - $microTime = self::getMicroTime(); - - if (!isset($this->timerStack[$timer->name])) - { - return false; - } - - if ($this->timerStack[$timer->name] !== $timer) - { - return false; - } - - $timer->lastTimeRun = $microTime; - $timer->nextRunTime = $microTime + $timer->interval; - - if ($timer->class != null) - { - $theFunc = $timer->func; - $status = $timer->class->$theFunc($timer->args); - } - else - { - $theFunc = $timer->func; - $status = $theFunc($timer->args); - } - - if ($status != true) - { - $this->removeTimer($timer->name); - } - else - { - $this->procQueue->addQueue($this->ircClass, $this, "handle", $timer, $timer->interval); - } - - return false; - } - - public function removeAllTimers() - { - foreach ($this->timerStack AS $timer) - { - $this->removeTimer($timer->name); - } - } - - - public function addTimer($name, $class, $function, $args, $interval, $runRightAway = false) - { - if (trim($name) == "") - { - return false; - } - - if (isset($this->timerStack[$name])) - { - return false; - } - - $newTimer = new timer; - - $newTimer->name = $name; - $newTimer->class = $class; - $newTimer->func = $function; - $newTimer->args = $args; - $newTimer->interval = $interval; - $newTimer->removed = false; - - if ($runRightAway == false) - { - $newTimer->lastTimeRun = $this->getMicroTime(); - $newTimer->nextRunTime = $this->getMicroTime() + $interval; - $tInterval = $interval; - } - else - { - $newTimer->lastTimeRun = 0; - $newTimer->nextRunTime = $this->getMicroTime(); - $tInterval = 0; - } - - $this->procQueue->addQueue($this->ircClass, $this, "handle", $newTimer, $tInterval); - - $this->timerStack[$newTimer->name] = $newTimer; - - return $name; - } - - /* Remove the current timer from both the list and stack, changed in 2.1.2, can only call by - * timer name now. - */ - public function removeTimer($name) - { - if (!isset($this->timerStack[$name])) - { - return false; - } - - //Set removed flag, - $this->timerStack[$name]->removed = true; - - //Remove from stack - unset($this->timerStack[$name]->args); - unset($this->timerStack[$name]->class); - unset($this->timerStack[$name]); - - return true; - } - -} - -?> diff --git a/ircbot/typedefs.conf b/ircbot/typedefs.conf deleted file mode 100644 index 07d09cc..0000000 --- a/ircbot/typedefs.conf +++ /dev/null @@ -1,75 +0,0 @@ -type file ~ ;----Used to import files - name ~ ;----the module name - filename - -type section ~ ;----Used to section functions in dcc chat (used with 'help') - name ~ ;-id name to specify with dcc function - longname ~ ;-section name displayed when 'help' is pressed - -type ctcp ~ ;----handle all ctcp commands - name ~ ;----the command typed (or trigger, like !list) - module ~ - function - -type priv ~ ;----Used to process input of users in channels - name ~ - active ~ - inform ~ - canDeactivate ~ - usage ~ - module ~ - function - -type dcc ~ ;----Used to process input of users in dcc interface - name ~ - numArgs ~ - usage ~ - help ~ - admin ~ - module ~ - function ~ - section ;--added 2.2.0 - -type privmsg ~ ;----Used to process privmsg irc command - module ~ - function - -type notice ~ ;----Used to process notice irc command - module ~ - function - -type mode ~ ;----Used to process mode irc command - module ~ - function - -type join ~ ;----Used to process join irc command - module ~ - function - -type kick ~ ;----Used to process kick irc command - module ~ - function - -type part ~ ;----Used to process part irc command - module ~ - function - -type quit ~ ;----Used to process quit irc command - module ~ - function - -type connect ~ ;----Perform on connect - module ~ ;----Note this is really 004 from irc - function - -type disconnect ~ ;----Perform on disconnect $line['text'] holds reason - module ~ ;----Note, this is really ERROR from irc - function - -type raw ~ - module ~ - function - -type action ~ - module ~ - function