From 4a11644df4672b77e22513e462bd6d4ecd18fa16 Mon Sep 17 00:00:00 2001 From: DariusIII Date: Mon, 31 Mar 2014 12:13:10 +0200 Subject: [PATCH] Added IRCScraper from nZEDb, must be run manualy. --- lib/IRCScraper.php | 594 +++ lib/IRCScraper/.gitignore | 1 + lib/IRCScraper/README.txt | 9 + lib/IRCScraper/scrape.php | 55 + lib/IRCScraper/scrape.sh | 20 + lib/IRCScraper/scrape_daemon.sh | 21 + lib/IRCScraper/settings_example.php | 24 + lib/Net_SmartIRC/.gitignore | 4 + lib/Net_SmartIRC/CHANGELOG | 334 ++ lib/Net_SmartIRC/CREDITS | 65 + lib/Net_SmartIRC/FEATURES | 61 + lib/Net_SmartIRC/LICENSE | 508 +++ lib/Net_SmartIRC/Net/SmartIRC.php | 3281 +++++++++++++++++ lib/Net_SmartIRC/Net/SmartIRC/defines.php | 237 ++ lib/Net_SmartIRC/Net/SmartIRC/irccommands.php | 526 +++ .../Net/SmartIRC/messagehandler.php | 527 +++ lib/Net_SmartIRC/README | 88 + lib/Net_SmartIRC/modules/PingFix.php | 34 + 18 files changed, 6389 insertions(+) create mode 100644 lib/IRCScraper.php create mode 100644 lib/IRCScraper/.gitignore create mode 100644 lib/IRCScraper/README.txt create mode 100644 lib/IRCScraper/scrape.php create mode 100644 lib/IRCScraper/scrape.sh create mode 100644 lib/IRCScraper/scrape_daemon.sh create mode 100644 lib/IRCScraper/settings_example.php create mode 100644 lib/Net_SmartIRC/.gitignore create mode 100644 lib/Net_SmartIRC/CHANGELOG create mode 100644 lib/Net_SmartIRC/CREDITS create mode 100644 lib/Net_SmartIRC/FEATURES create mode 100644 lib/Net_SmartIRC/LICENSE create mode 100644 lib/Net_SmartIRC/Net/SmartIRC.php create mode 100644 lib/Net_SmartIRC/Net/SmartIRC/defines.php create mode 100644 lib/Net_SmartIRC/Net/SmartIRC/irccommands.php create mode 100644 lib/Net_SmartIRC/Net/SmartIRC/messagehandler.php create mode 100644 lib/Net_SmartIRC/README create mode 100644 lib/Net_SmartIRC/modules/PingFix.php diff --git a/lib/IRCScraper.php b/lib/IRCScraper.php new file mode 100644 index 000000000..c78d674ec --- /dev/null +++ b/lib/IRCScraper.php @@ -0,0 +1,594 @@ +db = new DB(); + $this->groups = new Groups(); + $this->functions = new Functions(); + $this->groupList = array(); + $this->IRC = $irc; + if ($debug) { + $this->IRC->setDebug(SMARTIRC_DEBUG_ALL); + } + $this->serverType = $serverType; + $this->silent = $silent; + $this->resetPreVariables(); + $this->startScraping($socket); + } + + /** + * Destruct + */ + public function __destruct() + { + // Disconnect from IRC cleanly. + if (!is_null($this->IRC)) { + if (!$this->silent) { + echo + 'Disconnecting from ' . + $this->serverType . + '.' . + PHP_EOL; + } + $this->IRC->disconnect(); + } + } + + /** + * Main method for scraping. + * + * @param bool $socket Use real sockets or fsock? + */ + protected function startScraping(&$socket) + { + switch($this->serverType) { + case 'efnet': + $server = SCRAPE_IRC_EFNET_SERVER; + $port = SCRAPE_IRC_EFNET_PORT; + $nickname = SCRAPE_IRC_EFNET_NICKNAME; + $username = SCRAPE_IRC_EFNET_USERNAME; + $realname = SCRAPE_IRC_EFNET_REALNAME; + $password = SCRAPE_IRC_EFNET_PASSWORD; + $channelList = array( + // Channel Password. + '#alt.binaries.inner-sanctum' => null, + '#alt.binaries.cd.image' => null, + '#alt.binaries.movies.divx' => null, + '#alt.binaries.sounds.mp3.complete_cd' => null, + '#alt.binaries.warez' => null, + '#alt.binaries.teevee' => 'teevee', + '#alt.binaries.moovee' => 'moovee', + '#alt.binaries.erotica' => 'erotica', + '#alt.binaries.flac' => 'flac', + //'#alt.binaries.foreign' => 'foreign' + ); + $regex = + // Simple regex, more advanced regex below when doing the real checks. + '/' . + 'FILLED.*Pred.*ago' . // a.b.inner-sanctum + '|' . + 'Thank.*you.*Req.*Id.*Request' . // a.b.cd.image, a.b.movies.divx, a.b.sounds.mp3.complete_cd, a.b.warez + '|' . + 'Thank.*?you.*?You.*?are.*?now.*?Filling.*?ReqId.*?' . // a.b.flac a.b.teevee + '|' . + 'Thank.*?You.*?Request.*?Filled!.*?ReqId' . // a.b.moovee + '|' . + 'That.*?was.*?awesome.*?Shall.*?ReqId' . // a.b.erotica + '/i'; + break; + + case 'corrupt': + $server = SCRAPE_IRC_CORRUPT_SERVER; + $port = SCRAPE_IRC_CORRUPT_PORT; + $nickname = SCRAPE_IRC_CORRUPT_NICKNAME; + $username = SCRAPE_IRC_CORRUPT_USERNAME; + $realname = SCRAPE_IRC_CORRUPT_REALNAME; + $password = SCRAPE_IRC_CORRUPT_PASSWORD; + $channelList = array('#pre' => null); + $regex = '/PRE:.+?\[.+?\]/i'; // #pre + break; + + case 'zenet': + $server = SCRAPE_IRC_ZENET_SERVER; + $port = SCRAPE_IRC_ZENET_PORT; + $nickname = SCRAPE_IRC_ZENET_NICKNAME; + $username = SCRAPE_IRC_ZENET_USERNAME; + $realname = SCRAPE_IRC_ZENET_REALNAME; + $password = SCRAPE_IRC_ZENET_PASSWORD; + $channelList = array('#Pre' => null); + $regex = '/^\(PRE\)\s+\(/'; // #Pre + break; + + default: + return; + } + + // Use real sockets instead of fsock. + $this->IRC->setUseSockets($socket); + + // This will scan channel messages for the regex above. + $this->IRC->registerActionhandler(SMARTIRC_TYPE_CHANNEL, $regex, $this, 'check_type'); + + // If there's a problem during connection, try to reconnect. + $this->IRC->setAutoRetry(true); + + // If problem connecting, wait 5 seconds before reconnecting. + $this->IRC->setReconnectdelay(5); + + // Try 4 times before giving up. + $this->IRC->setAutoRetryMax(4); + + // If a network error happens, automatically reconnect. + $this->IRC->setAutoReconnect(true); + + // Connect to IRC. + $connection = $this->IRC->connect($server, $port); + if ($connection === false) { + exit ( + 'Error connecting to (' . + $server . + ':' . + $port . + '). Please verify your server information and try again.' . + PHP_EOL + ); + } + + // Login to IRC. + $this->IRC->login( + // Nick name. + $nickname, + // Real name. + $realname, + // User mode. + 0, + // User name. + $username, + // Password. + (empty($password) ? null : $password) + ); + + // Join channels. + $this->IRC->join($channelList); + + if (!$this->silent) { + echo + '[' . + date('r') . + '] [Scraping of IRC channels for ' . + $this->serverType . + ' started.]' . + PHP_EOL; + } + + // Wait for action handlers. + $this->IRC->listen(); + + // If we return from action handlers, disconnect from IRC. + $this->IRC->disconnect(); + } + + /** + * Check channel and poster, send to right method. + * + * @param object $irc + * @param object $data + */ + public function check_type($irc, $data) + { + $channel = strtolower($data->channel); + $poster = strtolower($data->nick); + + switch ($poster) { + case 'sanctum': + if ($channel === '#alt.binaries.inner-sanctum') { + $this->inner_sanctum($data->message); + } + break; + + case 'alt-bin': + $this->alt_bin($data->message, $channel); + break; + + case 'pr3': + $this->corrupt_pre($data->message); + break; + + case 'abflac': + if ($channel === '#alt.binaries.flac') { + $this->ab_flac($data->message); + } + break; + + case 'abking': + if ($channel === '#alt.binaries.moovee') { + $this->ab_moovee($data->message); + } + break; + + case 'ginger': + if ($channel === '#alt.binaries.erotica') { + $this->ab_erotica($data->message); + } + break; + + case 'abgod': + if ($channel === '#alt.binaries.teevee') { + $this->ab_teevee($data->message); + } + break; + + case 'theannouncer': + if ($channel === '#pre') { + $this->zenet_pre($data->message); + } + break; + + default: + break; + } + } + + /** + * Get pre date from wD xH yM zS ago string. + * + * @param $agoString + */ + protected function getTimeFromAgo($agoString) + { + $predate = 0; + // Get pre date from this format : 10m 54s + if (preg_match('/((?P\d+)d)?\s*((?P\d+)h)?\s*((?P\d+)m)?\s*((?P\d+)s)?/i', $agoString, $matches)) { + if (!empty($matches['day'])) { + $predate += ((int)($matches['day']) * 86400); + } + if (!empty($matches['hour'])) { + $predate += ((int)($matches['hour']) * 3600); + } + if (!empty($matches['min'])) { + $predate += ((int)($matches['min']) * 60); + } + if (!empty($matches['sec'])) { + $predate += (int)$matches['sec']; + } + if ($predate !== 0) { + $predate = (time() - $predate); + } + } + $this->CurPre['predate'] = ($predate === 0 ? '' : $this->functions->from_unixtime($predate)); + } + + /** + * Go through regex matches, find PRE info. + * + * @param array $matches + */ + protected function siftMatches(&$matches) + { + $this->CurPre['md5'] = $this->db->escapeString(md5($matches['title'])); + $this->CurPre['title'] = $matches['title']; + + if (isset($matches['reqid'])) { + $this->CurPre['reqid'] = $matches['reqid']; + } + if (isset($matches['size'])) { + $this->CurPre['size'] = $matches['size']; + } + if (isset($matches['predago'])) { + $this->getTimeFromAgo($matches['predago']); + } + if (isset($matches['category'])) { + $this->CurPre['category'] = $matches['category']; + } + $this->checkForDupe(); + } + + /** + * Gets new PRE from #a.b.erotica + * + * @param string $message The IRC message to parse. + */ + protected function ab_erotica(&$message) + { + //That was awesome [*Anonymous*] Shall we do it again? ReqId:[326377] [0-Day] [FULL 23x15MB Gyno-X.14.03.08.Annie.XXX.MP4-FUNKY] Filenames:[GX080314X8HRRZ2A8] Comments:[0] Watchers:[0] Total Size:[322MB] Points Earned:[23] + //That was awesome [*Anonymous*] Shall we do it again? ReqId:[326264] [HD-Clip] [FULL 16x50MB TeenSexMovs.14.03.30.Daniela.XXX.720p.WMV-iaK] Filenames:[iak-teensexmovs-140330] Comments:[0] Watchers:[0] Total Size:[753MB] Points Earned:[54] [Pred 3m 20s ago] + if (preg_match('/ReqId:\[(?P\d+)\]\s+\[.+?\]\s+\[FULL\s+\d+x\d+[KMGTP]?B\s+(?P.+?)\].+?Size:\[(?P<size>.+?)\](.+?\[Pred\s+(?P<predago>.+?)\s+ago\])?/i', $message, $matches)) { + $this->CurPre['source'] = '#a.b.erotica'; + $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.erotica'); + $this->CurPre['category'] = 'XXX'; + $this->siftMatches($matches); + } + } + + /** + * Gets new PRE from #a.b.flac + * + * @param string $message The IRC message to parse. + */ + protected function ab_flac(&$message) + { + //Thank You [*Anonymous*] You are now Filling ReqId:[42548] [FULL VA-Diablo_III_Reaper_of_Souls_Collectors_Edition_Soundtrack-CD-FLAC-2014-BUDDHA] [Pred 55s ago] + if (preg_match('/You\s+are\s+now\s+Filling\s+ReqID:.*?\[(?P<reqid>\d+)\]\s+\[FULL\s+(?P<title>.+?)\]\s+\[Pred\s+(?P<predago>.+?)\s+ago\]/i', $message, $matches)) { + $this->CurPre['source'] = '#a.b.flac'; + $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.sounds.flac'); + $this->siftMatches($matches); + } + } + + /** + * Gets new PRE from #a.b.moovee + * + * @param string $message The IRC message to parse. + */ + protected function ab_moovee(&$message) + { + //Thank You [*Anonymous*] Request Filled! ReqId:[140445] [FULL 94x50MB Burning.Daylight.2010.720p.BluRay.x264-SADPANDA] Requested by:[*Anonymous* 3h 29m ago] Comments:[0] Watchers:[0] Points Earned:[314] [Pred 4h 29m ago] + if (preg_match('/ReqId:\[(?P<reqid>\d+)\]\s+\[FULL\s+\d+x\d+[MGPTK]?B\s+(?P<title>.+?)\]\s+.+?\[Pred\s+(?P<predago>.+?)\s+ago\]/i', $message, $matches)) { + $this->CurPre['source'] = '#a.b.moovee'; + $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.moovee'); + $this->siftMatches($matches); + } + } + + /** + * Gets new PRE from #a.b.teevee + * + * @param string $message The IRC message to parse. + */ + protected function ab_teevee(&$message) + { + //Thank You [*Anonymous*] You are now Filling ReqId:[183443] [FULL Ant.and.Decs.Saturday.Night.Takeaway.S11E06.HDTV.x264-W4F] [Pred 1m 43s ago] + if (preg_match('/You\s+are\s+now\s+Filling\s+ReqId:\[(?P<reqid>\d+)\]\s+\[FULL\s+(?P<title>.+?)\]\s+\[Pred\s+(?P<predago>.+?)\s+ago\]/', $message, $matches)) { + $this->CurPre['source'] = '#a.b.teevee'; + $this->CurPre['grpoupid'] = $this->getGroupID('alt.binaries.teevee'); + $this->siftMatches($matches); + } + } + + /** + * Gets new PRE from #Pre on zenet + * + * @param string $message The IRC message to parse. + */ + protected function zenet_pre(&$message) + { + //(PRE) (XXX) (The.Golden.Age.Of.Porn.Candy.Samples.XXX.WEBRIP.WMV-GUSH) + if (preg_match('/^\(PRE\)\s+\((?P<category>.+?)\)\s+\((?P<title>.+?)\)$/', $message, $matches)) { + $this->CurPre['source'] = '#Pre@zenet'; + $this->siftMatches($matches); + } + } + + /** + * Gets new PRE from #pre on Corrupt-net + * + * @param string $message The IRC message to parse. + */ + protected function corrupt_pre(&$message) + { + //PRE: [TV-X264] Tinga.Tinga.Fabeln.S02E11.Warum.Bienen.stechen.GERMAN.WS.720p.HDTV.x264-RFG + if (preg_match('/^PRE:\s+\[(?P<category>.+?)\]\s+(?P<title>.+)$/i', $message, $matches)) { + $this->CurPre['source'] = '#pre@corrupt'; + $this->siftMatches($matches); + } + } + + /** + * Gets new PRE from #a.b.inner-sanctum. + * + * @param string $message The IRC message to parse. + */ + protected function inner_sanctum(&$message) + { //[FILLED] [ 341953 | Emilie_Simon-Mue-CD-FR-2014-JUST | 16x79 | MP3 | *Anonymous* ] [ Pred 10m 54s ago ] + //06[FILLED] [ 342184 06| DJ_Tuttle--Optoswitches_(FF_011)-VINYL-1997-CMC_INT 06| 7x47 06| MP3 06| *Anonymous* 06] 06[ Pred 5h 46m 10s ago 06]" + if (preg_match('/FILLED.*?\]\s+\[\s+(?P<reqid>\d+)\s+.*?\|\s+(?P<title>.+?)\s+.*?\|\s+.+?\s+.*?\|\s+(?P<category>.+?)\s+.*?\|\s+.+?\s+.*?\]\s+.*?\[\s+Pred\s+(?P<predago>.+?)\s+ago\s+.*?\]/i', $message, $matches)) { + $this->CurPre['source'] = '#a.b.inner-sanctum'; + $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.inner-sanctum'); + $this->siftMatches($matches); + } + } + + /** + * Get new PRE from Alt-Bin groups. + * + * @param string $message The IRC message from the bot. + * @param string $channel The IRC channel name. + */ + protected function alt_bin(&$message, &$channel) + { + //Thank you<Bijour> Req Id<137732> Request<The_Blueprint-Phenomenology-(Retail)-2004-KzT *Pars Included*> Files<19> Dates<Req:2014-03-24 Filling:2014-03-29> Points<Filled:1393 Score:25604> + //Thank you<gizka> Req Id<42948> Request<Bloodsport.IV.1999.FS.DVDRip.XviD.iNT-EwDp *Pars Included*> Files<55> Dates<Req:2014-03-22 Filling:2014-03-29> Points<Filled:93 Score:5607> + if (preg_match('/Req.+?Id.*?<.*?(?P<reqid>\d+).*?>.*?Request.*?<\d{0,2}(?P<title>.+?)(\s+\*Pars\s+Included\*\d{0,2}>|\d{0,2}>)\s+/i', $message, $matches)) { + $this->CurPre['source'] = str_replace('#alt.binaries', '#a.b', $channel); + $this->CurPre['groupid'] = $this->getGroupID(str_replace('#', '', $channel)); + $this->siftMatches($matches); + } + } + + /** + * Check if we already have the PRE. + * + * @return bool True if we already have, false if we don't. + */ + protected function checkForDupe() + { + if ($this->db->queryOneRow(sprintf('SELECT ID FROM prehash WHERE md5 = %s', $this->CurPre['md5'])) === false) { + $this->insertNewPre(); + } else { + $this->updatePre(); + } + } + + /** + * Insert new PRE into the DB. + */ + protected function insertNewPre() + { + if (empty($this->CurPre['title'])) { + return; + } + + $query = 'INSERT INTO prehash ('; + + $query .= (!empty($this->CurPre['size']) ? 'size, ' : ''); + $query .= (!empty($this->CurPre['category']) ? 'category, ' : ''); + $query .= (!empty($this->CurPre['source']) ? 'source, ' : ''); + $query .= (!empty($this->CurPre['reqid']) ? 'requestID, ' : ''); + $query .= (!empty($this->CurPre['groupid']) ? 'groupID, ' : ''); + + $query .= 'predate, md5, title, adddate) VALUES ('; + + $query .= (!empty($this->CurPre['size']) ? $this->db->escapeString($this->CurPre['size']) . ', ' : ''); + $query .= (!empty($this->CurPre['category']) ? $this->db->escapeString($this->CurPre['category']) . ', ' : ''); + $query .= (!empty($this->CurPre['source']) ? $this->db->escapeString($this->CurPre['source']) . ', ' : ''); + $query .= (!empty($this->CurPre['reqid']) ? $this->CurPre['reqid'] . ', ' : ''); + $query .= (!empty($this->CurPre['groupid']) ? $this->CurPre['groupid'] . ', ' : ''); + $query .= (!empty($this->CurPre['predate']) ? $this->CurPre['predate'] . ', ' : 'NOW(), '); + + $query .= '%s, %s, NOW())'; + + $this->db->exec( + sprintf( + $query, + $this->CurPre['md5'], + $this->db->escapeString($this->CurPre['title']) + ) + ); + + $this->doEcho(true); + + $this->resetPreVariables(); + } + + /** + * Updates PRE data in the DB. + */ + protected function updatePre() + { + if (empty($this->CurPre['title'])) { + return; + } + + $query = 'UPDATE prehash SET '; + + $query .= (!empty($this->CurPre['size']) ? 'size = ' . $this->db->escapeString($this->CurPre['size']) . ', ' : ''); + $query .= (!empty($this->CurPre['category']) ? 'category = ' . $this->db->escapeString($this->CurPre['category']) . ', ' : ''); + $query .= (!empty($this->CurPre['source']) ? 'source = ' . $this->db->escapeString($this->CurPre['source']) . ', ' : ''); + $query .= (!empty($this->CurPre['reqid']) ? 'requestID = ' . $this->CurPre['reqid'] . ', ' : ''); + $query .= (!empty($this->CurPre['groupid']) ? 'groupID = ' . $this->CurPre['groupid'] . ', ' : ''); + $query .= (!empty($this->CurPre['predate']) ? 'predate = ' . $this->CurPre['predate'] . ', ' : ''); + + if ($query === 'UPDATE prehash SET '){ + return; + } + + $query .= 'title = ' . $this->db->escapeString($this->CurPre['title']); + $query .= ' WHERE md5 = ' . $this->CurPre['md5']; + + $this->db->exec($query); + + $this->doEcho(false); + + $this->resetPreVariables(); + } + + protected function doEcho($new = true) + { + if (!$this->silent) { + echo + '[' . + date('r') . + ($new ? '] [ Added Pre ] [' : '] [Updated Pre] [') . + $this->CurPre['source'] . + '] [' . + $this->CurPre['title'] . + ']' . + (!empty($this->CurPre['category']) ? ' [' . $this->CurPre['category'] . ']' : '') . + PHP_EOL; + } + } + + /** + * Get a group ID for a group name. + * + * @param string $groupName + * + * @return mixed + */ + protected function getGroupID($groupName) + { + if (!isset($this->groupList[$groupName])) { + $this->groupList[$groupName] = $this->functions->getIDByName($groupName); + } + return $this->groupList[$groupName]; + } + + /** + * After updating or inserting new PRE, reset these. + */ + protected function resetPreVariables() + { + $this->CurPre = + array( + 'title' => '', + 'md5' => '', + 'size' => '', + 'predate' => '', + 'category' => '', + 'source' => '', + 'groupID' => '', + 'reqID' => '' + + ); + } +} \ No newline at end of file diff --git a/lib/IRCScraper/.gitignore b/lib/IRCScraper/.gitignore new file mode 100644 index 000000000..9f37e3549 --- /dev/null +++ b/lib/IRCScraper/.gitignore @@ -0,0 +1 @@ +/settings.php diff --git a/lib/IRCScraper/README.txt b/lib/IRCScraper/README.txt new file mode 100644 index 000000000..d5cf7bd54 --- /dev/null +++ b/lib/IRCScraper/README.txt @@ -0,0 +1,9 @@ +These scripts run IRC bots to get PRE information. + +You must first copy settings_example.php to settings.php and change the settings in the file (settings.php). + +Next you can run scrape.php, it will tell you all the options. + +scrape.sh runs the bots with text output, if you cancel the script, one of the bots will still run, you must kill it manually. + +scrape_daemon.sh runs the bots with no text output and lets go of the terminal lock (if you want to restart the script later, you MUST kill the bots first). \ No newline at end of file diff --git a/lib/IRCScraper/scrape.php b/lib/IRCScraper/scrape.php new file mode 100644 index 000000000..ddd7132b7 --- /dev/null +++ b/lib/IRCScraper/scrape.php @@ -0,0 +1,55 @@ +<?php + +if (!is_file('settings.php')) { + exit('Copy settings_example.php to settings.php and change the settings.' . PHP_EOL); +} + +if (!isset($argv[1])) { + exit( + 'Argument 1: cz|efnet ; Scrape efnet or corrupt/zenet.' . PHP_EOL . + ' ; Both zenet and corrupt pre the same, so pick one or the other in settings.php' . PHP_EOL . + ' ; You can run efnet at the same time as corrupt or zenet.' . PHP_EOL . + 'Argument 2: (optional) false|true ; True runs in silent mode (no text output)' . PHP_EOL . + 'Argument 3: (optional) false|true ; True turns on debug (not recommended)' . PHP_EOL . + 'Argument 4: (optional) false|true ; True uses real sockets(faster), false uses fsock. If you have issues with real sockets, try fsock.' . PHP_EOL . + 'ex:' . PHP_EOL . + 'php ' . $argv[0] . ' efnet ; Scrapes efnet with text output.' . PHP_EOL . + 'php ' . $argv[0] . ' cz true > /dev/null 2>&1 ; (unix) Scrapes corrupt/zenet with no text output, in the background (you can close your terminal window).' . PHP_EOL . + 'php ' . $argv[0] . ' efnet true ; Scrapes efnet with no text output, keeps lock on terminal (closing terminal kills the scraping).' . PHP_EOL . + 'php ' . $argv[0] . ' cz true true ; Scrapes corrupt/zenet with text output and debug output.' . PHP_EOL + ); +} + +if (!in_array($argv[1], array('efnet', 'cz'))) { + exit('Error, must be efnet or cz, you typed: ' . $argv[1] . PHP_EOL); +} + +require_once(dirname(__FILE__)."/../../bin/config.php"); +require_once(dirname(__FILE__).'/../Net_SmartIRC/Net/SmartIRC.php'); +require_once(dirname(__FILE__)."/../IRCScraper.php"); +require_once 'settings.php'; + +if (!defined('SCRAPE_IRC_EFNET_NICKNAME') || + !defined('SCRAPE_IRC_CORRUPT_NICKNAME') || + !defined('SCRAPE_IRC_ZENET_NICKNAME')) { + exit ('ERROR! You must update your settings.php using settings_example.php' . PHP_EOL); +} + +if (SCRAPE_IRC_EFNET_NICKNAME == '' || SCRAPE_IRC_CORRUPT_NICKNAME == '' || SCRAPE_IRC_ZENET_NICKNAME == '') { + exit("ERROR! You must put a username in settings.php" . PHP_EOL); +} + +if ($argv[1] === 'cz') { + if (SCRAPE_IRC_C_Z_BOOL === true) { + $argv[1] = 'corrupt'; + } else { + $argv[1] = 'zenet'; + } +} + +$silent = ((isset($argv[2]) && $argv[2] === 'true') ? true : false); +$debug = ((isset($argv[3]) && $argv[3] === 'true') ? true : false); +$socket = ((isset($argv[4]) && $argv[4] === 'false') ? false : true); + +// Net_SmartIRC started here, or else globals are not properly set. +$scraper = new IRCScraper(new Net_SmartIRC(), $argv[1], $silent, $debug, $socket); \ No newline at end of file diff --git a/lib/IRCScraper/scrape.sh b/lib/IRCScraper/scrape.sh new file mode 100644 index 000000000..2ef2d1d1a --- /dev/null +++ b/lib/IRCScraper/scrape.sh @@ -0,0 +1,20 @@ +#!/bin/bash +cmd1="/usr/bin/php scrape.php corrupt"; +cmd2="/usr/bin/php scrape.php efnet"; + +# Kill corrupt if it's already open. +`ps -ef | grep "php corrupt" | awk '{print $2}' | xargs kill` +sleep 2 + +# Run corrupt in the background. +$cmd1 & +sleep 3 +echo "" +echo "This started scrapeCorrupt in the background, if you cancel this script, it will still run, so you must kill it manually." +echo "scrapeEfnet, will close however, since it was not started in the background." +echo "" +echo `ps aux | grep 'php corrupt' | awk '{print $2}'` +echo "To kill it, in the message above, you see a number, in a command line, type kill theNumber (theNumber, is the number over this line, the one to the left)" +echo "" +sleep 3 +$cmd2 \ No newline at end of file diff --git a/lib/IRCScraper/scrape_daemon.sh b/lib/IRCScraper/scrape_daemon.sh new file mode 100644 index 000000000..3761c783d --- /dev/null +++ b/lib/IRCScraper/scrape_daemon.sh @@ -0,0 +1,21 @@ +#!/bin/bash + +# This runs IRCScraper silently in the background. + +cmd1="/usr/bin/php scrape.php corrupt true"; +cmd2="/usr/bin/php scrape.php efnet true"; + +echo "Started IRCScraping in daemon mode." + +# Kill corrupt if it's already open. +`ps -ef | grep "php corrupt" | awk '{print $2}' | xargs kill` +sleep 2 +# Kill efnet if it's already open. +`ps -ef | grep "php efnet" | awk '{print $2}' | xargs kill` +sleep 2 + +# Run corrupt +$cmd1 & +sleep 3 +# Run efnet +$cmd2 & \ No newline at end of file diff --git a/lib/IRCScraper/settings_example.php b/lib/IRCScraper/settings_example.php new file mode 100644 index 000000000..a7a9ee9f8 --- /dev/null +++ b/lib/IRCScraper/settings_example.php @@ -0,0 +1,24 @@ +<?php +// If you are lazy, just change this, or else go and change everything else you need to. +$username = ''; + +// IRC EFNET server address. Change this only if you have issues. +define('SCRAPE_IRC_EFNET_SERVER', 'irc.Prison.NET'); +// Port for the efnet server. +define('SCRAPE_IRC_EFNET_PORT', '6667'); +// IRC Corrupt.net address. +define('SCRAPE_IRC_CORRUPT_SERVER', 'irc.corrupt-net.org'); +// Port for the corrupt server. +define('SCRAPE_IRC_CORRUPT_PORT', '6667'); +// Nick name in the IRC channel. +define('SCRAPE_IRC_EFNET_NICKNAME', "$username"); +define('SCRAPE_IRC_CORRUPT_NICKNAME', "$username"); +// User name, used to log in to the server (like a ZNC server). Use the same as Nick name if you don't know what this is for. +define('SCRAPE_IRC_EFNET_USERNAME', "$username"); +define('SCRAPE_IRC_CORRUPT_USERNAME', "$username"); +// Password used to log in to the server (like a ZNC server). Leave false if you don't require a password. +define('SCRAPE_IRC_EFNET_PASSWORD', false); +define('SCRAPE_IRC_CORRUPT_PASSWORD', false); +// "Real name" for IRC server. Use the same as Nick name if you don't know what this is for. +define('SCRAPE_IRC_EFNET_REALNAME', "$username"); +define('SCRAPE_IRC_CORRUPT_REALNAME', "$username"); \ No newline at end of file diff --git a/lib/Net_SmartIRC/.gitignore b/lib/Net_SmartIRC/.gitignore new file mode 100644 index 000000000..869f49858 --- /dev/null +++ b/lib/Net_SmartIRC/.gitignore @@ -0,0 +1,4 @@ +# composer related +composer.lock +composer.phar +vendor diff --git a/lib/Net_SmartIRC/CHANGELOG b/lib/Net_SmartIRC/CHANGELOG new file mode 100644 index 000000000..b5424ed91 --- /dev/null +++ b/lib/Net_SmartIRC/CHANGELOG @@ -0,0 +1,334 @@ +/** + * $Id$ + * $Revision$ + * $Author$ + * $Date$ + */ + +v1.1.0: +------ +fixes: + +changes: + +new: + - applied reconnect delay patch (sf.net patch #883820) from Ronald Hummelink <ronaldhummelink@users.sourceforge.net> + added setReconnectdelay() method, allows delay between reconnects. This reduces CPU load and prevents DoS. + - applied autoretry patch (sf.net patch #883821) from Ronald Hummelink <ronaldhummelink@users.sourceforge.net> + added setAutoRetryMax() method, makes connect retries cleaner. + - added send() method, can be used to send raw message to the IRC server. + +v0.5.6: +------ +fixes: + - renamed Net_SmartIRC_base::Net_SmartIRC to + Net_SmartIRC_base::Net_SmartIRC_base + a PHP4 bug made it work, in PHP5 its fixed and doesn't + (closes PEAR bug #1466, sf.net patch #967067) + - fixed a bug in _rawreceive() + the parser checked if he found a colon (messagepart) but +1 was added, the + check never worked right (I found this bug while porting SmartIRC to C#) + - fixed bug in _gettype() + the regexs was too sloppy, sometimes it got confused, this can break easily + the ChannelSync code. + - fixed bug in _event_rpl_whoreply() + on some IRC networks, the channel info in who replies can't be used, they + return sometimes random channels, this can break ChannelSync code. + - fixed include paths in example scripts (closes PEAR bug #2042) + +changes: + - applied load socket extension patch (sf.net patch #911993) from + Anatoly Techtonik <techtonik@users.sourceforge.net> + if the socket extension is not loaded, it will now try to load it for *nix + and windows. + +new: + - added objListenFor() method + it works like listenFor() but returns an array of the received ircdata + objects (not just ircdata->message like listenFor() does) + +v0.5.5: +------- +fixes: + - fixed a bug in _rawreceive() + messages were parsed wrong which caused problems with kick reasons. + (thx to sniper for reporting this). + - fixed bug in message() + CTCP ACTION messages had missing \001 at the end. + - fixed a bug in quit(), which caused quit messages not to be sent to the server. + - fixed reconnect() bug, it sent the channel join requests right after connect(), + and tried to join a channel without a name. + - fixes in ChannelSync code + When a user joins a channel after SmartIRC, no WHO info is updated in the user object. + Fixed wrong update of channel mode when rpl_channelmodeis received. + Fixed bug in _mode() method, which caused wrong handling of mode changes. + Topic updates are now tracked (thanks to sniper). + Fixed bug which caused fatal errors with ChannelSync enabled + (closes sf.net bug #705269). + Fixed bug in _event_mode(), unhandled modes were stored wrong. + Fixed bug in _event_rpl_namreply(), which caused that the first char of the first nick + of a namreply got cut (closes sf.net bug #747832). + - fixed bug in _checktimer() + Which caused problems when a timehandler is unregistered. + - fixed _gettye() + It wasn't recognizing SMARTIRC_TYPE_ACTION. + - removed if(!$obj) check for newly created objects (closes PHP bug #24622), + required for PHP 4.1.2 compatibility. + +changes: + - removed all irc commands from SmartIRC.php + they have now their own file (SmartIRC/irccommands.php). + - Net_SmartIRC_messagehandler class now extends Net_SmartIRC_irccommands. + - removed the 1. parameter (&$irc) of all message handlers, not needed anymore. + - renamed class Net_SmartIRC_user to Net_SmartIRC_channeluser, + added class Net_SmartIRC_ircuser. + - added prefix _event to all message handlers (needed because of class restructuring). + - tweaked filling of the ircdata objects. + - log() now checks the passed debug level bitwise. + - $data->message will be null instead of random garbage, + if the IRC message has no colon (the message part), + - All methods that depend on ChannelSync mode, checks if it's enabled. + - Optimized the usage of time() for $this->_lastrx. + - updated the URL of a SmartIRC based bot (atbs). + - _loggedin is now set to false when the socket is dead, + required for proper working reconnect(). + - on a reconnect(), the logfile won't be overwritten anymore. + - updated phpdoc tags. + - all access to the channel array now uses strtolower() for the key. + - fixed typo in function name setChannelSynching(), + now it's called setChannelSyncing() with a BC wrapper. + - removed all SMARTIRC_ prefixes for debug output. + - changed isJoined($channel) to isJoined($channel, $nickname) + for checking if the specified user is joined. + - removed "destructors", because they don't free the memory. + +new: + - added isOpped() isVoiced() isBanned(). + - added debug output and debug level for the messageparser. + - reconnect() uses now the channel key if one exists. + - added channel key syncing in _mode(). + - when an actionhandler message regex has a leading '/' then the regex is used as it is, + this allows complex perl regex's. + - added message type SMARTIRC_TYPE_CTCP_REQUEST and SMARTIRC_CTCP_REPLY for more advanced CTCP. + - added new log destinations SMARTIRC_NONE and SMARTIRC_BROWSEROUT + (for firendly browserouput). When the script is called from a browser, + the BROWSEROUT will automatic be used (closed sf.net bug #708155). + - added error handling for socket_select() in _rawreceive(). + - added getMessage() to Net_SmartIRC_Error class. + - added debug level for ChannelSync code (SMARTIRC_DEBUG_CHANNELSYNCING). + - added filename and linenumber to debug output. + - added key property to channel class. + - added to all IRC commands optional $priority parameter with default value SMARTIRC_MEDIUM. + - added isError() for more advanced errorhandling, needed for encapsulation. + - added _isValidType() method, which checks for valid SMARTIRC_TYPE_* types. + +v0.5.1 +------ +fixes: + - major bugs in ChannelSynching fixed. + - fsocks support fixed. + - setUseSocket() method fixed. + If false was passed as parameter, it tried to load the socket extension. + Also warnings are now suppressed with @ in front of dl(). + - fixed a typo in reconnect(). + - missing SMARTIRC_DEBUG_CHANNELSYNCHING constant added. + +changes: + - new design for HTML documentation used (PEAR template). + - moved all examples to their own directory (examples/). + - moved the documentation to docs/HTML/. + - added new file descriptions to README. + - removed not needed parts of DOCUMENTATION (most is now in the HTML version). + - updated the HTML documentation. + +new: + - example5/6/7.php added. + - setAutoRetry() method added. + Autoretrying of connecting to the IRC server, is now supported. + +v0.5.0 +------ +fixes: + - fixed critical bug in the main _rawreceive() for() loop, messages were lost. + +changes: + - License changed from GPL to LGPL. + - updated in all files the copyright year. + - changed documentation tags in front of all methods to the phpDocumentator compatible format. + - improved connect() errorhandling. + - changed login() parameters to $nick, $realname, $usermode = 0, $username = null, $password = null. + - changed join() parameters to $channelarray, $key = null. + - changed kick() parameters to $channel, $nicknamearray, $reason = null. + - changed listenFor() parameters to $messagetype + return value is now the result, instead the of a reference to the result parameter. + - sendbuffer has now 3 queues: high, medium and low + high sends 2 messages, then 1 of medium + low is only send if high _and_ medium is empty. + - select() call for sockets is strongly optimized + +new: + - phpDocumentator package tags. + - include() for messagehandler.php (needed for the new API). + - setChannelSynching() method, for enabling the channel synching. + - setCtcpVersion() method, for changing the ctcp version reply string. + - setReceiveTimeout() method, for changing the receive timeout. + - setTransmitTimeout() method, for changing the transmit timeout. + - setAutoReconnect() method, for enabling the autoreconnect feature. + - channel variable, a reference to _channels because $object->channel("#chan")->topic is not possible in PHP4 (ZE1). + - reconnect() method, it will reconnect and also join all channels. + - channel() method, getting a reference to the channel, only if channelsynching is on. + - added ident, host, messageex and rawmessageex variables to the Net_SmartIRC_data class. + - class Net_SmartIRC_user, stores info about one user, only used if channelsynching is on. + - class Net_SmartIRC_channel, stores info about one channel, only used if channelsynching is on. + +v0.4.0 +------ +* phpSmartIRCclass.inc.php: + - fixed serious socket bug + The buffer of the socket got full because only 512 bytes were read at once, + which caused losing some IRC messages that are comming fast like the MOTD. + Now it will read 10240 bytes at once, and doesn't loose any IRC message. + - fixed sendbuffer + The sendbuffer will only be sent, when the class is fully connected and + registered on the IRC network. Before if a nickname collision happened, + all sent IRC commands from the buffer were ignored by the IRC server. + - fixed socket status + Socket handling is now compatible with PHP 4.3 dev. + - fixed $_nick + When the nickname got changed because of nickname is already in use, + $_nick will be updated. (thanks for the hint to Andreas Streichardt). + - fixed actionhandler ids (unregister caused that the other ids were changed). + - fixed TYPE_TOPIC to the right bitoperator value. + - added a reference to the IRC class in actionhandler callbacks + WARNING: all user writtin methods have to be changed!! + method( &$data ) _has to be changed_ to method( &$irc, &$data ) + If you don't change those, your IRC scripts will _not_ work anymore! + - changed internal methodnames to _methodname + - changed sendbuffer + Now it uses configurable senddelay, instead of static 2 messages + per second (send flood protection). + - changed TYPEs + All TYPE_* are now bitwise constants, register_actionhandler() can now + react to more than one message type. + - added TYPE_ACTION for those common /me messages. + - added timeevents Added method register_timehandler() + unregister_timeid() and reordertimehandler(). Those timehandler + can be used to call methods in specified intervalls, e.g. for + timeevents. Added needed class CphpSmartIRCclass_timehandler. + - moved all IRC related defines to defines.inc.php. + - changed if() elseif() structures where possible to switch() for + clearer/faster code. + - added more debug messages for actionhandler. + - added unregister_actionhandler() and unregister_actionid() method. + Also added needed reorderactionhandler(), which is called after an + unregister methods was called. + - added $data->channel to actionhandler callback. + +* defines.inc.php: + - initial import. + - now all IRC related defines are now in this file instead of + phpSmartIRCclass.inc.php. + +* DOCUMENTATION: + - updated/added methods description + +* example.php: + - changed user function parameter to new style ( &$irc and &$data ). + - added TYPE_NOTICE to query_test example. + +v0.3.2 +------ +* phpSmartIRCclass.inc.php: + - Replaced all quotes by single quote where possible for speedup. + - Added _disconnecttime for doing a clean IRC quit. + - Added Zend IDE style documentation for parameter variables types + and method descriptions. + - Spaces in nickname and username will be automaticly removed. + - Nicknamecollisions are automaticly detected and nickname will be + changed to nickname with 3 random numbers. + - New method nicknameuse(). + - Fixed a serious fsock bug. + - Added new type TYPE_ERROR. + - Fixed wrong usage of & when calling methods with params that are + called by reference. + - Fixed a debug message "DEBUG: disconnected", now it will only + occur when debug mode is enabled. + - listen_for() will now do a quickdisconnect, for a big speedup. + - Changed logging system, now with debug levels, default is + DEBUG_NOTICE. + - Added benchmark system, now its possible to time things for doing + optimizations. + - New methods: benchmark(), benchmarktstart(), benchmarkend() + and show_benchmark() for the benchmark system + - Added microint(), for getting the microtime as float, needed for + the benchmarks. + - Added a couple of log() calls, for different debug levels. + - fsockets now runs in non blocking mode, because of broken? + getstatus for fsockets. + - Added mode() method, for chaning modes of a user or channel. + - Added op() and deop() method. Added ban() and unban() method + (thx for diff file to Peter Petermann). + +* DOCUMENTATION: + - added documentation for new logging system + - added the whole DEBUG_* list + +* HOWTO: + - changed parameter description for debug() + +* example.php: + - replaced all quotes by singlequotes where possible. + - fixed wrong usage of message() + +* example2.php: + - replaced all quotes by singlquotes where possible. + - added benchmark test to the example + +v0.3.0 +----- +* phpSmartIRCclass.inc.php: + - added "Ping? Pong!" log message for debugging + - added real linux/windows syslog logging + to setlogdestination(). + - new method listen_for() makes it possible + to show irc related information on a homepage, like how many users + on a channel are. + +* HOWTO: + - added how to run/call the selfwritten bot + +* DOCUMENTATION: + - added (missing) explaination for new methods + +* example2.php: + - new examplefile with the new listen_for() method + +v0.2.6 +------ +* phpSmartIRCclass.inc.php: + - phpSmartIRCclass.inc renamed to + phpSmartIRCclass.inc.php because of security reasons + - changed function_exists() to get_loaded_extensions() for + checking if the PHP build has real socket support + - log() changed to create Linux style formated logs + - new methods for logging (daemon style) + log() for add log entries setlogdestination() can be STDOUT or FILE + setlogfile() sets the file + - changed received data processing in rawreceive() + +* HOWTO: + - added a mini howto for using the class + +* DOCUMENTATION: + - added class documentation of the project + +* CREDITS: + - added credits file + +v0.2.5 +------ +- improved socket handling +- bufferedsend fix +- new version number system +- cpu usage reduced +- added changelog file diff --git a/lib/Net_SmartIRC/CREDITS b/lib/Net_SmartIRC/CREDITS new file mode 100644 index 000000000..532adbbeb --- /dev/null +++ b/lib/Net_SmartIRC/CREDITS @@ -0,0 +1,65 @@ +/** + * $Id$ + * $Revision$ + * $Author$ + * $Date$ + */ + +This is the creditslist for SmartIRC + +The fields are: +(N) name +(E) email +(W) web-address +(P) PGP key ID and fingerprint +(D) description +(S) snail-mail address +--------------------------- + +N: Mirco 'meebey' Bauer +E: mail@meebey.net +E: meebey@php.net +W: www.meebey.net +P: 5051C9B9 / EF69 07A4 51AD 689E CF0C 767F CD9C 4C1A 5051 C9B9 +D: Project Maintainer +S: Kroonhorst 42 +S: 22549 Hamburg +S: Germany + +N: Garrett Whitehorn +W: http://garrettw.net/ +D: Project Maintainer as of 2014/02/04 + +N: Peter Petermann +E: webmaster@cyberfly.net +W: www.cyberfly.net +D: ban/unban diffs + +N: Andreas Streichardt +E: mop@spaceregents.de +W: www.spaceregents.de +D: several hints for bugfixes +D: some patchfiles + +N: Joern Heissler +E: joern@heissler.de +W: http://wulf.eu.org/ +P: 57C76B66 / 6333 346F D7F4 928D 02B0 FDBF B398 EBC6 57C7 6B66 +D: Quality Asurance (QA) +D: high improved concept for socket_select() handling +S: Willinghusener Weg 100 +S: 21509 Glinde +S: Germany + +N: Jani Taskinen +E: sniper@php.net +D: fixed several bugs + +N: Ronald Hummelink +E: ronaldhummelink@users.sourceforge.net +D: reconnect delay patch (sf.net patch #883820) +D: autoretry patch (sf.net patch #883821) + +N: Anatoly Techtonik +E: techtonik@users.sourceforge.net +D: load socket extension patch (sf.net patch #911993) diff --git a/lib/Net_SmartIRC/FEATURES b/lib/Net_SmartIRC/FEATURES new file mode 100644 index 000000000..10ad3d8ab --- /dev/null +++ b/lib/Net_SmartIRC/FEATURES @@ -0,0 +1,61 @@ +/** + * $Id$ + * $Revision$ + * $Author$ + * $Date$ + */ + +Full featurelist of Net_SmartIRC +------------------------------------- +- full object-oriented programmed +- every received IRC message is parsed into an object + (containing the following info: from, nick, ident, host, channel, message, type, rawmessage) +- actionhandler for the API (on different types of messages [channel/notice/query/kick/join..], callbacks can be registered) +- messagehandler for the API (class-based messagehandling using IRC reply codes) +- time events (callbacks to methods in intervals) +- send/receive flood protection +- detects and changes nickname on nickname collisions +- auto-reconnect if connection is lost +- auto-retry for initially connecting to IRC servers +- debugging/logging system with log levels (destination can be file, stdout, syslog or browserout) +- supports fsocks and PHP socket extension +- supports PHP as old as 4.4.4 (but not for much longer) +- send buffer with a queue that has 3 priority levels (high, medium, low) plus a bypass level (critical) +- channel syncing (tracking of users/modes/topic etc in objects) +- user syncing (tracking the user in channels, nick/ident/host/realname/server/hopcount in objects) +- when channel syncing is activated, the following functions are available: + isJoined + isFounder + isAdmin + isOpped + isHopped + isVoiced + isBanned +- on reconnect all joined channels will be rejoined, even when keys are used +- own CTCP version reply can be set +- IRC commands: + pass + op + deop + voice + devoice + ban + unban + join + part + action + message + notice + query + ctcp + mode + topic + nick + invite + list + names + kick + who + whois + whowas + quit diff --git a/lib/Net_SmartIRC/LICENSE b/lib/Net_SmartIRC/LICENSE new file mode 100644 index 000000000..71a4e3cfa --- /dev/null +++ b/lib/Net_SmartIRC/LICENSE @@ -0,0 +1,508 @@ +/** + * $Id$ + * $Revision$ + * $Author$ + * $Date$ + */ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + <one line to give the library's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + <signature of Ty Coon>, 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! diff --git a/lib/Net_SmartIRC/Net/SmartIRC.php b/lib/Net_SmartIRC/Net/SmartIRC.php new file mode 100644 index 000000000..5f5c4e3a0 --- /dev/null +++ b/lib/Net_SmartIRC/Net/SmartIRC.php @@ -0,0 +1,3281 @@ +<?php +/** + * $Id$ + * $Revision$ + * $Author$ + * $Date$ + * + * Net_SmartIRC + * This is a PHP class for communication with IRC networks, + * which conforms to the RFC 2812 (IRC protocol). + * It's an API that handles all IRC protocol messages. + * This class is designed for creating IRC bots, chats and showing irc related + * info on webpages. + * + * Documentation, a HOWTO, and examples are included in SmartIRC. + * + * Here you will find a service bot which I am also developing + * <http://cvs.meebey.net/atbs> and <http://cvs.meebey.net/phpbitch> + * Latest versions of Net_SmartIRC you will find on the project homepage + * or get it through PEAR since SmartIRC is an official PEAR package. + * See <http://pear.php.net/Net_SmartIRC>. + * + * Official Project Homepage: <http://sf.net/projects/phpsmartirc> + * + * Net_SmartIRC conforms to RFC 2812 (Internet Relay Chat: Client Protocol) + * + * Copyright (c) 2002-2005 Mirco Bauer <meebey@meebey.net> <http://www.meebey.net> + * + * Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ +// ------- PHP code ---------- +require_once 'SmartIRC/defines.php'; +define('SMARTIRC_VERSION', '1.1.0-dev ($Revision$)'); +define('SMARTIRC_VERSIONSTRING', 'Net_SmartIRC '.SMARTIRC_VERSION); + +/** + * main SmartIRC class + * + * @package Net_SmartIRC + * @version 0.6.0-dev + * @author Mirco 'meebey' Bauer <mail@meebey.net> + * @access public + */ +class Net_SmartIRC_base +{ + /** + * @var resource + * @access private + */ + var $_socket; + + /** + * @var string + * @access private + */ + var $_address; + + /** + * @var integer + * @access private + */ + var $_port; + + /** + * @var string + * @access private + */ + var $_bindaddress = null; + + /** + * @var integer + * @access private + */ + var $_bindport = 0; + + /** + * @var string + * @access private + */ + var $_nick; + + /** + * @var string + * @access private + */ + var $_username; + + /** + * @var string + * @access private + */ + var $_realname; + + /** + * @var string + * @access private + */ + var $_usermode; + + /** + * @var string + * @access private + */ + var $_password; + + /** + * @var array + * @access private + */ + var $_performs = array(); + + /** + * @var boolean + * @access private + */ + var $_state = false; + + /** + * @var array + * @access private + */ + var $_actionhandler = array(); + + /** + * @var array + * @access private + */ + var $_timehandler = array(); + + /** + * @var integer + * @access private + */ + var $_debug = SMARTIRC_DEBUG_NOTICE; + + /** + * @var array + * @access private + */ + var $_messagebuffer = array(); + + /** + * @var integer + * @access private + */ + var $_messagebuffersize; + + /** + * @var boolean + * @access private + */ + var $_usesockets = false; + + /** + * @var integer + * @access private + */ + var $_receivedelay = 100; + + /** + * @var integer + * @access private + */ + var $_senddelay = 250; + + /** + * @var integer + * @access private + */ + var $_logdestination = SMARTIRC_STDOUT; + + /** + * @var resource + * @access private + */ + var $_logfilefp = 0; + + /** + * @var string + * @access private + */ + var $_logfile = 'Net_SmartIRC.log'; + + /** + * @var integer + * @access private + */ + var $_disconnecttime = 1000; + + /** + * @var boolean + * @access private + */ + var $_loggedin = false; + + /** + * @var boolean + * @access private + */ + var $_benchmark = false; + + /** + * @var integer + * @access private + */ + var $_benchmark_starttime; + + /** + * @var integer + * @access private + */ + var $_benchmark_stoptime; + + /** + * @var integer + * @access private + */ + var $_actionhandlerid = 0; + + /** + * @var integer + * @access private + */ + var $_timehandlerid = 0; + + /** + * @var array + * @access private + */ + var $_motd = array(); + + /** + * @var array + * @access private + */ + var $_channels = array(); + + /** + * @var boolean + * @access private + */ + var $_channelsyncing = false; + + /** + * @var array + * @access private + */ + var $_users = array(); + + /** + * @var boolean + * @access private + */ + var $_usersyncing = false; + + /** + * Stores the path to the modules that can be loaded. + * + * @var string + * @access private + */ + var $_modulepath = ''; + + /** + * Stores all objects of the modules. + * + * @var string + * @access private + */ + var $_modules = array(); + + /** + * @var string + * @access private + */ + var $_ctcpversion; + + /** + * @var mixed + * @access private + */ + var $_mintimer = false; + + /** + * @var integer + * @access private + */ + var $_maxtimer = 300000; + + /** + * @var integer + * @access private + */ + var $_txtimeout = 300; + + /** + * @var integer + * @access private + */ + var $_rxtimeout = 300; + + /** + * @var integer + * @access private + */ + var $_selecttimeout; + + /** + * @var integer + * @access private + */ + var $_lastrx; + + /** + * @var integer + * @access private + */ + var $_lasttx; + + /** + * @var boolean + * @access private + */ + var $_autoreconnect = false; + + /** + * @var integer + * @access private + */ + var $_reconnectdelay = 10000; + + /** + * @var boolean + * @access private + */ + var $_autoretry = false; + + /** + * @var integer + * @access private + */ + var $_autoretrymax = 5; + + /** + * @var integer + * @access private + */ + var $_autoretrycount = 0; + + /** + * @var boolean + * @access private + */ + var $_connectionerror = false; + + /** + * @var boolean + * @access private + */ + var $_runasdaemon = false; + + + /** + * All IRC replycodes, the index is the replycode name. + * + * @see $SMARTIRC_replycodes + * @var array + * @access public + */ + var $replycodes; + + /** + * All numeric IRC replycodes, the index is the numeric replycode. + * + * @see $SMARTIRC_nreplycodes + * @var array + * @access public + */ + var $nreplycodes; + + /** + * Stores all channels in this array where we are joined, works only if channelsyncing is activated. + * Eg. for accessing a user, use it like this: (in this example the SmartIRC object is stored in $irc) + * $irc->channel['#test']->users['meebey']->nick; + * + * @see setChannelSyncing() + * @see Net_SmartIRC_channel + * @see Net_SmartIRC_channeluser + * @var array + * @access public + */ + var $channel; + + /** + * Stores all users that had/have contact with us (channel/query/notice etc.), works only if usersyncing is activated. + * Eg. for accessing a user, use it like this: (in this example the SmartIRC object is stored in $irc) + * $irc->user['meebey']->host; + * + * @see setUserSyncing() + * @see Net_SmartIRC_ircuser + * @var array + * @access public + */ + var $user; + + /** + * Constructor. Initiates the messagebuffer and "links" the replycodes from + * global into properties. Also some PHP runtime settings are configured. + * + * @access public + */ + function __construct() + { + // precheck + $this->_checkPHPVersion(); + + ob_implicit_flush(true); + @set_time_limit(0); + $this->_messagebuffer[SMARTIRC_CRITICAL] = array(); + $this->_messagebuffer[SMARTIRC_HIGH] = array(); + $this->_messagebuffer[SMARTIRC_MEDIUM] = array(); + $this->_messagebuffer[SMARTIRC_LOW] = array(); + + $this->replycodes = &$GLOBALS['SMARTIRC_replycodes']; + $this->nreplycodes = &$GLOBALS['SMARTIRC_nreplycodes']; + + // hack till PHP allows (PHP5) $object->somemethod($param)->memberofobject + $this->channel = &$this->_channels; + // another hack + $this->user = &$this->_users; + + if (isset($_SERVER['REQUEST_METHOD'])) { + // the script is called from a browser, lets set default log destination + // to SMARTIRC_BROWSEROUT (makes browser friendly output) + $this->setLogdestination(SMARTIRC_BROWSEROUT); + } + } + + /** + * Enables/disables the usage of real sockets. + * + * Enables/disables the usage of real sockets instead of fsocks + * (works only if your PHP build has loaded the PHP socket extension) + * Default: false + * + * @param bool $boolean + * @return void + * @access public + */ + function setUseSockets($boolean) + { + if ($boolean === true) { + if (@extension_loaded('sockets')) { + $this->_usesockets = true; + } else { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: socket extension not loaded, trying to load it...', __FILE__, __LINE__); + + if (strtoupper(substr(PHP_OS, 0,3) == 'WIN')) { + $load_status = @dl('php_sockets.dll'); + } else { + $load_status = @dl('sockets.so'); + } + + if ($load_status) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: socket extension succesfully loaded', __FILE__, __LINE__); + $this->_usesockets = true; + } else { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: couldn\'t load the socket extension', __FILE__, __LINE__); + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: your PHP build doesn\'t support real sockets, will use fsocks instead', __FILE__, __LINE__); + $this->_usesockets = false; + } + } + } else { + $this->_usesockets = false; + } + } + + /** + * Sets an IP address (and optionally, a port) to bind the socket to. + * + * Limits the bot to claiming only one of the machine's IPs as its home. + * Only works with setUseSockets(TRUE). Call with no parameters to unbind. + * + * @param string $addr + * @return bool + * @access public + */ + function setBindAddress($addr=null,$port=0) + { + if ($this->_usesockets) { + $this->bindaddress = $addr; + $this->bindport = $port; + } + return $this->_usesockets; + } + + /** + * Sets the level of debug messages. + * + * Sets the debug level (bitwise), useful for testing/developing your code. + * Here the list of all possible debug levels: + * SMARTIRC_DEBUG_NONE + * SMARTIRC_DEBUG_NOTICE + * SMARTIRC_DEBUG_CONNECTION + * SMARTIRC_DEBUG_SOCKET + * SMARTIRC_DEBUG_IRCMESSAGES + * SMARTIRC_DEBUG_MESSAGETYPES + * SMARTIRC_DEBUG_ACTIONHANDLER + * SMARTIRC_DEBUG_TIMEHANDLER + * SMARTIRC_DEBUG_MESSAGEHANDLER + * SMARTIRC_DEBUG_CHANNELSYNCING + * SMARTIRC_DEBUG_MODULES + * SMARTIRC_DEBUG_USERSYNCING + * SMARTIRC_DEBUG_ALL + * + * Default: SMARTIRC_DEBUG_NOTICE + * + * @see DOCUMENTATION + * @see SMARTIRC_DEBUG_NOTICE + * @param integer $level + * @return void + * @access public + */ + function setDebug($level) + { + $this->_debug = $level; + } + + /** + * Enables/disables the benchmark engine. + * + * @param boolean $boolean + * @return void + * @access public + */ + function setBenchmark($boolean) + { + if (is_bool($boolean)) { + $this->_benchmark = $boolean; + } else { + $this->_benchmark = false; + } + } + + /** + * Deprecated, use setChannelSyncing() instead! + * + * @deprecated + * @param boolean $boolean + * @return void + * @access public + */ + function setChannelSynching($boolean) + { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: you are using setChannelSynching() which is a deprecated method, use setChannelSyncing() instead!', __FILE__, __LINE__); + $this->setChannelSyncing($boolean); + } + + /** + * Enables/disables channel syncing. + * + * Channel syncing means, all users on all channel we are joined are tracked in the + * channel array. This makes it very handy for botcoding. + * + * @param boolean $boolean + * @return void + * @access public + */ + function setChannelSyncing($boolean) + { + if (is_bool($boolean)) { + $this->_channelsyncing = $boolean; + } else { + $this->_channelsyncing = false; + } + + if ($this->_channelsyncing == true) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: Channel syncing enabled', __FILE__, __LINE__); + } else { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: Channel syncing disabled', __FILE__, __LINE__); + } + } + + /** + * Enables/disables user syncing. + * + * User syncing means, all users we have or had contact with through channel, query or + * notice are tracked in the $irc->user array. This is very handy for botcoding. + * + * @param boolean $boolean + * @return void + * @access public + */ + function setUserSyncing($boolean) + { + if (is_bool($boolean)) { + $this->_usersyncing = $boolean; + } else { + $this->_usersyncing = false; + } + + if ($this->_usersyncing == true) { + $this->log(SMARTIRC_DEBUG_USERSYNCING, 'DEBUG_USERSYNCING: User syncing enabled', __FILE__, __LINE__); + } else { + $this->log(SMARTIRC_DEBUG_USERSYNCING, 'DEBUG_USERSYNCING: User syncing disabled', __FILE__, __LINE__); + } + } + + /** + * Sets the CTCP version reply string. + * + * @param string $versionstring + * @return void + * @access public + */ + function setCtcpVersion($versionstring) + { + $this->_ctcpversion = $versionstring; + } + + /** + * Sets the destination of all log messages. + * + * Sets the destination of log messages. + * $type can be: + * SMARTIRC_FILE for saving the log into a file + * SMARTIRC_STDOUT for echoing the log to stdout + * SMARTIRC_SYSLOG for sending the log to the syslog + * Default: SMARTIRC_STDOUT + * + * @see SMARTIRC_STDOUT + * @param integer $type must be on of the constants + * @return void + * @access public + */ + function setLogdestination($type) + { + switch ($type) { + case SMARTIRC_FILE: + case SMARTIRC_STDOUT: + case SMARTIRC_SYSLOG: + case SMARTIRC_BROWSEROUT: + case SMARTIRC_NONE: + $this->_logdestination = $type; + break; + default: + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: unknown logdestination type ('.$type.'), will use STDOUT instead', __FILE__, __LINE__); + $this->_logdestination = SMARTIRC_STDOUT; + } + } + + /** + * Sets the file for the log if the destination is set to file. + * + * Sets the logfile, if {@link setLogdestination logdestination} is set to SMARTIRC_FILE. + * This should be only used with full path! + * + * @param string $file + * @return void + * @access public + */ + function setLogfile($file) + { + $this->_logfile = $file; + } + + /** + * Sets the delaytime before closing the socket when disconnect. + * + * @param integer $milliseconds + * @return void + * @access public + */ + function setDisconnecttime($milliseconds) + { + if (is_integer($milliseconds) && $milliseconds >= 100) { + $this->_disconnecttime = $milliseconds; + } else { + $this->_disconnecttime = 100; + } + } + + /** + * Sets the delaytime before attempting reconnect. + * Value of 0 disables the delay entirely. + * + * @param integer $milliseconds + * @return void + * @access public + */ + function setReconnectdelay($milliseconds) + { + if (is_integer($milliseconds)) { + $this->_reconnectdelay = $milliseconds; + } else { + $this->_reconnectdelay = 10000; + } + } + + /** + * Sets the delay for receiving data from the IRC server. + * + * Sets the delaytime between messages that are received, this reduces your CPU load. + * Don't set this too low (min 100ms). + * Default: 100 + * + * @param integer $milliseconds + * @return void + * @access public + */ + function setReceivedelay($milliseconds) + { + if (is_integer($milliseconds) && $milliseconds >= 100) { + $this->_receivedelay = $milliseconds; + } else { + $this->_receivedelay = 100; + } + } + + /** + * Sets the delay for sending data to the IRC server. + * + * Sets the delaytime between messages that are sent, because IRC servers doesn't like floods. + * This will avoid sending your messages too fast to the IRC server. + * Default: 250 + * + * @param integer $milliseconds + * @return void + * @access public + */ + function setSenddelay($milliseconds) + { + if (is_integer($milliseconds)) { + $this->_senddelay = $milliseconds; + } else { + $this->_senddelay = 250; + } + } + + /** + * Enables/disables autoreconnecting. + * + * @param boolean $boolean + * @return void + * @access public + */ + function setAutoReconnect($boolean) + { + if (is_bool($boolean)) { + $this->_autoreconnect = $boolean; + } else { + $this->_autoreconnect = false; + } + } + + /** + * Enables/disables autoretry for connecting to a server. + * + * @param boolean $boolean + * @return void + * @access public + */ + function setAutoRetry($boolean) + { + if (is_bool($boolean)) { + $this->_autoretry = $boolean; + } else { + $this->_autoretry = false; + } + } + + /** + * Sets the maximum number of attempts to connect to a server + * before giving up. + * + * @param integer $autoretrymax + * @return void + * @access public + */ + function setAutoRetryMax($autoretrymax) + { + if (is_integer($autoretrymax)) { + $this->_autoretrymax = $autoretrymax; + } else { + $this->_autoretrymax = 5; + } + } + + /** + * Sets the receive timeout. + * + * If the timeout occurs, the connection will be reinitialized + * Default: 300 seconds + * + * @param integer $seconds + * @return void + * @access public + */ + function setReceiveTimeout($seconds) + { + if (is_integer($seconds)) { + $this->_rxtimeout = $seconds; + } else { + $this->_rxtimeout = 300; + } + } + + /** + * Sets the transmit timeout. + * + * If the timeout occurs, the connection will be reinitialized + * Default: 300 seconds + * + * @param integer $seconds + * @return void + * @access public + */ + function setTransmitTimeout($seconds) + { + if (is_integer($seconds)) { + $this->_txtimeout = $seconds; + } else { + $this->_txtimeout = 300; + } + } + + /** + * Sets the paths for the modules. + * + * @param integer $path + * @return void + * @access public + */ + function setModulepath($path) + { + $this->_modulepath = $path; + } + + /** + * Sets wheter the script should be run as a daemon or not + * ( actually disables/enables ignore_user_abort() ) + * + * @param boolean $boolean + * @return void + * @access public + */ + function setRunAsDaemon($boolean) + { + if ($boolean === true) { + $this->_runasdaemon = true; + ignore_user_abort(true); + set_time_limit(0); + } else { + $this->_runasdaemon = false; + } + } + + /** + * Starts the benchmark (sets the counters). + * + * @return void + * @access public + */ + function startBenchmark() + { + $this->_benchmark_starttime = $this->_microint(); + $this->log(SMARTIRC_DEBUG_NOTICE, 'benchmark started', __FILE__, __LINE__); + } + + /** + * Stops the benchmark and displays the result. + * + * @return void + * @access public + */ + function stopBenchmark() + { + $this->_benchmark_stoptime = $this->_microint(); + $this->log(SMARTIRC_DEBUG_NOTICE, 'benchmark stopped', __FILE__, __LINE__); + + if ($this->_benchmark) { + $this->showBenchmark(); + } + } + + /** + * Shows the benchmark result. + * + * @return void + * @access public + */ + function showBenchmark() + { + $this->log(SMARTIRC_DEBUG_NOTICE, 'benchmark time: '.((float)$this->_benchmark_stoptime-(float)$this->_benchmark_starttime), __FILE__, __LINE__); + } + + /** + * Adds an entry to the log. + * + * Adds an entry to the log with Linux style log format. + * Possible $level constants (can also be combined with "|"s) + * SMARTIRC_DEBUG_NONE + * SMARTIRC_DEBUG_NOTICE + * SMARTIRC_DEBUG_CONNECTION + * SMARTIRC_DEBUG_SOCKET + * SMARTIRC_DEBUG_IRCMESSAGES + * SMARTIRC_DEBUG_MESSAGETYPES + * SMARTIRC_DEBUG_ACTIONHANDLER + * SMARTIRC_DEBUG_TIMEHANDLER + * SMARTIRC_DEBUG_MESSAGEHANDLER + * SMARTIRC_DEBUG_CHANNELSYNCING + * SMARTIRC_DEBUG_MODULES + * SMARTIRC_DEBUG_USERSYNCING + * SMARTIRC_DEBUG_ALL + * + * @see SMARTIRC_DEBUG_NOTICE + * @param integer $level bit constants (SMARTIRC_DEBUG_*) + * @param string $entry the new log entry + * @return void + * @access public + */ + function log($level, $entry, $file = null, $line = null) + { + // prechecks + if (!(is_integer($level)) || + !($level & SMARTIRC_DEBUG_ALL)) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: invalid log level passed to log() ('.$level.')', __FILE__, __LINE__); + return; + } + + if (!($level & $this->_debug) || + ($this->_logdestination == SMARTIRC_NONE)) { + return; + } + + if (substr($entry, -1) != "\n") { + $entry .= "\n"; + } + + if ($file !== null && + $line !== null) { + $file = basename($file); + $entry = $file.'('.$line.') '.$entry; + } else { + $entry = 'unknown(0) '.$entry; + } + + $formatedentry = date('M d H:i:s ').$entry; + switch ($this->_logdestination) { + case SMARTIRC_STDOUT: + echo $formatedentry; + flush(); + break; + case SMARTIRC_BROWSEROUT: + echo '<pre>'.htmlentities($formatedentry).'</pre>'; + break; + case SMARTIRC_FILE: + if (!is_resource($this->_logfilefp)) { + if ($this->_logfilefp === null) { + // we reconncted and don't want to destroy the old log entries + $this->_logfilefp = fopen($this->_logfile,'a'); + } else { + $this->_logfilefp = fopen($this->_logfile,'w'); + } + } + fwrite($this->_logfilefp, $formatedentry); + fflush($this->_logfilefp); + break; + case SMARTIRC_SYSLOG: + if (version_compare(PHP_VERSION, '5.3.0', '<')) { + define_syslog_variables(); + } + if (!is_int($this->_logfilefp)) { + $this->_logfilefp = openlog('Net_SmartIRC', LOG_NDELAY, LOG_DAEMON); + } + syslog(LOG_INFO, $entry); + break; + } + } + + /** + * Returns the full motd. + * + * @return array + * @access public + */ + function getMotd() + { + return $this->_motd; + } + + /** + * Returns the usermode. + * + * @return string + * @access public + */ + function getUsermode() + { + return $this->_usermode; + } + + /** + * Returns a reference to the channel object of the specified channelname. + * + * @param string $channelname + * @return object + * @access public + */ + function &getChannel($channelname) + { + if ($this->_channelsyncing != true) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: getChannel() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); + return false; + } + + if ($this->isJoined($channelname)) { + return $this->_channels[strtolower($channelname)]; + } else { + return false; + } + } + + /** + * Returns a reference to the user object for the specified username and channelname. + * + * @param string $channelname + * @param string $username + * @return object + * @access public + */ + function &getUser($channelname, $username) + { + if ($this->_channelsyncing != true) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: getUser() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); + return false; + } + + if ($this->isJoined($channelname, $username)) { + return $this->_channels[strtolower($channelname)]->users[strtolower($username)]; + } else { + return false; + } + } + + /** + * Creates the sockets and connects to the IRC server on the given port. + * + * @param string $address + * @param integer $port + * @return boolean + * @access public + */ + function connect($address, $port) + { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connecting', __FILE__, __LINE__); + $this->_address = $address; + $this->_port = $port; + + if ($this->_usesockets == true) { + $this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_SOCKET: using real sockets', __FILE__, __LINE__); + $this->_socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); + if ($this->_bindaddress !== null) { + if (socket_bind($this->_socket, $this->_bindaddress, $this->_bindport)) { + $this->log(SMARTIRC_DEBUG_SOCKET, + 'DEBUG_SOCKET: bound to '.$this->_bindaddress.':' + .$this->_bindport, __FILE__, __LINE__); + } else { + $errno = socket_last_error($this->_socket); + $error_msg = 'ERROR: Unable to bind '.$this->_bindaddress.':' + .$this->_bindport.' reason: '.socket_strerror($errno) + .' ('.$errno.')'; + $this->log(SMARTIRC_DEBUG_NOTICE, + 'DEBUG_NOTICE: '.$error_msg, __FILE__, __LINE__); + echo $error_msg . PHP_EOL; + return false; + } + } + $result = @socket_connect($this->_socket, $this->_address, $this->_port); + } else { + $this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_SOCKET: using fsockets', __FILE__, __LINE__); + $result = fsockopen($this->_address, $this->_port, $errno, $errstr); + } + + if ($result === false) { + if ($this->_usesockets == true) { + $error = socket_strerror(socket_last_error($this->_socket)); + } else { + $error = $errstr.' ('.$errno.')'; + } + + $error_msg = 'couldn\'t connect to "'.$address.'" reason: "'.$error.'"'; + $this->log(SMARTIRC_DEBUG_NOTICE, 'DEBUG_NOTICE: '.$error_msg, __FILE__, __LINE__); + // TODO! needs to be return value + //$this->throwError($error_msg); // This returns, preventing reconnect. + + if (($this->_autoretry == true) && + ($this->_autoretrycount < $this->_autoretrymax)) { + echo 'ERROR connecting to (' . + $address . + ':' . + $port . + ') error: (' . + $error . + ') retry (' . + $this->_autoretrycount . + '/' . + $this->_autoretrymax . + '). Sleeping for (' . + $this->_reconnectdelay . + ') ms.' . + PHP_EOL; + $this->_delayReconnect(); + $this->_autoretrycount++; + $this->reconnect(); + } else { + echo 'ERROR connecting to (' . + $address . + ':' . + $port . + ') after (' . + $this->_autoretrymax . + ') retries, error: (' . + $error . + ').' . + PHP_EOL; + return false; + } + } else { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connected', __FILE__, __LINE__); + $this->_autoretrycount = 0; + $this->_connectionerror = false; + + if ($this->_usesockets != true) { + $this->_socket = $result; + $this->log(SMARTIRC_DEBUG_SOCKET, 'DEBUG_SOCKET: activating nonblocking fsocket mode', __FILE__, __LINE__); + stream_set_blocking($this->_socket, 0); + } + } + + $this->_lastrx = time(); + $this->_lasttx = $this->_lastrx; + $this->_updatestate(); + + return $result !== false; + } + + /** + * Disconnects from the IRC server nicely with a QUIT or just destroys the socket. + * + * Disconnects from the IRC server in the given quickness mode. + * $quickdisconnect: + * true, just close the socket + * false, send QUIT and wait {@link $_disconnectime $_disconnectime} before closing the socket + * + * @param boolean $quickdisconnect default: false + * @return boolean + * @access public + */ + function disconnect($quickdisconnect = false) + { + if ($this->_state() == SMARTIRC_STATE_CONNECTED) { + if ($quickdisconnect == false) { + $this->_send('QUIT', SMARTIRC_CRITICAL); + usleep($this->_disconnecttime*1000); + } + + if ($this->_usesockets == true) { + @socket_shutdown($this->_socket); + @socket_close($this->_socket); + } else { + fclose($this->_socket); + } + + $this->_updatestate(); + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: disconnected', __FILE__, __LINE__); + } else { + return false; + } + + if ($this->_channelsyncing == true) { + // let's clean our channel array + $this->_channels = array(); + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: cleaned channel array', __FILE__, __LINE__); + } + + if ($this->_usersyncing == true) { + // let's clean our user array + $this->_users = array(); + $this->log(SMARTIRC_DEBUG_USERSYNCING, 'DEBUG_USERSYNCING: cleaned user array', __FILE__, __LINE__); + } + + if ($this->_logdestination == SMARTIRC_FILE) { + fclose($this->_logfilefp); + $this->_logfilefp = null; + } else if ($this->_logdestination == SMARTIRC_SYSLOG) { + closelog(); + } + + return true; + } + + /** + * Reconnects to the IRC server with the same login info, + * it also rejoins the channels + * + * @return void + * @access public + */ + function reconnect() + { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: reconnecting...', __FILE__, __LINE__); + + // remember in which channels we are joined + $channels = array(); + foreach ($this->_channels as $value) { + if (empty($value->key)) { + $channels[] = array('name' => $value->name); + } else { + $channels[] = array('name' => $value->name, 'key' => $value->key); + } + } + + $this->disconnect(true); + $this->connect($this->_address, $this->_port); + $this->login($this->_nick, $this->_realname, $this->_usermode, $this->_username, $this->_password); + + // rejoin the channels + foreach ($channels as $value) { + if (isset($value['key'])) { + $this->join($value['name'], $value['key']); + } else { + $this->join($value['name']); + } + } + } + + /** + * login and register nickname on the IRC network + * + * Registers the nickname and user information on the IRC network. + * + * @param string $nick + * @param string $realname + * @param integer $usermode + * @param string $username + * @param string $password + * @return void + * @access public + */ + function login($nick, $realname, $usermode = 0, $username = null, $password = null) + { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: logging in', __FILE__, __LINE__); + + $this->_nick = str_replace(' ', '', $nick); + $this->_realname = $realname; + + if ($username !== null) { + $this->_username = str_replace(' ', '', $username); + } else { + $this->_username = str_replace(' ', '', exec('whoami')); + } + + if ($password !== null) { + $this->_password = $password; + $this->_send('PASS '.$this->_password, SMARTIRC_CRITICAL); + } + + if (!is_numeric($usermode)) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'DEBUG_NOTICE: login() usermode ('.$usermode.') is not valid, will use 0 instead', __FILE__, __LINE__); + $usermode = 0; + } + + $this->_send('NICK '.$this->_nick, SMARTIRC_CRITICAL); + $this->_send('USER '.$this->_username.' '.$usermode.' '.SMARTIRC_UNUSED.' :'.$this->_realname, SMARTIRC_CRITICAL); + + if (count($this->_performs)) { + // if we have extra commands to send, do it now + foreach($this->_performs as $command) { + $this->_send($command, SMARTIRC_HIGH); + } + // if we sent "ns auth" commands, we may need to resend our nick + $this->_send('NICK '.$this->_nick, SMARTIRC_HIGH); + } + } + + // </IRC methods> + + /** + * adds a command to the list of commands to be sent after login() info + * + * @param string $cmd the command to add to the perform list + * @access public + */ + function perform($cmd) + { + $this->_performs[] = $cmd; + } + + /** + * checks if the passed nickname is our own nickname + * + * @param string $nickname + * @return boolean + * @access public + */ + function isMe($nickname) + { + if ($nickname == $this->_nick) { + return true; + } else { + return false; + } + } + + /** + * checks if we or the given user is joined to the specified channel and returns the result + * ChannelSyncing is required for this. + * + * @see setChannelSyncing + * @param string $channel + * @param string $nickname + * @return boolean + * @access public + */ + function isJoined($channel, $nickname = null) + { + if ($this->_channelsyncing != true) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isJoined() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); + return false; + } + + if ($nickname === null) { + $nickname = $this->_nick; + } + + if (isset($this->_channels[strtolower($channel)]->users[strtolower($nickname)])) { + return true; + } + + return false; + } + + /** + * Checks if we or the given user is founder on the specified channel and returns the result. + * ChannelSyncing is required for this. + * + * @see setChannelSyncing + * @param string $channel + * @param string $nickname + * @return boolean + * @access public + */ + function isFounder($channel, $nickname = null) + { + if ($this->_channelsyncing != true) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isFounder() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); + return false; + } + + if ($nickname === null) { + $nickname = $this->_nick; + } + + if ($this->isJoined($channel, $nickname)) { + if ($this->_channels[strtolower($channel)]->users[strtolower($nickname)]->founder) { + return true; + } + } + + return false; + } + + /** + * Checks if we or the given user is admin on the specified channel and returns the result. + * ChannelSyncing is required for this. + * + * @see setChannelSyncing + * @param string $channel + * @param string $nickname + * @return boolean + * @access public + */ + function isAdmin($channel, $nickname = null) + { + if ($this->_channelsyncing != true) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isAdmin() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); + return false; + } + + if ($nickname === null) { + $nickname = $this->_nick; + } + + if ($this->isJoined($channel, $nickname)) { + if ($this->_channels[strtolower($channel)]->users[strtolower($nickname)]->admin) { + return true; + } + } + + return false; + } + + /** + * Checks if we or the given user is opped on the specified channel and returns the result. + * ChannelSyncing is required for this. + * + * @see setChannelSyncing + * @param string $channel + * @param string $nickname + * @return boolean + * @access public + */ + function isOpped($channel, $nickname = null) + { + if ($this->_channelsyncing != true) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isOpped() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); + return false; + } + + if ($nickname === null) { + $nickname = $this->_nick; + } + + if ($this->isJoined($channel, $nickname)) { + if ($this->_channels[strtolower($channel)]->users[strtolower($nickname)]->op) { + return true; + } + } + + return false; + } + + /** + * Checks if we or the given user is hopped on the specified channel and returns the result. + * ChannelSyncing is required for this. + * + * @see setChannelSyncing + * @param string $channel + * @param string $nickname + * @return boolean + * @access public + */ + function isHopped($channel, $nickname = null) + { + if ($this->_channelsyncing != true) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isHopped() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); + return false; + } + + if ($nickname === null) { + $nickname = $this->_nick; + } + + if ($this->isJoined($channel, $nickname)) { + if ($this->_channels[strtolower($channel)]->users[strtolower($nickname)]->hop) { + return true; + } + } + + return false; + } + + /** + * Checks if we or the given user is voiced on the specified channel and returns the result. + * ChannelSyncing is required for this. + * + * @see setChannelSyncing + * @param string $channel + * @param string $nickname + * @return boolean + * @access public + */ + function isVoiced($channel, $nickname = null) + { + if ($this->_channelsyncing != true) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isVoiced() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); + return false; + } + + if ($nickname === null) { + $nickname = $this->_nick; + } + + if ($this->isJoined($channel, $nickname)) { + if ($this->_channels[strtolower($channel)]->users[strtolower($nickname)]->voice) { + return true; + } + } + + return false; + } + + /** + * Checks if the hostmask is on the specified channel banned and returns the result. + * ChannelSyncing is required for this. + * + * @see setChannelSyncing + * @param string $channel + * @param string $hostmask + * @return boolean + * @access public + */ + function isBanned($channel, $hostmask) + { + if ($this->_channelsyncing != true) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: isBanned() is called and the required Channel Syncing is not activated!', __FILE__, __LINE__); + return false; + } + + if ($this->isJoined($channel)) { + $result = array_search($hostmask, $this->_channels[strtolower($channel)]->bans); + + if ($result !== false) { + return true; + } + } + + return false; + } + + /** + * goes into receive mode + * + * Goes into receive and idle mode. Only call this if you want to "spawn" the bot. + * No further lines of PHP code will be processed after this call, only the bot methods! + * + * @return boolean + * @access public + */ + function listen() + { + while ($this->_state() == SMARTIRC_STATE_CONNECTED) { + $this->listenOnce(); + } + + return false; + } + + /** + * goes into receive mode _only_ for one pass + * + * Goes into receive mode. It will return when one pass is complete. + * Use this when you want to connect to multiple IRC servers. + * + * @return boolean + * @access public + */ + function listenOnce() + { + if ($this->_state() == SMARTIRC_STATE_CONNECTED) { + $this->_rawreceive(); + if ($this->_connectionerror) { + if ($this->_autoreconnect) { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connection error detected, will reconnect!', __FILE__, __LINE__); + $this->reconnect(); + } else { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connection error detected, will disconnect!', __FILE__, __LINE__); + $this->disconnect(); + } + } + return true; + } else { + return false; + } + } + + /** + * waits for a special message type and puts the answer in $result + * + * Creates a special actionhandler for that given TYPE and returns the answer. + * This will only receive the requested type, immediately quit and disconnect from the IRC server. + * Made for showing IRC statistics on your homepage, or other IRC related information. + * + * @param integer $messagetype see in the documentation 'Message Types' + * @return array answer from the IRC server for this $messagetype + * @access public + */ + function listenFor($messagetype) + { + $listenfor = new Net_SmartIRC_listenfor(); + $this->registerActionhandler($messagetype, '.*', $listenfor, 'handler'); + $this->listen(); + $result = $listenfor->result; + + if (isset($listenfor)) { + unset($listenfor); + } + + return $result; + } + + /** + * registers a new actionhandler and returns the assigned id + * + * Registers an actionhandler in Net_SmartIRC for calling it later. + * The actionhandler id is needed for unregistering the actionhandler. + * + * @see example.php + * @param integer $handlertype bits constants, see in this documentation Message Types + * @param string $regexhandler the message that has to be in the IRC message in regex syntax + * @param object $object a reference to the objects of the method + * @param string $methodname the methodname that will be called when the handler happens + * @return integer assigned actionhandler id + * @access public + */ + function registerActionhandler($handlertype, $regexhandler, &$object, $methodname) + { + // precheck + if (!$this->_isValidType($handlertype)) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: passed invalid handlertype to registerActionhandler()', __FILE__, __LINE__); + return false; + } + + $id = $this->_actionhandlerid++; + $newactionhandler = new Net_SmartIRC_actionhandler(); + + $newactionhandler->id = $id; + $newactionhandler->type = $handlertype; + $newactionhandler->message = $regexhandler; + $newactionhandler->object = &$object; + $newactionhandler->method = $methodname; + + $this->_actionhandler[] = &$newactionhandler; + $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler('.$id.') registered', __FILE__, __LINE__); + return $id; + } + + /** + * unregisters an existing actionhandler + * + * @param integer $handlertype + * @param string $regexhandler + * @param object $object + * @param string $methodname + * @return boolean + * @access public + */ + function unregisterActionhandler($handlertype, $regexhandler, &$object, $methodname) + { + // precheck + if (!$this->_isValidType($handlertype)) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: passed invalid handlertype to unregisterActionhandler()', __FILE__, __LINE__); + return false; + } + + $handler = &$this->_actionhandler; + $handlercount = count($handler); + + for ($i = 0; $i < $handlercount; $i++) { + $handlerobject = &$handler[$i]; + + if ($handlerobject->type == $handlertype && + $handlerobject->message == $regexhandler && + $handlerobject->method == $methodname) { + + $id = $handlerobject->id; + + if (isset($this->_actionhandler[$i])) { + unset($this->_actionhandler[$i]); + } + + $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler('.$id.') unregistered', __FILE__, __LINE__); + $this->_reorderactionhandler(); + return true; + } + } + + $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: could not find actionhandler type: "'.$handlertype.'" message: "'.$regexhandler.'" method: "'.$methodname.'" from object "'.get_class($object).'" _not_ unregistered', __FILE__, __LINE__); + return false; + } + + /** + * unregisters an existing actionhandler via the id + * + * @param integer $id + * @return boolean + * @access public + */ + function unregisterActionid($id) + { + $handler = &$this->_actionhandler; + $handlercount = count($handler); + for ($i = 0; $i < $handlercount; $i++) { + $handlerobject = &$handler[$i]; + + if ($handlerobject->id == $id) { + if (isset($this->_actionhandler[$i])) { + unset($this->_actionhandler[$i]); + } + + $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler('.$id.') unregistered', __FILE__, __LINE__); + $this->_reorderactionhandler(); + return true; + } + } + + $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: could not find actionhandler id: '.$id.' _not_ unregistered', __FILE__, __LINE__); + return false; + } + + /** + * registers a timehandler and returns the assigned id + * + * Registers a timehandler in Net_SmartIRC, which will be called in the specified interval. + * The timehandler id is needed for unregistering the timehandler. + * + * @see example7.php + * @param integer $interval interval time in milliseconds + * @param object $object a reference to the objects of the method + * @param string $methodname the methodname that will be called when the handler happens + * @return integer assigned timehandler id + * @access public + */ + function registerTimehandler($interval, &$object, $methodname) + { + $id = $this->_timehandlerid++; + $newtimehandler = new Net_SmartIRC_timehandler(); + + $newtimehandler->id = $id; + $newtimehandler->interval = $interval; + $newtimehandler->object = &$object; + $newtimehandler->method = $methodname; + $newtimehandler->lastmicrotimestamp = $this->_microint(); + + $this->_timehandler[] = &$newtimehandler; + $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: timehandler('.$id.') registered', __FILE__, __LINE__); + + if (($interval < $this->_mintimer) || ($this->_mintimer == false)) { + $this->_mintimer = $interval; + } + + return $id; + } + + /** + * unregisters an existing timehandler via the id + * + * @see example7.php + * @param integer $id + * @return boolean + * @access public + */ + function unregisterTimeid($id) + { + $handler = &$this->_timehandler; + $handlercount = count($handler); + for ($i = 0; $i < $handlercount; $i++) { + $handlerobject = &$handler[$i]; + + if ($handlerobject->id == $id) { + if (isset($this->_timehandler[$i])) { + unset($this->_timehandler[$i]); + } + + $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: timehandler('.$id.') unregistered', __FILE__, __LINE__); + $this->_reordertimehandler(); + $this->_updatemintimer(); + return true; + } + } + + $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: could not find timehandler id: '.$id.' _not_ unregistered', __FILE__, __LINE__); + return false; + } + + function loadModule($name) + { + // is the module already loaded? + if (in_array($name, $this->_modules)) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING! module with the name "'.$name.'" already loaded!', __FILE__, __LINE__); + return false; + } + + $filename = $this->_modulepath.'/'.$name.'.php'; + if (!file_exists($filename)) { + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: couldn\'t load module "'.$filename.'" file doesn\'t exist', __FILE__, __LINE__); + return false; + } + + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: loading module: "'.$name.'"...', __FILE__, __LINE__); + // pray that there is no parse error, it will kill us! + include_once($filename); + $classname = 'Net_SmartIRC_module_'.$name; + + if (!class_exists($classname)) { + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: class '.$classname.' not found in '.$filename, __FILE__, __LINE__); + return false; + } + + $methods = get_class_methods($classname); + if (!in_array('__construct', $methods) && !in_array('module_init', $methods)) { + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: required method'.$classname.'::__construct not found, aborting...', __FILE__, __LINE__); + return false; + } + + if (!in_array('__destruct', $methods) && !in_array('module_exit', $methods)) { + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: required method'.$classname.'::__destruct not found, aborting...', __FILE__, __LINE__); + return false; + } + + $vars = array_keys(get_class_vars($classname)); + if (!in_array('name', $vars)) { + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: required variable '.$classname.'::name not found, aborting...', __FILE__, __LINE__); + return false; + } + + if (!in_array('description', $vars)) { + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: required variable '.$classname.'::description not found, aborting...', __FILE__, __LINE__); + return false; + } + + if (!in_array('author', $vars)) { + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: required variable '.$classname.'::author not found, aborting...', __FILE__, __LINE__); + return false; + } + + if (!in_array('license', $vars)) { + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: required variable '.$classname.'::license not found, aborting...', __FILE__, __LINE__); + return false; + } + + // looks like the module satisfies us, so instantiate it + if (in_array('module_init', $methods)) { + // we're using an old module_init style module + $module = new $classname; + } else if (func_num_args() == 1) { + // we're using a new __construct style module, which maintains its + // own reference to the $irc client object it's being used on + $module = new $classname($this); + } else { + // we're using new style AND we have args to pass to the constructor + if (func_num_args() == 2) { + // only one arg, so pass it as is + $module = new $classname($this, func_get_arg(1)); + } else { + // multiple args, so pass them in an array + $module = new $classname($this, array_slice(func_get_args(), 1)); + } + } + + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: successfully created' + .' instance of: '.$classname, __FILE__, __LINE__ + ); + + // check for deprecated init function and run it if it exists + if (in_array('module_init', get_class_methods($classname))) { + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: calling ' + .$classname.'::module_init()', __FILE__, __LINE__ + ); + $module->module_init($this); + } + + $this->_modules[$name] = &$module; + + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: successfully loaded' + .' module: '.$name, __FILE__, __LINE__ + ); + return true; + } + + function unloadModule($name) + { + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: unloading module: '.$name.'...', __FILE__, __LINE__); + + $modules_keys = array_keys($this->_modules); + $modulecount = count($modules_keys); + for ($i = 0; $i < $modulecount; $i++) { + $module = &$this->_modules[$modules_keys[$i]]; + $modulename = strtolower(get_class($module)); + + if ($modulename == 'net_smartirc_module_'.$name) { + if (in_array('module_exit', get_class_methods($modulename))) { + $module->module_exit($this); + } + unset($this->_modules[$i]); // should call __destruct() on it + $this->_reordermodules(); + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: successfully' + .' unloaded module: '.$name, __FILE__, __LINE__); + return true; + } + } + + $this->log(SMARTIRC_DEBUG_MODULES, 'DEBUG_MODULES: couldn\'t unload' + .' module: '.$name.' (it\'s not loaded!)', __FILE__, __LINE__ + ); + return false; + } + + // <private methods> + /** + * changes a already used nickname to a new nickname plus 3 random digits + * + * @return void + * @access private + */ + function _nicknameinuse() + { + $newnickname = substr($this->_nick, 0, 5).rand(0, 999); + $this->changeNick($newnickname, SMARTIRC_CRITICAL); + } + + /** + * sends an IRC message + * + * Adds a message to the messagequeue, with the optional priority. + * $priority: + * SMARTIRC_CRITICAL + * SMARTIRC_HIGH + * SMARTIRC_MEDIUM + * SMARTIRC_LOW + * + * @param string $data + * @param integer $priority must be one of the priority constants + * @return boolean + * @access public + */ + function send($data, $priority = SMARTIRC_MEDIUM) + { + return $this->_send($data, $priority); + } + + /** + * sends an IRC message + * + * Adds a message to the messagequeue, with the optional priority. + * $priority: + * SMARTIRC_CRITICAL + * SMARTIRC_HIGH + * SMARTIRC_MEDIUM + * SMARTIRC_LOW + * + * @param string $data + * @param integer $priority must be one of the priority constants + * @return boolean + * @access private + */ + function _send($data, $priority = SMARTIRC_MEDIUM) + { + switch ($priority) { + case SMARTIRC_CRITICAL: + $this->_rawsend($data); + break; + case SMARTIRC_HIGH: + case SMARTIRC_MEDIUM: + case SMARTIRC_LOW: + $this->_messagebuffer[$priority][] = $data; + break; + default: + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: message ('.$data.') with an invalid priority passed ('.$priority.'), message is ignored!', __FILE__, __LINE__); + return false; + } + + return true; + } + + /** + * checks the buffer if there are messages to send + * + * @return void + * @access private + */ + function _checkbuffer() + { + if (!$this->_loggedin) { + return; + } + + static $highsent = 0; + static $lastmicrotimestamp = 0; + + if ($lastmicrotimestamp == 0) { + $lastmicrotimestamp = $this->_microint(); + } + + $highcount = count($this->_messagebuffer[SMARTIRC_HIGH]); + $mediumcount = count($this->_messagebuffer[SMARTIRC_MEDIUM]); + $lowcount = count($this->_messagebuffer[SMARTIRC_LOW]); + $this->_messagebuffersize = $highcount+$mediumcount+$lowcount; + + // don't send them too fast + if ($this->_microint() >= ($lastmicrotimestamp+($this->_senddelay/1000))) { + $result = null; + if ($highcount > 0 && $highsent <= 2) { + $this->_rawsend(array_shift($this->_messagebuffer[SMARTIRC_HIGH])); + $lastmicrotimestamp = $this->_microint(); + $highsent++; + } else if ($mediumcount > 0) { + $this->_rawsend(array_shift($this->_messagebuffer[SMARTIRC_MEDIUM])); + $lastmicrotimestamp = $this->_microint(); + $highsent = 0; + } else if ($lowcount > 0) { + $this->_rawsend(array_shift($this->_messagebuffer[SMARTIRC_LOW])); + $lastmicrotimestamp = $this->_microint(); + } + } + } + + /** + * Checks the running timers and calls the registered timehandler, + * when the interval is reached. + * + * @return void + * @access private + */ + function _checktimer() + { + if (!$this->_loggedin) { + return; + } + + // has to be count() because the array may change during the loop! + for ($i = 0; $i < count($this->_timehandler); $i++) { + $handlerobject = &$this->_timehandler[$i]; + $microtimestamp = $this->_microint(); + if ($microtimestamp >= ($handlerobject->lastmicrotimestamp+($handlerobject->interval/1000))) { + $methodobject = &$handlerobject->object; + $method = $handlerobject->method; + $handlerobject->lastmicrotimestamp = $microtimestamp; + + if (@method_exists($methodobject, $method)) { + $this->log(SMARTIRC_DEBUG_TIMEHANDLER, 'DEBUG_TIMEHANDLER: calling method "'.get_class($methodobject).'->'.$method.'"', __FILE__, __LINE__); + $methodobject->$method($this); + } + } + } + } + + /** + * Checks if a receive or transmit timeout occured and reconnects if configured + * + * @return void + * @access private + */ + function _checktimeout() + { + if ($this->_autoreconnect == true) { + $timestamp = time(); + if ($this->_lastrx < ($timestamp - $this->_rxtimeout)) { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: receive timeout detected, doing reconnect...', __FILE__, __LINE__); + $this->_delayReconnect(); + $this->reconnect(); + } else if ($this->_lasttx < ($timestamp - $this->_txtimeout)) { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: transmit timeout detected, doing reconnect...', __FILE__, __LINE__); + $this->_delayReconnect(); + $this->reconnect(); + } + } + } + + /** + * sends a raw message to the IRC server (don't use this!!) + * + * Use message() or send() instead. + * + * @param string $data + * @return boolean + * @access private + */ + function _rawsend($data) + { + if ($this->_state() == SMARTIRC_STATE_CONNECTED) { + $this->log(SMARTIRC_DEBUG_IRCMESSAGES, 'DEBUG_IRCMESSAGES: sent: "'.$data.'"', __FILE__, __LINE__); + + if ($this->_usesockets == true) { + $result = socket_write($this->_socket, $data.SMARTIRC_CRLF); + } else { + $result = fwrite($this->_socket, $data.SMARTIRC_CRLF); + } + + + if ($result === false) { + // writing to the socket failed, means the connection is broken + $this->_connectionerror = true; + + return false; + } else { + $this->_lasttx = time(); + return true; + } + } else { + return false; + } + } + + /** + * goes into main receive mode _once_ per call and waits for messages from the IRC server + * + * @return void + * @access private + */ + function _rawreceive() + { + $lastpart = ''; + $rawdataar = array(); + + $this->_checkbuffer(); + + $timeout = $this->_selecttimeout(); + if ($this->_usesockets == true) { + $sread = array($this->_socket); + // this will trigger a warning when catching a signal + $result = @socket_select($sread, $w = null, $e = null, 0, $timeout*1000); + + if ($result == 1) { + // the socket got data to read + $rawdata = socket_read($this->_socket, 10240); + } else if ($result === false) { + if (socket_last_error() == 4) { + // we got hit with a SIGHUP signal + $rawdata = null; + global $bot; + + if (is_callable(array($bot, 'reload'))) { + $bot->reload(); + } + } else { + // panic! panic! something went wrong! + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: socket_select() returned false, something went wrong! Reason: '.socket_strerror(socket_last_error()), __FILE__, __LINE__); + exit; + } + } else { + // no data + $rawdata = null; + } + } else { + usleep($this->_receivedelay*1000); + $rawdata = fread($this->_socket, 10240); + } + if ($rawdata === false) { + // reading from the socket failed, the connection is broken + $this->_connectionerror = true; + } + + $this->_checktimer(); + $this->_checktimeout(); + + if ($rawdata !== null && !empty($rawdata)) { + $this->_lastrx = time(); + $rawdata = str_replace("\r", '', $rawdata); + $rawdata = $lastpart.$rawdata; + + $lastpart = substr($rawdata, strrpos($rawdata ,"\n")+1); + $rawdata = substr($rawdata, 0, strrpos($rawdata ,"\n")); + $rawdataar = explode("\n", $rawdata); + } + + // loop through our received messages + while (count($rawdataar) > 0) { + $rawline = array_shift($rawdataar); + $validmessage = false; + + $this->log(SMARTIRC_DEBUG_IRCMESSAGES, 'DEBUG_IRCMESSAGES: received: "'.$rawline.'"', __FILE__, __LINE__); + + // building our data packet + $ircdata = new Net_SmartIRC_data(); + $ircdata->rawmessage = $rawline; + $lineex = explode(' ', $rawline); + $ircdata->rawmessageex = $lineex; + $messagecode = $lineex[0]; + + if (substr($rawline, 0, 1) == ':') { + $validmessage = true; + $line = substr($rawline, 1); + $lineex = explode(' ', $line); + + // conform to RFC 2812 + $from = $lineex[0]; + $messagecode = $lineex[1]; + $exclamationpos = strpos($from, '!'); + $atpos = strpos($from, '@'); + $colonpos = strpos($line, ' :'); + if ($colonpos !== false) { + // we want the exact position of ":" not beginning from the space + $colonpos += 1; + } + $ircdata->nick = substr($from, 0, $exclamationpos); + $ircdata->ident = substr($from, $exclamationpos+1, ($atpos-$exclamationpos)-1); + $ircdata->host = substr($from, $atpos+1); + $ircdata->type = $this->_gettype($rawline); + $ircdata->from = $from; + if ($colonpos !== false) { + $ircdata->message = substr($line, $colonpos+1); + $ircdata->messageex = explode(' ', $ircdata->message); + } + + if ($ircdata->type & (SMARTIRC_TYPE_CHANNEL| + SMARTIRC_TYPE_ACTION| + SMARTIRC_TYPE_MODECHANGE| + SMARTIRC_TYPE_TOPICCHANGE| + SMARTIRC_TYPE_KICK| + SMARTIRC_TYPE_PART| + SMARTIRC_TYPE_JOIN)) { + $ircdata->channel = $lineex[2]; + } else if ($ircdata->type & (SMARTIRC_TYPE_WHO| + SMARTIRC_TYPE_BANLIST| + SMARTIRC_TYPE_TOPIC| + SMARTIRC_TYPE_CHANNELMODE)) { + $ircdata->channel = $lineex[3]; + } else if ($ircdata->type & SMARTIRC_TYPE_NAME) { + $ircdata->channel = $lineex[4]; + } + + if ($ircdata->channel !== null) { + if (substr($ircdata->channel, 0, 1) == ':') { + $ircdata->channel = substr($ircdata->channel, 1); + } + } + + $this->log(SMARTIRC_DEBUG_MESSAGEPARSER, 'DEBUG_MESSAGEPARSER: ircdata nick: "'.$ircdata->nick. + '" ident: "'.$ircdata->ident. + '" host: "'.$ircdata->host. + '" type: "'.$ircdata->type. + '" from: "'.$ircdata->from. + '" channel: "'.$ircdata->channel. + '" message: "'.$ircdata->message. + '"', __FILE__, __LINE__); + } + + // lets see if we have a messagehandler for it + $this->_handlemessage($messagecode, $ircdata); + + if ($validmessage == true) { + // now the actionhandlers are comming + $this->_handleactionhandler($ircdata); + } + + if (isset($ircdata)) { + unset($ircdata); + } + } + } + + /** + * sends the pong for keeping alive + * + * Sends the PONG signal as reply of the PING from the IRC server. + * + * @param string $data + * @return void + * @access private + */ + function _pong($data) + { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: Ping? Pong!', __FILE__, __LINE__); + $this->_send('PONG '.$data, SMARTIRC_CRITICAL); + } + + /** + * returns the calculated selecttimeout value + * + * @return integer selecttimeout in microseconds + * @access private + */ + function _selecttimeout() + { + if ($this->_messagebuffersize == 0) { + $this->_selecttimeout = null; + + if ($this->_mintimer != false) { + $this->_calculateselecttimeout($this->_mintimer); + } + + if ($this->_autoreconnect == true) { + $this->_calculateselecttimeout($this->_rxtimeout*1000); + } + + $this->_calculateselecttimeout($this->_maxtimer); + return $this->_selecttimeout; + } else { + return $this->_senddelay; + } + } + + /** + * calculates the selecttimeout value + * + * @return void + * @access private + */ + function _calculateselecttimeout($microseconds) + { + if (($this->_selecttimeout > $microseconds) || $this->_selecttimeout === null) { + $this->_selecttimeout = $microseconds; + } + } + + /** + * updates _mintimer to the smallest timer interval + * + * @return void + * @access private + */ + function _updatemintimer() + { + $timerarray = array(); + foreach ($this->_timehandler as $values) { + $timerarray[] = $values->interval; + } + + $result = array_multisort($timerarray, SORT_NUMERIC, SORT_ASC); + if ($result == true && isset($timerarray[0])) { + $this->_mintimer = $timerarray[0]; + } else { + $this->_mintimer = false; + } + } + + /** + * reorders the actionhandler array, needed after removing one + * + * @return void + * @access private + */ + function _reorderactionhandler() + { + $orderedactionhandler = array(); + foreach ($this->_actionhandler as $value) { + $orderedactionhandler[] = $value; + } + $this->_actionhandler = &$orderedactionhandler; + } + + /** + * reorders the timehandler array, needed after removing one + * + * @return void + * @access private + */ + function _reordertimehandler() + { + $orderedtimehandler = array(); + foreach ($this->_timehandler as $value) { + $orderedtimehandler[] = $value; + } + $this->_timehandler = &$orderedtimehandler; + } + + /** + * reorders the modules array, needed after removing one + * + * @return void + * @access private + */ + function _reordermodules() + { + $orderedmodules = array(); + foreach ($this->_modules as $value) { + $orderedmodules[] = $value; + } + $this->_modules = &$orderedmodules; + } + + /** + * determines the messagetype of $line + * + * Analyses the type of an IRC message and returns the type. + * + * @param string $line + * @return integer SMARTIRC_TYPE_* constant + * @access private + */ + function _gettype($line) + { + if (preg_match('/^:[^ ]+? [0-9]{3} .+$/', $line) == 1) { + $lineex = explode(' ', $line); + $code = $lineex[1]; + + switch ($code) { + case SMARTIRC_RPL_WELCOME: + case SMARTIRC_RPL_YOURHOST: + case SMARTIRC_RPL_CREATED: + case SMARTIRC_RPL_MYINFO: + case SMARTIRC_RPL_BOUNCE: + return SMARTIRC_TYPE_LOGIN; + case SMARTIRC_RPL_LUSERCLIENT: + case SMARTIRC_RPL_LUSEROP: + case SMARTIRC_RPL_LUSERUNKNOWN: + case SMARTIRC_RPL_LUSERME: + case SMARTIRC_RPL_LUSERCHANNELS: + return SMARTIRC_TYPE_INFO; + case SMARTIRC_RPL_MOTDSTART: + case SMARTIRC_RPL_MOTD: + case SMARTIRC_RPL_ENDOFMOTD: + return SMARTIRC_TYPE_MOTD; + case SMARTIRC_RPL_NAMREPLY: + case SMARTIRC_RPL_ENDOFNAMES: + return SMARTIRC_TYPE_NAME; + case SMARTIRC_RPL_WHOREPLY: + case SMARTIRC_RPL_ENDOFWHO: + return SMARTIRC_TYPE_WHO; + case SMARTIRC_RPL_LISTSTART: + return SMARTIRC_TYPE_NONRELEVANT; + case SMARTIRC_RPL_LIST: + case SMARTIRC_RPL_LISTEND: + return SMARTIRC_TYPE_LIST; + case SMARTIRC_RPL_BANLIST: + case SMARTIRC_RPL_ENDOFBANLIST: + return SMARTIRC_TYPE_BANLIST; + case SMARTIRC_RPL_TOPIC: + return SMARTIRC_TYPE_TOPIC; + case SMARTIRC_RPL_WHOISUSER: + case SMARTIRC_RPL_WHOISSERVER: + case SMARTIRC_RPL_WHOISOPERATOR: + case SMARTIRC_RPL_WHOISIDLE: + case SMARTIRC_RPL_ENDOFWHOIS: + case SMARTIRC_RPL_WHOISCHANNELS: + return SMARTIRC_TYPE_WHOIS; + case SMARTIRC_RPL_WHOWASUSER: + case SMARTIRC_RPL_ENDOFWHOWAS: + return SMARTIRC_TYPE_WHOWAS; + case SMARTIRC_RPL_UMODEIS: + return SMARTIRC_TYPE_USERMODE; + case SMARTIRC_RPL_CHANNELMODEIS: + return SMARTIRC_TYPE_CHANNELMODE; + case SMARTIRC_ERR_NICKNAMEINUSE: + case SMARTIRC_ERR_NOTREGISTERED: + return SMARTIRC_TYPE_ERROR; + default: + $this->log(SMARTIRC_DEBUG_IRCMESSAGES, 'DEBUG_IRCMESSAGES: replycode UNKNOWN ('.$code.'): "'.$line.'"', __FILE__, __LINE__); + } + } + + if (preg_match('/^:.*? PRIVMSG .* :'.chr(1).'ACTION .*'.chr(1).'$/', $line) == 1) { + return SMARTIRC_TYPE_ACTION; + } else if (preg_match('/^:.*? PRIVMSG .* :'.chr(1).'.*'.chr(1).'$/', $line) == 1) { + return (SMARTIRC_TYPE_CTCP_REQUEST|SMARTIRC_TYPE_CTCP); + } else if (preg_match('/^:.*? NOTICE .* :'.chr(1).'.*'.chr(1).'$/', $line) == 1) { + return (SMARTIRC_TYPE_CTCP_REPLY|SMARTIRC_TYPE_CTCP); + } else if (preg_match('/^:.*? PRIVMSG (\&|\#|\+|\!).* :.*$/', $line) == 1) { + return SMARTIRC_TYPE_CHANNEL; + } else if (preg_match('/^:.*? PRIVMSG .*:.*$/', $line) == 1) { + return SMARTIRC_TYPE_QUERY; + } else if (preg_match('/^:.*? NOTICE .* :.*$/', $line) == 1) { + return SMARTIRC_TYPE_NOTICE; + } else if (preg_match('/^:.*? INVITE .* .*$/', $line) == 1) { + return SMARTIRC_TYPE_INVITE; + } else if (preg_match('/^:.*? JOIN .*$/', $line) == 1) { + return SMARTIRC_TYPE_JOIN; + } else if (preg_match('/^:.*? TOPIC .* :.*$/', $line) == 1) { + return SMARTIRC_TYPE_TOPICCHANGE; + } else if (preg_match('/^:.*? NICK .*$/', $line) == 1) { + return SMARTIRC_TYPE_NICKCHANGE; + } else if (preg_match('/^:.*? KICK .* .*$/', $line) == 1) { + return SMARTIRC_TYPE_KICK; + } else if (preg_match('/^:.*? PART .*$/', $line) == 1) { + return SMARTIRC_TYPE_PART; + } else if (preg_match('/^:.*? MODE .* .*$/', $line) == 1) { + return SMARTIRC_TYPE_MODECHANGE; + } else if (preg_match('/^:.*? QUIT :.*$/', $line) == 1) { + return SMARTIRC_TYPE_QUIT; + } else { + $this->log(SMARTIRC_DEBUG_MESSAGETYPES, 'DEBUG_MESSAGETYPES: SMARTIRC_TYPE_UNKNOWN!: "'.$line.'"', __FILE__, __LINE__); + return SMARTIRC_TYPE_UNKNOWN; + } + } + + /** + * updates the current connection state + * + * @return boolean + * @access private + */ + function _updatestate() + { + if (is_resource($this->_socket)) { + $rtype = get_resource_type($this->_socket); + if (($this->_socket !== false) && + ($rtype == 'socket' || $rtype == 'Socket' || $rtype == 'stream')) { + $this->_state = true; + return true; + } + } else { + $this->_state = false; + $this->_loggedin = false; + return false; + } + } + + /** + * returns the current connection state + * + * @return integer SMARTIRC_STATE_CONNECTED or SMARTIRC_STATE_DISCONNECTED + * @access private + */ + function _state() + { + $result = $this->_updatestate(); + + if ($result == true) { + return SMARTIRC_STATE_CONNECTED; + } else { + return SMARTIRC_STATE_DISCONNECTED; + } + } + + /** + * tries to find a messagehandler for the received message ($ircdata) and calls it + * + * @param string $messagecode + * @param object $ircdata + * @return void + * @access private + */ + function _handlemessage($messagecode, &$ircdata) + { + $found = false; + + if (is_numeric($messagecode)) { + if (!array_key_exists($messagecode, $this->nreplycodes)) { + $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: ignoring unrecognized messagecode! "'.$messagecode.'"', __FILE__, __LINE__); + $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: this IRC server ('.$this->_address.') doesn\'t conform to the RFC 2812!', __FILE__, __LINE__); + return; + } + + $methodname = 'event_'.strtolower($this->nreplycodes[$messagecode]); + $_methodname = '_'.$methodname; + $_codetype = 'by numeric'; + } else if (is_string($messagecode)) { // its not numericcode so already a name/string + $methodname = 'event_'.strtolower($messagecode); + $_methodname = '_'.$methodname; + $_codetype = 'by string'; + } + + // if exists call internal method for the handling + if (@method_exists($this, $_methodname)) { + $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: calling internal method "'.get_class($this).'->'.$_methodname.'" ('.$_codetype.')', __FILE__, __LINE__); + $this->$_methodname($ircdata); + $found = true; + } + + // if exist, call user defined method for the handling + if (@method_exists($this, $methodname)) { + $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: calling user defined method "'.get_class($this).'->'.$methodname.'" ('.$_codetype.')', __FILE__, __LINE__); + $this->$methodname($ircdata); + $found = true; + } + + if ($found == false) { + $this->log(SMARTIRC_DEBUG_MESSAGEHANDLER, 'DEBUG_MESSAGEHANDLER: no method found for "'.$messagecode.'" ('.$methodname.')', __FILE__, __LINE__); + } + } + + /** + * Strips control characters from a IRC message. + * + * @param string $text + * + * @return string + */ + function stripControlCharacters($text) { + $controlCodes = array( + '/(\x03(?:\d{1,2}(?:,\d{1,2})?)?)/', // Color code + '/\x02/', // Bold + '/\x0F/', // Escaped + '/\x16/', // Italic + '/\x1F/', // Underline + '/\x12/' + ); + return preg_replace($controlCodes,'',$text); + } + + /** + * tries to find a actionhandler for the received message ($ircdata) and calls it + * + * @param object $ircdata + * @return void + * @access private + */ + function _handleactionhandler(&$ircdata) + { + $handler = &$this->_actionhandler; + $handlercount = count($handler); + for ($i = 0; $i < $handlercount; $i++) { + $handlerobject = &$handler[$i]; + + if (substr($handlerobject->message, 0, 1) == '/') { + $regex = $handlerobject->message; + } else { + $regex = '/'.$handlerobject->message.'/'; + } + + $ircdata->message = $this->stripControlCharacters($ircdata->message); + if (($handlerobject->type & $ircdata->type) && + (preg_match($regex, $ircdata->message) == 1)) { + + $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: actionhandler match found for id: '.$i.' type: '.$ircdata->type.' message: "'.$ircdata->message.'" regex: "'.$regex.'"', __FILE__, __LINE__); + + $methodobject = &$handlerobject->object; + $method = $handlerobject->method; + + if (@method_exists($methodobject, $method)) { + $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: calling method "'.get_class($methodobject).'->'.$method.'"', __FILE__, __LINE__); + $methodobject->$method($this, $ircdata); + } else { + $this->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: method doesn\'t exist! "'.get_class($methodobject).'->'.$method.'"', __FILE__, __LINE__); + } + } + } + } + + /** + * Delay reconnect + * + * @return void + * @access private + */ + function _delayReconnect() + { + if ($this->_reconnectdelay > 0) { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: delaying reconnect for '.$this->_reconnectdelay.' ms', __FILE__, __LINE__); + usleep($this->_reconnectdelay * 1000); + } + } + + /** + * getting current microtime, needed for benchmarks + * + * @return float + * @access private + */ + function _microint() + { + $tmp = microtime(); + $parts = explode(' ', $tmp); + $floattime = (float)$parts[0] + (float)$parts[1]; + return $floattime; + } + + /** + * adds an user to the channelobject or updates his info + * + * @param object $channel + * @param object $newuser + * @return void + * @access private + */ + function _adduser(&$channel, &$newuser) + { + $lowerednick = strtolower($newuser->nick); + if ($this->isJoined($channel->name, $newuser->nick)) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: updating user: '.$newuser->nick.' on channel: '.$channel->name, __FILE__, __LINE__); + + // lets update the existing user + $currentuser = &$channel->users[$lowerednick]; + + if ($newuser->ident !== null) { + $currentuser->ident = $newuser->ident; + } + if ($newuser->host !== null) { + $currentuser->host = $newuser->host; + } + if ($newuser->realname !== null) { + $currentuser->realname = $newuser->realname; + } + if ($newuser->ircop !== null) { + $currentuser->ircop = $newuser->ircop; + } + if ($newuser->founder !== null) { + $currentuser->founder = $newuser->founder; + } + if ($newuser->admin !== null) { + $currentuser->admin = $newuser->admin; + } + if ($newuser->op !== null) { + $currentuser->op = $newuser->op; + } + if ($newuser->hop !== null) { + $currentuser->hop = $newuser->hop; + } + if ($newuser->voice !== null) { + $currentuser->voice = $newuser->voice; + } + if ($newuser->away !== null) { + $currentuser->away = $newuser->away; + } + if ($newuser->server !== null) { + $currentuser->server = $newuser->server; + } + if ($newuser->hopcount !== null) { + $currentuser->hopcount = $newuser->hopcount; + } + } else { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding user: '.$newuser->nick.' to channel: '.$channel->name, __FILE__, __LINE__); + + // he is new just add the reference to him + $channel->users[$lowerednick] = &$newuser; + } + + $user = &$channel->users[$lowerednick]; + if ($user->founder) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding founder: '.$user->nick.' to channel: '.$channel->name, __FILE__, __LINE__); + $channel->founders[$user->nick] = true; + } + if ($user->admin) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding admin: '.$user->nick.' to channel: '.$channel->name, __FILE__, __LINE__); + $channel->admins[$user->nick] = true; + } + if ($user->op) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding op: '.$user->nick.' to channel: '.$channel->name, __FILE__, __LINE__); + $channel->ops[$user->nick] = true; + } + if ($user->hop) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding half-op: '.$user->nick.' to channel: '.$channel->name, __FILE__, __LINE__); + $channel->hops[$user->nick] = true; + } + if ($user->voice) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding voice: '.$user->nick.' to channel: '.$channel->name, __FILE__, __LINE__); + $channel->voices[$user->nick] = true; + } + } + + /** + * removes an user from one channel or all if he quits + * + * @param object $ircdata + * @return void + * @access private + */ + function _removeuser(&$ircdata) + { + if ($ircdata->type & (SMARTIRC_TYPE_PART|SMARTIRC_TYPE_QUIT)) { + $nick = $ircdata->nick; + } else if ($ircdata->type & SMARTIRC_TYPE_KICK) { + $nick = $ircdata->rawmessageex[3]; + } else { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: unknown TYPE ('.$ircdata->type.') in _removeuser(), trying default', __FILE__, __LINE__); + $nick = $ircdata->nick; + } + + $lowerednick = strtolower($nick); + + if ($this->_nick == $nick) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: we left channel: '.$ircdata->channel.' destroying...', __FILE__, __LINE__); + unset($this->_channels[strtolower($ircdata->channel)]); + } else { + if ($ircdata->type & SMARTIRC_TYPE_QUIT) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: user '.$nick.' quit, removing him from all channels', __FILE__, __LINE__); + // remove the user from all channels + $channelkeys = array_keys($this->_channels); + foreach ($channelkeys as $channelkey) { + // loop through all channels + $channel = &$this->_channels[$channelkey]; + foreach ($channel->users as $uservalue) { + // loop through all user in this channel + if ($nick == $uservalue->nick) { + // found him + // kill him + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: found him on channel: '.$channel->name.' destroying...', __FILE__, __LINE__); + unset($channel->users[$lowerednick]); + + if (isset($channel->founders[$nick])) { + // die! + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from founder list', __FILE__, __LINE__); + unset($channel->founders[$nick]); + } + + if (isset($channel->admins[$nick])) { + // die! + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from admin list', __FILE__, __LINE__); + unset($channel->admins[$nick]); + } + + if (isset($channel->ops[$nick])) { + // die! + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from op list', __FILE__, __LINE__); + unset($channel->ops[$nick]); + } + + if (isset($channel->hops[$nick])) { + // die! + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from hop list', __FILE__, __LINE__); + unset($channel->hops[$nick]); + } + + if (isset($channel->voices[$nick])) { + // die!! + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from voice list', __FILE__, __LINE__); + unset($channel->voices[$nick]); + } + + // ups this was not DukeNukem 3D + } + } + } + } else { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing user: '.$nick.' from channel: '.$ircdata->channel, __FILE__, __LINE__); + $channel = &$this->_channels[strtolower($ircdata->channel)]; + unset($channel->users[$lowerednick]); + + if (isset($channel->founders[$nick])) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from founder list', __FILE__, __LINE__); + unset($channel->founders[$nick]); + } + + if (isset($channel->admins[$nick])) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from admin list', __FILE__, __LINE__); + unset($channel->admins[$nick]); + } + + if (isset($channel->ops[$nick])) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from op list', __FILE__, __LINE__); + unset($channel->ops[$nick]); + } + + if (isset($channel->hops[$nick])) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from hop list', __FILE__, __LINE__); + unset($channel->hops[$nick]); + } + + if (isset($channel->voices[$nick])) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing him from voice list', __FILE__, __LINE__); + unset($channel->voices[$nick]); + } + } + } + } + + /** + * @return void + * @access private + */ + function _checkPHPVersion() + { + // doing nothing at the moment + } + + /** + * checks if the passed handlertype is valid + * + * @param integer $handlertype + * @return boolean + * @access private + */ + function _isValidType($handlertype) { + if ($handlertype & SMARTIRC_TYPE_ALL) { + return true; + } else { + return false; + } + } + + function _addIrcUser() + { + } + + function _updateIrcUser() + { + } + + function _removeIrcUser() + { + } + + function _addChannelUser() + { + } + + function _updateChannelUser() + { + } + + function _removeChannelUser() + { + } + + // </private methods> + + function isError($object) + { + return (bool)(is_object($object) && (strtolower(get_class($object)) == 'net_smartirc_error')); + } + + function &throwError($message) + { + $error = new Net_SmartIRC_Error($message); + return $error; + } +} + +// includes must be after the base class definition, required for PHP5 +require_once 'SmartIRC/irccommands.php'; +require_once 'SmartIRC/messagehandler.php'; + +class Net_SmartIRC extends Net_SmartIRC_messagehandler +{ + // empty +} + +/** + * @access public + */ +class Net_SmartIRC_data +{ + /** + * @var string + * @access public + */ + var $from; + + /** + * @var string + * @access public + */ + var $nick; + + /** + * @var string + * @access public + */ + var $ident; + + /** + * @var string + * @access public + */ + var $host; + + /** + * @var string + * @access public + */ + var $channel; + + /** + * @var string + * @access public + */ + var $message; + + /** + * @var array + * @access public + */ + var $messageex = array(); + + /** + * @var integer + * @access public + */ + var $type; + + /** + * @var string + * @access public + */ + var $rawmessage; + + /** + * @var array + * @access public + */ + var $rawmessageex = array(); +} + +/** + * @access public + */ +class Net_SmartIRC_actionhandler +{ + /** + * @var integer + * @access public + */ + var $id; + + /** + * @var integer + * @access public + */ + var $type; + + /** + * @var string + * @access public + */ + var $message; + + /** + * @var object + * @access public + */ + var $object; + + /** + * @var string + * @access public + */ + var $method; +} + +/** + * @access public + */ +class Net_SmartIRC_timehandler +{ + /** + * @var integer + * @access public + */ + var $id; + + /** + * @var integer + * @access public + */ + var $interval; + + /** + * @var integer + * @access public + */ + var $lastmicrotimestamp; + + /** + * @var object + * @access public + */ + var $object; + + /** + * @var string + * @access public + */ + var $method; +} + +/** + * @access public + */ +class Net_SmartIRC_channel +{ + /** + * @var string + * @access public + */ + var $name; + + /** + * @var string + * @access public + */ + var $key; + + /** + * @var array + * @access public + */ + var $users = array(); + + /** + * @var array + * @access public + */ + var $founders = array(); + + /** + * @var array + * @access public + */ + var $admins = array(); + + /** + * @var array + * @access public + */ + var $ops = array(); + + /** + * @var array + * @access public + */ + var $hops = array(); + + /** + * @var array + * @access public + */ + var $voices = array(); + + /** + * @var array + * @access public + */ + var $bans = array(); + + /** + * @var string + * @access public + */ + var $topic; + + /** + * @var string + * @access public + */ + var $user_limit = false; + + /** + * @var string + * @access public + */ + var $mode; + + /** + * @var integer + * @access public + */ + var $synctime_start = 0; + + /** + * @var integer + * @access public + */ + var $synctime_stop = 0; + + /** + * @var integer + * @access public + */ + var $synctime; +} + +/** + * @access public + */ +class Net_SmartIRC_user +{ + /** + * @var string + * @access public + */ + var $nick; + + /** + * @var string + * @access public + */ + var $ident; + + /** + * @var string + * @access public + */ + var $host; + + /** + * @var string + * @access public + */ + var $realname; + + /** + * @var boolean + * @access public + */ + var $ircop; + + /** + * @var boolean + * @access public + */ + var $away; + + /** + * @var string + * @access public + */ + var $server; + + /** + * @var integer + * @access public + */ + var $hopcount; +} + +/** + * @access public + */ +class Net_SmartIRC_channeluser extends Net_SmartIRC_user +{ + /** + * @var boolean + * @access public + */ + var $founder; + + /** + * @var boolean + * @access public + */ + var $admin; + + /** + * @var boolean + * @access public + */ + var $op; + + /** + * @var boolean + * @access public + */ + var $hop; + + /** + * @var boolean + * @access public + */ + var $voice; +} + +/** + * @access public + */ +class Net_SmartIRC_ircuser extends Net_SmartIRC_user +{ + /** + * @var array + * @access public + */ + var $joinedchannels = array(); +} + +/** + * @access public + */ +class Net_SmartIRC_listenfor +{ + /** + * @var array + * @access public + */ + var $result = array(); + + /** + * stores the received answer into the result array + * + * @param object $irc + * @param object $ircdata + * @return void + */ + function handler(&$irc, &$ircdata) + { + $irc->log(SMARTIRC_DEBUG_ACTIONHANDLER, 'DEBUG_ACTIONHANDLER: listenfor handler called', __FILE__, __LINE__); + $this->result[] = $ircdata; + $irc->disconnect(true); + } +} + +class Net_SmartIRC_Error +{ + var $error_msg; + + function __construct($message) + { + $this->error_msg = $message; + } + + function getMessage() + { + return $this->error_msg; + } +} +?> diff --git a/lib/Net_SmartIRC/Net/SmartIRC/defines.php b/lib/Net_SmartIRC/Net/SmartIRC/defines.php new file mode 100644 index 000000000..87f46dc95 --- /dev/null +++ b/lib/Net_SmartIRC/Net/SmartIRC/defines.php @@ -0,0 +1,237 @@ +<?php +/** + * $Id$ + * $Revision$ + * $Author$ + * $Date$ + * + * Copyright (c) 2002-2004 Mirco Bauer <meebey@meebey.net> <http://www.meebey.net> + * + * Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +// don't change this! unless you know what you do +define('SMARTIRC_CRLF', "\r\n"); +define('SMARTIRC_UNUSED', '*'); +define('SMARTIRC_STDOUT', 0); +define('SMARTIRC_FILE', 1); +define('SMARTIRC_SYSLOG', 2); +define('SMARTIRC_BROWSEROUT', 3); +define('SMARTIRC_NONE', 4); +define('SMARTIRC_LOW', 0); +define('SMARTIRC_MEDIUM', 1); +define('SMARTIRC_HIGH', 2); +define('SMARTIRC_CRITICAL', 3); +define('SMARTIRC_STATE_DISCONNECTED', 0); +define('SMARTIRC_STATE_CONNECTING', 1); +define('SMARTIRC_STATE_CONNECTED', 2); +define('SMARTIRC_DEBUG_NONE', 0); +define('SMARTIRC_DEBUG_NOTICE', 1); +define('SMARTIRC_DEBUG_CONNECTION', 2); +define('SMARTIRC_DEBUG_SOCKET', 4); +define('SMARTIRC_DEBUG_IRCMESSAGES', 8); +define('SMARTIRC_DEBUG_MESSAGETYPES', 16); +define('SMARTIRC_DEBUG_ACTIONHANDLER', 32); +define('SMARTIRC_DEBUG_TIMEHANDLER', 64); +define('SMARTIRC_DEBUG_MESSAGEHANDLER', 128); +define('SMARTIRC_DEBUG_CHANNELSYNCING', 256); +define('SMARTIRC_DEBUG_MODULES', 512); +define('SMARTIRC_DEBUG_USERSYNCING', 1024); +define('SMARTIRC_DEBUG_MESSAGEPARSER', 2048); +define('SMARTIRC_DEBUG_DCC', 4096); +define('SMARTIRC_DEBUG_ALL', 8191); +define('SMARTIRC_TYPE_UNKNOWN', 1); +define('SMARTIRC_TYPE_CHANNEL', 2); +define('SMARTIRC_TYPE_QUERY', 4); +define('SMARTIRC_TYPE_CTCP', 8); +define('SMARTIRC_TYPE_NOTICE', 16); +define('SMARTIRC_TYPE_WHO', 32); +define('SMARTIRC_TYPE_JOIN', 64); +define('SMARTIRC_TYPE_INVITE', 128); +define('SMARTIRC_TYPE_ACTION', 256); +define('SMARTIRC_TYPE_TOPICCHANGE', 512); +define('SMARTIRC_TYPE_NICKCHANGE', 1024); +define('SMARTIRC_TYPE_KICK', 2048); +define('SMARTIRC_TYPE_QUIT', 4096); +define('SMARTIRC_TYPE_LOGIN', 8192); +define('SMARTIRC_TYPE_INFO', 16384); +define('SMARTIRC_TYPE_LIST', 32768); +define('SMARTIRC_TYPE_NAME', 65536); +define('SMARTIRC_TYPE_MOTD', 131072); +define('SMARTIRC_TYPE_MODECHANGE', 262144); +define('SMARTIRC_TYPE_PART', 524288); +define('SMARTIRC_TYPE_ERROR', 1048576); +define('SMARTIRC_TYPE_BANLIST', 2097152); +define('SMARTIRC_TYPE_TOPIC', 4194304); +define('SMARTIRC_TYPE_NONRELEVANT', 8388608); +define('SMARTIRC_TYPE_WHOIS', 16777216); +define('SMARTIRC_TYPE_WHOWAS', 33554432); +define('SMARTIRC_TYPE_USERMODE', 67108864); +define('SMARTIRC_TYPE_CHANNELMODE', 134217728); +define('SMARTIRC_TYPE_CTCP_REQUEST', 268435456); +define('SMARTIRC_TYPE_CTCP_REPLY', 536870912); +//define('SMARTIRC_TYPE_DCC', 536870912); +define('SMARTIRC_TYPE_ALL', 1073741823); + +$SMARTIRC_replycodes = array( +'RPL_WELCOME' => '001', +'RPL_YOURHOST' => '002', +'RPL_CREATED' => '003', +'RPL_MYINFO' => '004', +'RPL_BOUNCE' => '005', +'RPL_TRACELINK' => '200', +'RPL_TRACECONNECTING' => '201', +'RPL_TRACEHANDSHAKE' => '202', +'RPL_TRACEUNKNOWN' => '203', +'RPL_TRACEOPERATOR' => '204', +'RPL_TRACEUSER' => '205', +'RPL_TRACESERVER' => '206', +'RPL_TRACESERVICE' => '207', +'RPL_TRACENEWTYPE' => '208', +'RPL_TRACECLASS' => '209', +'RPL_TRACERECONNECT' => '210', +'RPL_STATSLINKINFO' => '211', +'RPL_STATSCOMMANDS' => '212', +'RPL_ENDOFSTATS' => '219', +'RPL_UMODEIS' => '221', +'RPL_SERVLIST' => '234', +'RPL_SERVLISTEND' => '235', +'RPL_STATSUPTIME' => '242', +'RPL_STATSOLINE' => '243', +'RPL_LUSERCLIENT' => '251', +'RPL_LUSEROP' => '252', +'RPL_LUSERUNKNOWN' => '253', +'RPL_LUSERCHANNELS' => '254', +'RPL_LUSERME' => '255', +'RPL_ADMINME' => '256', +'RPL_ADMINLOC1' => '257', +'RPL_ADMINLOC2' => '258', +'RPL_ADMINEMAIL' => '259', +'RPL_TRACELOG' => '261', +'RPL_TRACEEND' => '262', +'RPL_TRYAGAIN' => '263', +'RPL_AWAY' => '301', +'RPL_USERHOST' => '302', +'RPL_ISON' => '303', +'RPL_UNAWAY' => '305', +'RPL_NOWAWAY' => '306', +'RPL_WHOISUSER' => '311', +'RPL_WHOISSERVER' => '312', +'RPL_WHOISOPERATOR' => '313', +'RPL_WHOWASUSER' => '314', +'RPL_ENDOFWHO' => '315', +'RPL_WHOISIDLE' => '317', +'RPL_ENDOFWHOIS' => '318', +'RPL_WHOISCHANNELS' => '319', +'RPL_LISTSTART' => '321', +'RPL_LIST' => '322', +'RPL_LISTEND' => '323', +'RPL_CHANNELMODEIS' => '324', +'RPL_UNIQOPIS' => '325', +'RPL_NOTOPIC' => '331', +'RPL_TOPIC' => '332', +'RPL_INVITING' => '341', +'RPL_SUMMONING' => '342', +'RPL_INVITELIST' => '346', +'RPL_ENDOFINVITELIST' => '347', +'RPL_EXCEPTLIST' => '348', +'RPL_ENDOFEXCEPTLIST' => '349', +'RPL_VERSION' => '351', +'RPL_WHOREPLY' => '352', +'RPL_NAMREPLY' => '353', +'RPL_LINKS' => '364', +'RPL_ENDOFLINKS' => '365', +'RPL_ENDOFNAMES' => '366', +'RPL_BANLIST' => '367', +'RPL_ENDOFBANLIST' => '368', +'RPL_ENDOFWHOWAS' => '369', +'RPL_INFO' => '371', +'RPL_MOTD' => '372', +'RPL_ENDOFINFO' => '374', +'RPL_MOTDSTART' => '375', +'RPL_ENDOFMOTD' => '376', +'RPL_YOUREOPER' => '381', +'RPL_REHASHING' => '382', +'RPL_YOURESERVICE' => '383', +'RPL_TIME' => '391', +'RPL_USERSSTART' => '392', +'RPL_USERS' => '393', +'RPL_ENDOFUSERS' => '394', +'RPL_NOUSERS' => '395', +'ERR_NOSUCHNICK' => '401', +'ERR_NOSUCHSERVER' => '402', +'ERR_NOSUCHCHANNEL' => '403', +'ERR_CANNOTSENDTOCHAN' => '404', +'ERR_TOOMANYCHANNELS' => '405', +'ERR_WASNOSUCHNICK' => '406', +'ERR_TOOMANYTARGETS' => '407', +'ERR_NOSUCHSERVICE' => '408', +'ERR_NOORIGIN' => '409', +'ERR_NORECIPIENT' => '411', +'ERR_NOTEXTTOSEND' => '412', +'ERR_NOTOPLEVEL' => '413', +'ERR_WILDTOPLEVEL' => '414', +'ERR_BADMASK' => '415', +'ERR_UNKNOWNCOMMAND' => '421', +'ERR_NOMOTD' => '422', +'ERR_NOADMININFO' => '423', +'ERR_FILEERROR' => '424', +'ERR_NONICKNAMEGIVEN' => '431', +'ERR_ERRONEUSNICKNAME' => '432', +'ERR_NICKNAMEINUSE' => '433', +'ERR_NICKCOLLISION' => '436', +'ERR_UNAVAILRESOURCE' => '437', +'ERR_USERNOTINCHANNEL' => '441', +'ERR_NOTONCHANNEL' => '442', +'ERR_USERONCHANNEL' => '443', +'ERR_NOLOGIN' => '444', +'ERR_SUMMONDISABLED' => '445', +'ERR_USERSDISABLED' => '446', +'ERR_NOTREGISTERED' => '451', +'ERR_NEEDMOREPARAMS' => '461', +'ERR_ALREADYREGISTRED' => '462', +'ERR_NOPERMFORHOST' => '463', +'ERR_PASSWDMISMATCH' => '464', +'ERR_YOUREBANNEDCREEP' => '465', +'ERR_YOUWILLBEBANNED' => '466', +'ERR_KEYSET' => '467', +'ERR_CHANNELISFULL' => '471', +'ERR_UNKNOWNMODE' => '472', +'ERR_INVITEONLYCHAN' => '473', +'ERR_BANNEDFROMCHAN' => '474', +'ERR_BADCHANNELKEY' => '475', +'ERR_BADCHANMASK' => '476', +'ERR_NOCHANMODES' => '477', +'ERR_BANLISTFULL' => '478', +'ERR_NOPRIVILEGES' => '481', +'ERR_CHANOPRIVSNEEDED' => '482', +'ERR_CANTKILLSERVER' => '483', +'ERR_RESTRICTED' => '484', +'ERR_UNIQOPPRIVSNEEDED' => '485', +'ERR_NOOPERHOST' => '491', +'ERR_UMODEUNKNOWNFLAG' => '501', +'ERR_USERSDONTMATCH' => '502', +); + +$SMARTIRC_nreplycodes = array(); + +foreach ($SMARTIRC_replycodes as $key => $value) { + define('SMARTIRC_'.$key, $value); + $SMARTIRC_nreplycodes[$value] = $key; +} + +?> \ No newline at end of file diff --git a/lib/Net_SmartIRC/Net/SmartIRC/irccommands.php b/lib/Net_SmartIRC/Net/SmartIRC/irccommands.php new file mode 100644 index 000000000..a85f37f07 --- /dev/null +++ b/lib/Net_SmartIRC/Net/SmartIRC/irccommands.php @@ -0,0 +1,526 @@ +<?php +/** + * $Id$ + * $Revision$ + * $Author$ + * $Date$ + * + * Copyright (c) 2002-2004 Mirco Bauer <meebey@meebey.net> <http://www.meebey.net> + * + * Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +class Net_SmartIRC_irccommands extends Net_SmartIRC_base +{ + /** + * sends a new message + * + * Sends a message to a channel or user. + * + * @see DOCUMENTATION + * @param integer $type specifies the type, like QUERY/ACTION or CTCP see 'Message Types' + * @param string $destination can be a user or channel + * @param mixed $message the message + * @return boolean + * @access public + */ + function message($type, $destination, $messagearray, $priority = SMARTIRC_MEDIUM) + { + if (!is_array($messagearray)) { + $messagearray = array($messagearray); + } + + switch ($type) { + case SMARTIRC_TYPE_CHANNEL: + case SMARTIRC_TYPE_QUERY: + foreach ($messagearray as $message) { + $this->_send('PRIVMSG '.$destination.' :'.$message, $priority); + } + break; + case SMARTIRC_TYPE_ACTION: + foreach ($messagearray as $message) { + $this->_send('PRIVMSG '.$destination.' :'.chr(1).'ACTION '.$message.chr(1), $priority); + } + break; + case SMARTIRC_TYPE_NOTICE: + foreach ($messagearray as $message) { + $this->_send('NOTICE '.$destination.' :'.$message, $priority); + } + break; + case SMARTIRC_TYPE_CTCP: // backwards compatibilty + case SMARTIRC_TYPE_CTCP_REPLY: + foreach ($messagearray as $message) { + $this->_send('NOTICE '.$destination.' :'.chr(1).$message.chr(1), $priority); + } + break; + case SMARTIRC_TYPE_CTCP_REQUEST: + foreach ($messagearray as $message) { + $this->_send('PRIVMSG '.$destination.' :'.chr(1).$message.chr(1), $priority); + } + break; + default: + return false; + } + + return true; + } + + /** + * returns an object reference to the specified channel + * + * If the channel does not exist (because not joint) false will be returned. + * + * @param string $channelname + * @return object reference to the channel object + * @access public + */ + function &channel($channelname) + { + if (isset($this->_channels[strtolower($channelname)])) { + return $this->_channels[strtolower($channelname)]; + } else { + return false; + } + } + + // <IRC methods> + /** + * Joins one or more IRC channels with an optional key. + * + * @NOTE MODIFIED BY NZEDB TO ACCEPT PASSWORD PER CHANNEL. + * + * @param array $channelarray ; array('#channelname1' => 'password', '#channelname2' => null); + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function join($channelarray, $priority = SMARTIRC_MEDIUM) + { + foreach ($channelarray as $channel => $password) { + $this->_send('JOIN ' . $channel . ($password === null ? '' : ' ' . $password), $priority); + } + } + + /** + * parts from one or more IRC channels with an optional reason + * + * @param mixed $channelarray + * @param string $reason + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function part($channelarray, $reason = null, $priority = SMARTIRC_MEDIUM) + { + if (!is_array($channelarray)) { + $channelarray = array($channelarray); + } + + $channellist = implode(',', $channelarray); + + if ($reason !== null) { + $this->_send('PART '.$channellist.' :'.$reason, $priority); + } else { + $this->_send('PART '.$channellist, $priority); + } + } + + /** + * Kicks one or more user from an IRC channel with an optional reason. + * + * @param string $channel + * @param mixed $nicknamearray + * @param string $reason + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function kick($channel, $nicknamearray, $reason = null, $priority = SMARTIRC_MEDIUM) + { + if (!is_array($nicknamearray)) { + $nicknamearray = array($nicknamearray); + } + + $nicknamelist = implode(',', $nicknamearray); + + if ($reason !== null) { + $this->_send('KICK '.$channel.' '.$nicknamelist.' :'.$reason, $priority); + } else { + $this->_send('KICK '.$channel.' '.$nicknamelist, $priority); + } + } + + /** + * gets a list of one ore more channels + * + * Requests a full channellist if $channelarray is not given. + * (use it with care, usualy its a looooong list) + * + * @param mixed $channelarray + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function getList($channelarray = null, $priority = SMARTIRC_MEDIUM) + { + if ($channelarray !== null) { + if (!is_array($channelarray)) { + $channelarray = array($channelarray); + } + + $channellist = implode(',', $channelarray); + $this->_send('LIST '.$channellist, $priority); + } else { + $this->_send('LIST', $priority); + } + } + + /** + * requests all nicknames of one or more channels + * + * The requested nickname list also includes op and voice state + * + * @param mixed $channelarray + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function names($channelarray = null, $priority = SMARTIRC_MEDIUM) + { + if ($channelarray !== null) { + if (!is_array($channelarray)) { + $channelarray = array($channelarray); + } + + $channellist = implode(',', $channelarray); + $this->_send('NAMES '.$channellist, $priority); + } else { + $this->_send('NAMES', $priority); + } + } + + /** + * sets a new topic of a channel + * + * @param string $channel + * @param string $newtopic + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function setTopic($channel, $newtopic, $priority = SMARTIRC_MEDIUM) + { + $this->_send('TOPIC '.$channel.' :'.$newtopic, $priority); + } + + /** + * gets the topic of a channel + * + * @param string $channel + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function getTopic($channel, $priority = SMARTIRC_MEDIUM) + { + $this->_send('TOPIC '.$channel, $priority); + } + + /** + * sets or gets the mode of an user or channel + * + * Changes/requests the mode of the given target. + * + * @param string $target the target, can be an user (only yourself) or a channel + * @param string $newmode the new mode like +mt + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function mode($target, $newmode = null, $priority = SMARTIRC_MEDIUM) + { + if ($newmode !== null) { + $this->_send('MODE '.$target.' '.$newmode, $priority); + } else { + $this->_send('MODE '.$target, $priority); + } + } + + /** + * founders an user in the given channel + * + * @param string $channel + * @param string $nickname + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function founder($channel, $nickname, $priority = SMARTIRC_MEDIUM) + { + $this->mode($channel, '+q '.$nickname, $priority); + } + + /** + * defounders an user in the given channel + * + * @param string $channel + * @param string $nickname + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function defounder($channel, $nickname, $priority = SMARTIRC_MEDIUM) + { + $this->mode($channel, '-q '.$nickname, $priority); + } + + /** + * admins an user in the given channel + * + * @param string $channel + * @param string $nickname + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function admin($channel, $nickname, $priority = SMARTIRC_MEDIUM) + { + $this->mode($channel, '+a '.$nickname, $priority); + } + + /** + * deadmins an user in the given channel + * + * @param string $channel + * @param string $nickname + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function deadmin($channel, $nickname, $priority = SMARTIRC_MEDIUM) + { + $this->mode($channel, '-a '.$nickname, $priority); + } + + /** + * ops an user in the given channel + * + * @param string $channel + * @param string $nickname + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function op($channel, $nickname, $priority = SMARTIRC_MEDIUM) + { + $this->mode($channel, '+o '.$nickname, $priority); + } + + /** + * deops an user in the given channel + * + * @param string $channel + * @param string $nickname + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function deop($channel, $nickname, $priority = SMARTIRC_MEDIUM) + { + $this->mode($channel, '-o '.$nickname, $priority); + } + + /** + * hops an user in the given channel + * + * @param string $channel + * @param string $nickname + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function hop($channel, $nickname, $priority = SMARTIRC_MEDIUM) + { + $this->mode($channel, '+h '.$nickname, $priority); + } + + /** + * dehops an user in the given channel + * + * @param string $channel + * @param string $nickname + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function dehop($channel, $nickname, $priority = SMARTIRC_MEDIUM) + { + $this->mode($channel, '-h '.$nickname, $priority); + } + + /** + * voice a user in the given channel + * + * @param string $channel + * @param string $nickname + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function voice($channel, $nickname, $priority = SMARTIRC_MEDIUM) + { + $this->mode($channel, '+v '.$nickname, $priority); + } + + /** + * devoice a user in the given channel + * + * @param string $channel + * @param string $nickname + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function devoice($channel, $nickname, $priority = SMARTIRC_MEDIUM) + { + $this->mode($channel, '-v '.$nickname, $priority); + } + + /** + * bans a hostmask for the given channel or requests the current banlist + * + * The banlist will be requested if no hostmask is specified + * + * @param string $channel + * @param string $hostmask + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function ban($channel, $hostmask = null, $priority = SMARTIRC_MEDIUM) + { + if ($hostmask !== null) { + $this->mode($channel, '+b '.$hostmask, $priority); + } else { + $this->mode($channel, 'b', $priority); + } + } + + /** + * unbans a hostmask on the given channel + * + * @param string $channel + * @param string $hostmask + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function unban($channel, $hostmask, $priority = SMARTIRC_MEDIUM) + { + $this->mode($channel, '-b '.$hostmask, $priority); + } + + /** + * invites a user to the specified channel + * + * @param string $nickname + * @param string $channel + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function invite($nickname, $channel, $priority = SMARTIRC_MEDIUM) + { + $this->_send('INVITE '.$nickname.' '.$channel, $priority); + } + + /** + * changes the own nickname + * + * Trys to set a new nickname, nickcollisions are handled. + * + * @param string $newnick + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function changeNick($newnick, $priority = SMARTIRC_MEDIUM) + { + $this->_send('NICK '.$newnick, $priority); + $this->_nick = $newnick; + } + + /** + * requests a 'WHO' from the specified target + * + * @param string $target + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function who($target, $priority = SMARTIRC_MEDIUM) + { + $this->_send('WHO '.$target, $priority); + } + + /** + * requests a 'WHOIS' from the specified target + * + * @param string $target + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function whois($target, $priority = SMARTIRC_MEDIUM) + { + $this->_send('WHOIS '.$target, $priority); + } + + /** + * requests a 'WHOWAS' from the specified target + * (if he left the IRC network) + * + * @param string $target + * @param integer $priority message priority, default is SMARTIRC_MEDIUM + * @return void + * @access public + */ + function whowas($target, $priority = SMARTIRC_MEDIUM) + { + $this->_send('WHOWAS '.$target, $priority); + } + + /** + * sends QUIT to IRC server and disconnects + * + * @param string $quitmessage optional quitmessage + * @param integer $priority message priority, default is SMARTIRC_CRITICAL + * @return void + * @access public + */ + function quit($quitmessage = null, $priority = SMARTIRC_CRITICAL) + { + if ($quitmessage !== null) { + $this->_send('QUIT :'.$quitmessage, $priority); + } else { + $this->_send('QUIT', $priority); + } + + $this->disconnect(true); + } +} +?> diff --git a/lib/Net_SmartIRC/Net/SmartIRC/messagehandler.php b/lib/Net_SmartIRC/Net/SmartIRC/messagehandler.php new file mode 100644 index 000000000..8ff8358ff --- /dev/null +++ b/lib/Net_SmartIRC/Net/SmartIRC/messagehandler.php @@ -0,0 +1,527 @@ +<?php +/** + * $Id$ + * $Revision$ + * $Author$ + * $Date$ + * + * Copyright (c) 2002-2004 Mirco Bauer <meebey@meebey.net> <http://www.meebey.net> + * + * Full LGPL License: <http://www.gnu.org/licenses/lgpl.txt> + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library 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 + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + */ + +class Net_SmartIRC_messagehandler extends Net_SmartIRC_irccommands +{ + /* misc */ + function _event_ping(&$ircdata) + { + $this->_pong(substr($ircdata->rawmessage, 5)); + } + + function _event_error(&$ircdata) + { + if ($this->_autoretry == true) { + $this->_delayReconnect(); + $this->reconnect(); + } else { + $this->disconnect(true); + } + } + + function _event_join(&$ircdata) + { + if ($this->_channelsyncing == true) { + if ($this->_nick == $ircdata->nick) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: joining channel: '.$ircdata->channel, __FILE__, __LINE__); + $channel = new Net_SmartIRC_channel(); + $channel->name = $ircdata->channel; + $microint = $this->_microint(); + $channel->synctime_start = $microint; + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: synctime_start for '.$ircdata->channel.' set to: '.$microint, __FILE__, __LINE__); + $this->_channels[strtolower($channel->name)] = &$channel; + + // the class will get his own who data from the whole who channel list + $this->mode($channel->name); + $this->who($channel->name); + $this->ban($channel->name); + } else { + // the class didn't join but someone else, lets get his who data + $this->who($ircdata->nick); + } + + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: '.$ircdata->nick.' joins channel: '.$ircdata->channel, __FILE__, __LINE__); + $channel = &$this->_channels[strtolower($ircdata->channel)]; + $user = new Net_SmartIRC_channeluser(); + $user->nick = $ircdata->nick; + $user->ident = $ircdata->ident; + $user->host = $ircdata->host; + + $this->_adduser($channel, $user); + } + } + + function _event_part(&$ircdata) + { + if ($this->_channelsyncing == true) { + $this->_removeuser($ircdata); + } + } + + function _event_kick(&$ircdata) + { + if ($this->_channelsyncing == true) { + $this->_removeuser($ircdata); + } + } + + function _event_quit(&$ircdata) + { + if ($this->_channelsyncing == true) { + $this->_removeuser($ircdata); + } + } + + function _event_nick(&$ircdata) + { + if ($this->_channelsyncing == true) { + $newnick = $ircdata->rawmessageex[2]; + $lowerednewnick = strtolower($newnick); + $lowerednick = strtolower($ircdata->nick); + + $channelkeys = array_keys($this->_channels); + foreach ($channelkeys as $channelkey) { + // loop through all channels + $channel = &$this->_channels[$channelkey]; + foreach ($channel->users as $uservalue) { + // loop through all user in this channel + + if ($ircdata->nick == $uservalue->nick) { + // found him + // time for updating the object and his nickname + $channel->users[$lowerednewnick] = $channel->users[$lowerednick]; + $channel->users[$lowerednewnick]->nick = $newnick; + + if ($lowerednewnick != $lowerednick) { + unset($channel->users[$lowerednick]); + } + + // he was maybe op or voice, update comming + if (isset($channel->founders[$ircdata->nick])) { + $channel->founders[$newnick] = $channel->founders[$ircdata->nick]; + unset($channel->founders[$ircdata->nick]); + } + if (isset($channel->admins[$ircdata->nick])) { + $channel->admins[$newnick] = $channel->admins[$ircdata->nick]; + unset($channel->admins[$ircdata->nick]); + } + if (isset($channel->ops[$ircdata->nick])) { + $channel->ops[$newnick] = $channel->ops[$ircdata->nick]; + unset($channel->ops[$ircdata->nick]); + } + if (isset($channel->hops[$ircdata->nick])) { + $channel->hops[$newnick] = $channel->hops[$ircdata->nick]; + unset($channel->hops[$ircdata->nick]); + } + if (isset($channel->voices[$ircdata->nick])) { + $channel->voices[$newnick] = $channel->voices[$ircdata->nick]; + unset($channel->voices[$ircdata->nick]); + } + + break; + } + } + } + } + } + + function _event_mode(&$ircdata) + { + // check if its own usermode + if ($ircdata->rawmessageex[2] == $this->_nick) { + $this->_usermode = substr($ircdata->rawmessageex[3], 1); + } else if ($this->_channelsyncing == true) { + // it's not, and we do channel syching + $channel = &$this->_channels[strtolower($ircdata->channel)]; + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: updating channel mode for: '.$channel->name, __FILE__, __LINE__); + $mode = $ircdata->rawmessageex[3]; + $parameters = array_slice($ircdata->rawmessageex, 4); + + $add = false; + $remove = false; + $modelength = strlen($mode); + for ($i = 0; $i < $modelength; $i++) { + switch($mode[$i]) { + case '-': + $remove = true; + $add = false; + break; + case '+': + $add = true; + $remove = false; + break; + // user modes + case 'q': + $nick = array_shift($parameters); + $lowerednick = strtolower($nick); + if ($add) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding founder: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); + $channel->founders[$nick] = true; + $channel->users[$lowerednick]->founder = true; + } + if ($remove) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing founder: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); + unset($channel->founders[$nick]); + $channel->users[$lowerednick]->founder = false; + } + break; + case 'a': + $nick = array_shift($parameters); + $lowerednick = strtolower($nick); + if ($add) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding admin: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); + $channel->admins[$nick] = true; + $channel->users[$lowerednick]->admin = true; + } + if ($remove) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing admin: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); + unset($channel->admins[$nick]); + $channel->users[$lowerednick]->admin = false; + } + break; + case 'o': + $nick = array_shift($parameters); + $lowerednick = strtolower($nick); + if ($add) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding op: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); + $channel->ops[$nick] = true; + $channel->users[$lowerednick]->op = true; + } + if ($remove) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing op: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); + unset($channel->ops[$nick]); + $channel->users[$lowerednick]->op = false; + } + break; + case 'h': + $nick = array_shift($parameters); + $lowerednick = strtolower($nick); + if ($add) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding half-op: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); + $channel->hops[$nick] = true; + $channel->users[$lowerednick]->hop = true; + } + if ($remove) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing half-op: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); + unset($channel->hops[$nick]); + $channel->users[$lowerednick]->hop = false; + } + break; + case 'v': + $nick = array_shift($parameters); + $lowerednick = strtolower($nick); + if ($add) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding voice: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); + $channel->voices[$nick] = true; + $channel->users[$lowerednick]->voice = true; + } + if ($remove) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing voice: '.$nick.' to channel: '.$channel->name, __FILE__, __LINE__); + unset($channel->voices[$nick]); + $channel->users[$lowerednick]->voice = false; + } + break; + case 'k': + $key = array_shift($parameters); + if ($add) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: stored channel key for: '.$channel->name, __FILE__, __LINE__); + $channel->key = $key; + } + if ($remove) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removed channel key for: '.$channel->name, __FILE__, __LINE__); + $channel->key = ''; + } + break; + case 'l': + if ($add) { + $limit = array_shift($parameters); + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: stored user limit for: '.$channel->name, __FILE__, __LINE__); + $channel->user_limit = $limit; + } + if ($remove) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removed user limit for: '.$channel->name, __FILE__, __LINE__); + $channel->user_limit = false; + } + break; + default: + // channel modes + if ($mode[$i] == 'b') { + $hostmask = array_shift($parameters); + if ($add) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: adding ban: '.$hostmask.' for: '.$channel->name, __FILE__, __LINE__); + $channel->bans[$hostmask] = true; + } + if ($remove) { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: removing ban: '.$hostmask.' for: '.$channel->name, __FILE__, __LINE__); + unset($channel->bans[$hostmask]); + } + } else { + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: storing unknown channelmode ('.$mode.') in channel->mode for: '.$channel->name, __FILE__, __LINE__); + if ($add) { + $channel->mode .= $mode[$i]; + } + if ($remove) { + $channel->mode = str_replace($mode[$i], '', $channel->mode); + } + } + } + } + } + } + + function _event_topic(&$ircdata) + { + if ($this->_channelsyncing == true) { + $channel = &$this->_channels[strtolower($ircdata->rawmessageex[2])]; + $channel->topic = $ircdata->message; + } + } + + function _event_privmsg(&$ircdata) + { + if ($ircdata->type & SMARTIRC_TYPE_CTCP_REQUEST) { + // substr must be 1,4 because of \001 in CTCP messages + if (substr($ircdata->message, 1, 4) == 'PING') { + $this->message(SMARTIRC_TYPE_CTCP_REPLY, $ircdata->nick, 'PING '.substr($ircdata->message, 5, -1)); + } elseif (substr($ircdata->message, 1, 7) == 'VERSION') { + if (!empty($this->_ctcpversion)) { + $versionstring = $this->_ctcpversion; + } else { + $versionstring = SMARTIRC_VERSIONSTRING; + } + + $this->message(SMARTIRC_TYPE_CTCP_REPLY, $ircdata->nick, 'VERSION '.$versionstring); + } elseif (substr($ircdata->message, 1, 10) == 'CLIENTINFO') { + $this->message(SMARTIRC_TYPE_CTCP_REPLY, $ircdata->nick, 'CLIENTINFO PING VERSION CLIENTINFO'); + } + } + } + + /* rpl_ */ + function _event_rpl_welcome(&$ircdata) + { + $this->_loggedin = true; + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: logged in', __FILE__, __LINE__); + + // updating our nickname, that we got (maybe cutted...) + $this->_nick = $ircdata->rawmessageex[2]; + } + + function _event_rpl_motdstart(&$ircdata) + { + $this->_motd[] = $ircdata->message; + } + + function _event_rpl_motd(&$ircdata) + { + $this->_motd[] = $ircdata->message; + } + + function _event_rpl_endofmotd(&$ircdata) + { + $this->_motd[] = $ircdata->message; + } + + function _event_rpl_umodeis(&$ircdata) + { + $this->_usermode = $ircdata->message; + } + + function _event_rpl_channelmodeis(&$ircdata) { + if ($this->_channelsyncing == true && $this->isJoined($ircdata->channel)) { + $mode = $ircdata->rawmessageex[4]; + $parameters = array_slice($ircdata->rawmessageex, 5); + + $ircdata->rawmessageex = array( 0 => '', + 1 => '', + 2 => '', + 3 => $mode); + + foreach ($parameters as $value) { + $ircdata->rawmessageex[] = $value; + } + + // let _mode() handle the received mode + $this->_event_mode($ircdata); + } + } + + function _event_rpl_whoreply(&$ircdata) + { + if ($this->_channelsyncing == true) { + $nick = $ircdata->rawmessageex[7]; + if ($ircdata->channel == '*') { + // we got who info without channel info, so we need to search the user + // on all channels and update him + foreach ($this->_channels as $channel) { + if ($this->isJoined($channel->name, $nick)) { + $ircdata->channel = $channel->name; + $this->_event_rpl_whoreply($ircdata); + } + } + } else { + if (!$this->isJoined($ircdata->channel, $nick)) { + return; + } + + $channel = &$this->_channels[strtolower($ircdata->channel)]; + + $user = new Net_SmartIRC_channeluser(); + $user->ident = $ircdata->rawmessageex[4]; + $user->host = $ircdata->rawmessageex[5]; + $user->server = $ircdata->rawmessageex[6]; + $user->nick = $ircdata->rawmessageex[7]; + + $user->ircop = false; + $user->founder = false; + $user->admin = false; + $user->op = false; + $user->hop = false; + $user->voice = false; + + $usermode = $ircdata->rawmessageex[8]; + $usermodelength = strlen($usermode); + for ($i = 0; $i < $usermodelength; $i++) { + switch ($usermode[$i]) { + case 'H': + $user->away = false; + break; + case 'G': + $user->away = true; + break; + case '*': + $user->ircop = true; + break; + case '~': + $user->founder = true; + break; + case '&': + $user->admin = true; + break; + case '@': + $user->op = true; + break; + case '%': + $user->hop = true; + break; + case '+': + $user->voice = true; + break; + } + $user->modes .= $usermode[$i]; + } + + $user->hopcount = substr($ircdata->rawmessageex[9], 1); + $user->realname = implode(array_slice($ircdata->rawmessageex, 10), ' '); + + $this->_adduser($channel, $user); + } + } + } + + function _event_rpl_namreply(&$ircdata) + { + if ($this->_channelsyncing == true) { + $channel = &$this->_channels[strtolower($ircdata->channel)]; + + $userarray = explode(' ', rtrim($ircdata->message)); + $userarraycount = count($userarray); + for ($i = 0; $i < $userarraycount; $i++) { + $user = new Net_SmartIRC_channeluser(); + + $usermode = substr($userarray[$i], 0, 1); + switch ($usermode) { + case '~': + $user->founder = true; + $user->nick = substr($userarray[$i], 1); + break; + case '&': + $user->admin = true; + $user->nick = substr($userarray[$i], 1); + break; + case '@': + $user->op = true; + $user->nick = substr($userarray[$i], 1); + break; + case '%': + $user->hop = true; + $user->nick = substr($userarray[$i], 1); + break; + case '+': + $user->voice = true; + $user->nick = substr($userarray[$i], 1); + break; + default: + $user->nick = $userarray[$i]; + } + $user->modes .= $usermode[$i]; + + $this->_adduser($channel, $user); + } + } + } + + function _event_rpl_banlist(&$ircdata) + { + if ($this->_channelsyncing == true && $this->isJoined($ircdata->channel)) { + $channel = &$this->_channels[strtolower($ircdata->channel)]; + $hostmask = $ircdata->rawmessageex[4]; + $channel->bans[$hostmask] = true; + } + } + + function _event_rpl_endofbanlist(&$ircdata) + { + if ($this->_channelsyncing == true && $this->isJoined($ircdata->channel)) { + $channel = &$this->getChannel($ircdata->channel); + if ($channel->synctime_stop == 0) { + // we received end of banlist and the stop timestamp is not set yet + $microint = $this->_microint(); + $channel->synctime_stop = $microint; + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: synctime_stop for '.$ircdata->channel.' set to: '.$microint, __FILE__, __LINE__); + + $channel->synctime = ((float)$channel->synctime_stop - (float)$channel->synctime_start); + $this->log(SMARTIRC_DEBUG_CHANNELSYNCING, 'DEBUG_CHANNELSYNCING: synced channel '.$ircdata->channel.' in '.round($channel->synctime, 2).' secs', __FILE__, __LINE__); + } + } + } + + function _event_rpl_topic(&$ircdata) + { + if ($this->_channelsyncing == true) { + $channel = &$this->_channels[strtolower($ircdata->channel)]; + $topic = substr(implode(array_slice($ircdata->rawmessageex, 4), ' '), 1); + $channel->topic = $topic; + } + } + + /* err_ */ + function _event_err_nicknameinuse(&$ircdata) + { + $this->_nicknameinuse(); + } +} +?> diff --git a/lib/Net_SmartIRC/README b/lib/Net_SmartIRC/README new file mode 100644 index 000000000..227d0166b --- /dev/null +++ b/lib/Net_SmartIRC/README @@ -0,0 +1,88 @@ +/** + * $Id$ + * $Revision$ + * $Author$ + * $Date$ + */ + +Net_SmartIRC +---------------- +What is this? +Net_SmartIRC is a PHP class for communication with IRC networks conforming to +RFC 2812 -- an API that handles all IRC protocol messages. This class is +designed for creating IRC bots, chatting, and showing IRC-related info on +web pages. + +official PEAR package page: +https://pear.php.net/package/Net_SmartIRC/ + +files included in SmartIRC +-------------------------- +SmartIRC.php +The class itself. + +FEATURES +A full list of features that SmartIRC includes + +CHANGELOG +Listing of changes between all versions. + +README +this file + +LICENSE +The license of Net_SmartIRC. + +CREDITS +Creditlist with people that work/help on Net_SmartIRC. + +SmartIRC/ + defines.php + Nessesary IRC related defines (IRC reply codes). + + messagehandler.php + All defined messagehandler that SmartIRC currently uses for channelsynching + and some other API handling. + + irccommands.php + All supported IRC commands (like join/part/kick/etc..) + +docs/ + DOCUMENTATION + Appendix to the HTML documention for developers. + + HOWTO + Mini howto with detailed information, step by step. + + HTML/ + index.html + the full documenation of SmartIRC + +examples/ + example.php + An example of how you can use this class for a mini php bot. + + example2.php + This example shows how to display the amount of users in a specific + IRC channel on your homepage. + + example3.php + This bot echos the oplist if !ops is said on the channel. + + example4.php + This bot checks all realnames of people that are on the channel + and displays the result. + + example5.php + This bot can kicks users when !kick NICKNAME is said on the channel. + + example6.php + This example shows how an onjoin greeting can be done with SmartIRC. + + example7.php + This is an example how timers can be used and how to unregister them. + +modules/ + PingFix.php + This is a module you can load with your script to fix a connection keep-alive + issue until it gets fixed in the main class code. diff --git a/lib/Net_SmartIRC/modules/PingFix.php b/lib/Net_SmartIRC/modules/PingFix.php new file mode 100644 index 000000000..b7adf6c4b --- /dev/null +++ b/lib/Net_SmartIRC/modules/PingFix.php @@ -0,0 +1,34 @@ +<?php + +class Net_SmartIRC_module_PingFix +{ + public $name = 'PingFix'; + public $version = '1.0'; + public $description = 'An active-pinging system to keep the bot from dropping the connection'; + public $author = 'Garrett W.'; + public $license = 'LGPL'; + + private $irc; + private $thid; + + function __construct (&$irc) { + $this->irc = $irc; + $this->thid = $this->irc->registerTimehandler( + $this->irc->_rxtimeout/8*1000, $this, 'pingCheck' + ); + } + + function __destruct () { + $this->irc->unregisterTimeid($this->thid); + } + + function pingCheck () { + if (time() - $this->irc->_lastrx > $this->irc->_rxtimeout) { + $this->irc->reconnect(); + $this->irc->_lastrx = time(); + } elseif (time() - $this->irc->_lastrx > $this->irc->_rxtimeout/2) { + $this->irc->_send('PING '.$this->irc->_address, SMARTIRC_CRITICAL); + } + } +} +?>