From 67248fdec310aa1988b2eb88fe73b6e8874c6b5f Mon Sep 17 00:00:00 2001 From: DariusIII Date: Mon, 21 Apr 2014 13:48:05 +0200 Subject: [PATCH] Reverted changes to Prehash. --- bin/monitor.php | 2 +- lib/IRCScraper.php | 398 +- 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 | 3381 +++++++++++++++++ lib/Net_SmartIRC/Net/SmartIRC/defines.php | 235 ++ lib/Net_SmartIRC/Net/SmartIRC/irccommands.php | 558 +++ .../Net/SmartIRC/messagehandler.php | 528 +++ lib/Net_SmartIRC/README | 88 + lib/Net_SmartIRC/modules/PingFix.php | 36 + lib/prehash.php | 353 +- 14 files changed, 6213 insertions(+), 338 deletions(-) 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/bin/monitor.php b/bin/monitor.php index b9305b651..1a2d61a25 100644 --- a/bin/monitor.php +++ b/bin/monitor.php @@ -9,7 +9,7 @@ require_once(dirname(__FILE__) . "/../lib/showsleep.php"); require_once(dirname(__FILE__) . "/../lib/functions.php"); -$version = "0.3r1108"; +$version = "0.3r1109"; $db = new DB(); $functions = new Functions(); diff --git a/lib/IRCScraper.php b/lib/IRCScraper.php index 56e20382f..e74fe7321 100644 --- a/lib/IRCScraper.php +++ b/lib/IRCScraper.php @@ -1,46 +1,47 @@ db = new DB(); $this->functions = new Functions(); $this->groupList = array(); + $this->IRC = $irc; + // Use the PingFix module. + new Net_SmartIRC_module_PingFix($irc); + if ($debug) { + $this->IRC->setDebug(SMARTIRC_DEBUG_ALL); + } $this->serverType = $serverType; $this->silent = $silent; - $this->_debug = $debug; $this->resetPreVariables(); - $this->startScraping(); + $this->startScraping($socket); + } + + /** + * Destruct + */ + public function __destruct() + { + // Close the socket. + if (!is_null($this->IRC)) { + if (!$this->silent) { + echo + 'Disconnecting from ' . + $this->serverType . + '.' . + PHP_EOL; + } + $this->IRC->disconnect(true); + } } /** * Main method for scraping. * - * @access protected + * @param bool $socket Use real sockets or fsock? */ - protected function startScraping() + protected function startScraping(&$socket) { switch($this->serverType) { case 'efnet': @@ -102,7 +123,6 @@ class IRCScraper extends IRCClient $username = SCRAPE_IRC_EFNET_USERNAME; $realname = SCRAPE_IRC_EFNET_REALNAME; $password = SCRAPE_IRC_EFNET_PASSWORD; - $tls = SCRAPE_IRC_EFNET_ENCRYPTION; $channelList = array( // Channel Password. '#alt.binaries.inner-sanctum' => null, @@ -138,6 +158,33 @@ class IRCScraper extends IRCClient $channelList = $newList; unset($newList); } + $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.*?Request.*?Filled!.*?ReqId' . // a.b.moovee a.b.foreign a.b.flac a.b.teevee + '|' . + 'That.*?was.*?awesome.*?Shall.*?ReqId' . // a.b.erotica + '|' . + 'person.*?filling.*?request.*?for:.*?ReqID:' . // a.b.console.ps3 + '|' . + 'NEW.*?\[NDS\].*?PRE:' . // a.b.games.nintendods + '|' . + 'A\s+new\s+NZB\s+has\s+been\s+added:' . // a.b.games.wii a.b.games.xbox360 + '|' . + 'A\s+NZB\s+is\s+available.*?To\s+Download' . // a.b.sony.psp + '|' . + '\s+NZB:\s+http:\/\/scnzb\.eu\/' . // scnzb + //'|' . + //'^\[SBINDEX\]' . // tvnzb + '|' . + '^\[(MOD|OLD|RE|UN)?NUKE\]' . // Nukes. various channels + '|' . + 'added\s+(nuke|reason)\s+info\s+for:' . // Nukes. a.b.games.xbox360 a.b.games.wii + '/i'; break; case 'corrupt': @@ -147,8 +194,8 @@ class IRCScraper extends IRCClient $username = SCRAPE_IRC_CORRUPT_USERNAME; $realname = SCRAPE_IRC_CORRUPT_REALNAME; $password = SCRAPE_IRC_CORRUPT_PASSWORD; - $tls = SCRAPE_IRC_CORRUPT_ENCRYPTION; $channelList = array('#pre' => null); + $regex = '/PRE:.+?\[.+?\]|^(MOD|OLD|RE|UN)?NUKE:\s+/i'; // #pre break; case 'zenet': @@ -158,16 +205,50 @@ class IRCScraper extends IRCClient $username = SCRAPE_IRC_ZENET_USERNAME; $realname = SCRAPE_IRC_ZENET_REALNAME; $password = SCRAPE_IRC_ZENET_PASSWORD; - $tls = SCRAPE_IRC_ZENET_ENCRYPTION; $channelList = array('#Pre' => null); + $regex = '/^\(PRE\)\s+\(|^\((MOD|OLD|RE|UN)?NUKE\)\s+/i'; // #Pre break; default: return; } + $versions = array( + 'HexChat 2.9.6 [x64] / Windows ' . rand(7, 8) . ' [' . rand(2, 3) . '.' . rand(0, 99) . 'GHz]', + 'irssi v0.8.' . rand(10, 16) . ' - running on Linux i686', + 'KVIrc 4.2.0', + 'mIRC 7.32 Khaled Mardam-Bey', + 'mIRC v6.31 Khaled Mardam-Bey', + 'HydraIRC v0.3.165', + 'xchat 2.8. ' . rand(6, 9) . ' Ubuntu', + 'ZNC 1.' . rand(0, 2) . ' - http://znc.in', + ); + + // Change the CTCP string. + $this->IRC->setCtcpVersion($versions[mt_rand(0, 6)]); + unset($versions); + + // 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 20 seconds before reconnecting. + $this->IRC->setReconnectdelay(200000); + + // Try 4 times before giving up. + $this->IRC->setAutoRetryMax(4); + + // If a network error happens, automatically reconnect. + $this->IRC->setAutoReconnect(true); + // Connect to IRC. - if ($this->connect($server, $port, $tls) === false) { + $connection = $this->IRC->connect($server, $port); + if ($connection === false) { exit ( 'Error connecting to (' . $server . @@ -179,7 +260,19 @@ class IRCScraper extends IRCClient } // Login to IRC. - if ($this->login($nickname, $username, $realname, $password) === false) { + if (!$this->IRC->login( + // Nick name. + $nickname, + // Real name. + $realname, + // User mode. + 0, + // User name. + $username, + // Password. + (empty($password) ? null : $password) + ) + ) { exit('Error logging in to: (' . $server . ':' . $port . ') nickname: (' . $nickname . '). Verify your connection information, you might also be banned from this server or there might have been a connection issue.' . @@ -188,7 +281,9 @@ class IRCScraper extends IRCClient } // Join channels. - $this->joinChannels($channelList); + if (!$this->IRC->joinChannels($channelList)) { + exit('Error joining channels on (' . $server . ':' . $port . ') might be an issue with the server.' . PHP_EOL); + } if (!$this->silent) { echo @@ -204,8 +299,11 @@ class IRCScraper extends IRCClient PHP_EOL; } - // Scan incoming IRC messages. - $this->readIncoming(); + // Wait for action handlers. + $this->IRC->listen(); + + // If we return from action handlers, disconnect from IRC. + $this->IRC->disconnect(); } /** @@ -216,8 +314,6 @@ class IRCScraper extends IRCClient * @param int $similarity * * @return bool - * - * @access protected */ protected function checkSimilarity(&$word1, $word2, $similarity = 49) { @@ -229,105 +325,107 @@ class IRCScraper extends IRCClient } /** - * Check channel and poster, send message to right method. - * access protected + * Check channel and poster, send to right method. + * + * @param object $irc + * @param object $data */ - protected function processChannelMessages() + public function check_type($irc, $data) { - $channel = strtolower($this->_channelData['channel']); - $poster = strtolower($this->_channelData['nickname']); + $channel = strtolower($data->channel); + $poster = strtolower($data->nick); switch($channel) { case '#alt.binaries.inner-sanctum': if ($this->checkSimilarity($poster, 'sanctum')) { - $this->inner_sanctum(); + $this->inner_sanctum($data->message); } break; case '#alt.binaries.erotica': if ($this->checkSimilarity($poster, 'ginger') || $this->checkSimilarity($poster, 'g1nger')) { - $this->ab_erotica(); + $this->ab_erotica($data->message); } break; case '#alt.binaries.flac': if ($this->checkSimilarity($poster, 'abflac')) { - $this->ab_flac(); + $this->ab_flac($data->message); } break; case '#alt.binaries.moovee': if ($this->checkSimilarity($poster, 'abking')) { - $this->ab_moovee(); + $this->ab_moovee($data->message); } break; case '#alt.binaries.teevee': if ($this->checkSimilarity($poster, 'abgod')) { - $this->ab_teevee(); + $this->ab_teevee($data->message); } break; case '#pre': if ($this->checkSimilarity($poster, 'theannouncer')) { - $this->zenet_pre(); + $this->zenet_pre($data->message); } else if ($this->checkSimilarity($poster, 'pr3')) { - $this->corrupt_pre(); + $this->corrupt_pre($data->message); } break; case '#alt.binaries.foreign': if ($this->checkSimilarity($poster, 'abqueen')) { - $this->ab_foreign(); + $this->ab_foreign($data->message); } break; case '#alt.binaries.console.ps3': if ($this->checkSimilarity($poster, 'binarybot')) { - $this->ab_console_ps3(); + $this->ab_console_ps3($data->message); } break; case '#alt.binaries.games.nintendods': if ($this->checkSimilarity($poster, 'binarybot')) { - $this->ab_games_nintendods(); + $this->ab_games_nintendods($data->message); } break; case '#alt.binaries.games.wii': if ($this->checkSimilarity($poster, 'binarybot') || $this->checkSimilarity($poster, 'googlebot')) { - $this->ab_games_wii($poster); + $this->ab_games_wii($data->message, $poster); } break; case '#alt.binaries.games.xbox360': if ($this->checkSimilarity($poster, 'binarybot') || $this->checkSimilarity($poster, 'googlebot')) { - $this->ab_games_xbox360($poster); + $this->ab_games_xbox360($data->message, $poster); } break; case '#alt.binaries.sony.psp': if ($this->checkSimilarity($poster, 'googlebot')) { - $this->ab_sony_psp(); + $this->ab_sony_psp($data->message); } break; case '#scnzb': if ($this->checkSimilarity($poster, 'nzbs')) { - $this->scnzb(); + $this->scnzb($data->message); } break; /*case '#tvnzb': if ($this->checkSimilarity($poster, 'tweetie')) { - $this->tvnzb(); + $this->tvnzb($data->message); } break;*/ default: if ($this->checkSimilarity($poster, 'alt-bin')) { - $this->alt_bin($channel); + $this->alt_bin($data->message, $channel); } } } @@ -336,8 +434,6 @@ class IRCScraper extends IRCClient * Get pre date from wD xH yM zS ago string. * * @param $agoString - * - * @access protected */ protected function getTimeFromAgo($agoString) { @@ -367,13 +463,10 @@ class IRCScraper extends IRCClient * Go through regex matches, find PRE info. * * @param array $matches - * - * @access protected */ protected function siftMatches(&$matches) { $this->CurPre['md5'] = $this->db->escapeString(md5($matches['title'])); - $this->CurPre['sha1'] = $this->db->escapeString(sha1($matches['title'])); $this->CurPre['title'] = $matches['title']; if (isset($matches['reqid'])) { @@ -392,19 +485,19 @@ class IRCScraper extends IRCClient $this->nuked = true; switch ($matches['nuke']) { case 'NUKE': - $this->CurPre['nuked'] = PreDb::PRE_NUKED; + $this->CurPre['nuked'] = PreHash::PRE_NUKED; break; case 'UNNUKE': - $this->CurPre['nuked'] = PreDb::PRE_UNNUKED; + $this->CurPre['nuked'] = PreHash::PRE_UNNUKED; break; case 'MODNUKE': - $this->CurPre['nuked'] = PreDb::PRE_MODNUKE; + $this->CurPre['nuked'] = PreHash::PRE_MODNUKE; break; case 'RENUKE': - $this->CurPre['nuked'] = PreDb::PRE_RENUKED; + $this->CurPre['nuked'] = PreHash::PRE_RENUKED; break; case 'OLDNUKE': - $this->CurPre['nuked'] = PreDb::PRE_OLDNUKE; + $this->CurPre['nuked'] = PreHash::PRE_OLDNUKE; break; } } @@ -428,20 +521,20 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #a.b.erotica * - * @access protected + * @param string $message The IRC message to parse. */ - protected function ab_erotica() + protected function ab_erotica(&$message) { //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] //That was awesome [*Anonymous*] Shall we do it again? ReqId:[326663] [x264] [FULL 53x100MB Young.Ripe.Mellons.10.XXX.720P.WEBRIP.X264-GUSH] Filenames:[gush.yrmellons10] Comments:[1] Watchers:[0] Total Size:[4974MB] Points Earned:[354] [Pred 7m 5s ago] [NUKED] - if (preg_match('/ReqId:\[(?P\d+)\]\s+\[.+?\]\s+\[FULL\s+(?P\d+x\d+[KMGTP]?B)\s+(?P.+?)\].+?Size:\[(?P<size>.+?)\](.+?\[Pred\s+(?P<predago>.+?)\s+ago\])?(.+?\[(?P<nuke>(MOD|OLD|RE|UN)?NUKE)D\])?/i', $this->_channelData['message'], $matches)) { + if (preg_match('/ReqId:\[(?P<reqid>\d+)\]\s+\[.+?\]\s+\[FULL\s+(?P<files>\d+x\d+[KMGTP]?B)\s+(?P<title>.+?)\].+?Size:\[(?P<size>.+?)\](.+?\[Pred\s+(?P<predago>.+?)\s+ago\])?(.+?\[(?P<nuke>(MOD|OLD|RE|UN)?NUKE)D\])?/i', $message, $matches)) { $this->CurPre['source'] = '#a.b.erotica'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.erotica'); $this->CurPre['category'] = 'XXX'; $this->siftMatches($matches); //[NUKE] ReqId:[326663] [Young.Ripe.Mellons.10.XXX.720P.WEBRIP.X264-GUSH] Reason:[selfdupe.2014-03-09] - } elseif (preg_match('/\[(?P<nuke>(MOD|OLD|RE|UN)?NUKE)\]\s+ReqId:\[(?P<reqid>\d+)\]\s+\[(?P<title>.+?)\]\s+Reason:\[(?P<reason>.+?)]/i', $this->_channelData['message'], $matches)) { + } elseif (preg_match('/\[(?P<nuke>(MOD|OLD|RE|UN)?NUKE)\]\s+ReqId:\[(?P<reqid>\d+)\]\s+\[(?P<title>.+?)\]\s+Reason:\[(?P<reason>.+?)]/i', $message, $matches)) { $this->CurPre['source'] = '#a.b.erotica'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.erotica'); $this->CurPre['category'] = 'XXX'; @@ -452,12 +545,12 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #a.b.flac * - * @access protected + * @param string $message The IRC message to parse. */ - protected function ab_flac() + protected function ab_flac(&$message) { //Thank You [*Anonymous*] Request Filled! ReqId:[42614] [FULL 10x15MB You_Blew_It-Keep_Doing_What_Youre_Doing-CD-FLAC-2014-WRE] Requested by:[*Anonymous* 21s ago] Comments:[0] Watchers:[0] Points Earned:[10] [Pred 3m 16s ago] - if (preg_match('/Request\s+Filled!\s+ReqId:\[(?P<reqid>\d+)\]\s+\[FULL\s+(?P<files>\d+x\d+[KMGTP]?B)\s+(?P<title>.+?)\].+?\[Pred\s+(?P<predago>.+?)\s+ago\]/i', $this->_channelData['message'], $matches)) { + if (preg_match('/Request\s+Filled!\s+ReqId:\[(?P<reqid>\d+)\]\s+\[FULL\s+(?P<files>\d+x\d+[KMGTP]?B)\s+(?P<title>.+?)\].+?\[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->CurPre['category'] = 'FLAC'; @@ -468,19 +561,19 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #a.b.moovee * - * @access protected + * @param string $message The IRC message to parse. */ - protected function ab_moovee() + 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+(?P<files>\d+x\d+[MGPTK]?B)\s+(?P<title>.+?)\]\s+.+?\[Pred\s+(?P<predago>.+?)\s+ago\]/i', $this->_channelData['message'], $matches)) { + if (preg_match('/ReqId:\[(?P<reqid>\d+)\]\s+\[FULL\s+(?P<files>\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->CurPre['category'] = 'Movies'; $this->siftMatches($matches); //[NUKE] ReqId:[130274] [NOVA.The.Bibles.Buried.Secrets.2008.DVDRip.XviD-FiCO] Reason:[field.shifted_oi47.tinypic.com.24evziv.jpg] - } else if (preg_match('/\[(?P<nuke>(MOD|OLD|RE|UN)?NUKE)\]\s+ReqId:\[(?P<reqid>\d+)\]\s+\[(?P<title>.+?)\]\s+Reason:\[(?P<reason>.+?)\]/', $this->_channelData['message'], $matches)) { + } else if (preg_match('/\[(?P<nuke>(MOD|OLD|RE|UN)?NUKE)\]\s+ReqId:\[(?P<reqid>\d+)\]\s+\[(?P<title>.+?)\]\s+Reason:\[(?P<reason>.+?)\]/', $message, $matches)) { $this->CurPre['source'] = '#a.b.moovee'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.moovee'); $this->CurPre['category'] = 'Movies'; @@ -491,12 +584,12 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #a.b.foreign * - * @access protected + * @param string $message The IRC message to parse. */ - protected function ab_foreign() + protected function ab_foreign(&$message) { //Thank You [*Anonymous*] Request Filled! ReqId:[61525] [Movie] [FULL 95x50MB Wadjda.2012.PAL.MULTI.DVDR-VIAZAC] Requested by:[*Anonymous* 5m 13s ago] Comments:[0] Watchers:[0] Points Earned:[317] [Pred 8m 27s ago] - if (preg_match('/ReqId:\[(?P<reqid>\d+)\]\s+\[(?P<category>.+?)\]\s+\[FULL\s+(?P<files>\d+x\d+[MGPTK]?B)\s+(?P<title>.+?)\]\s+.+?\[Pred\s+(?P<predago>.+?)\s+ago\]/i', $this->_channelData['message'], $matches)) { + if (preg_match('/ReqId:\[(?P<reqid>\d+)\]\s+\[(?P<category>.+?)\]\s+\[FULL\s+(?P<files>\d+x\d+[MGPTK]?B)\s+(?P<title>.+?)\]\s+.+?\[Pred\s+(?P<predago>.+?)\s+ago\]/i', $message, $matches)) { $this->CurPre['source'] = '#a.b.foreign'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.mom'); $this->siftMatches($matches); @@ -506,12 +599,12 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #a.b.teevee * - * @access protected + * @param string $message The IRC message to parse. */ - protected function ab_teevee() + protected function ab_teevee(&$message) { //Thank You [*Anonymous*] Request Filled! ReqId:[183520] [FULL 19x50MB Louis.Therouxs.LA.Stories.S01E02.720p.HDTV.x264-FTP] Requested by:[*Anonymous* 53s ago] Comments:[0] Watchers:[0] Points Earned:[64] [Pred 3m 45s ago] - if (preg_match('/Request\s+Filled!\s+ReqId:\[(?P<reqid>\d+)\]\s+\[FULL\s+(?P<files>\d+x\d+[KMGPT]?B)\s+(?P<title>.+?)\].+?\[Pred\s+(?P<predago>.+?)\s+ago\]/i', $this->_channelData['message'], $matches)) { + if (preg_match('/Request\s+Filled!\s+ReqId:\[(?P<reqid>\d+)\]\s+\[FULL\s+(?P<files>\d+x\d+[KMGPT]?B)\s+(?P<title>.+?)\].+?\[Pred\s+(?P<predago>.+?)\s+ago\]/i', $message, $matches)) { $this->CurPre['source'] = '#a.b.teevee'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.teevee'); $this->CurPre['category'] = 'TV'; @@ -519,7 +612,7 @@ class IRCScraper extends IRCClient //[NUKE] ReqId:[183497] [From.Dusk.Till.Dawn.S01E01.720p.HDTV.x264-BATV] Reason:[bad.ivtc.causing.jerky.playback.due.to.dupe.and.missing.frames.in.segment.from.16m.to.30m] //[UNNUKE] ReqId:[183449] [The.Biggest.Loser.AU.S09E29.PDTV.x264-RTA] Reason:[get.samplefix] - } else if (preg_match('/\[(?P<nuke>(MOD|OLD|RE|UN)?NUKE)\]\s+ReqId:\[(?P<reqid>\d+)\]\s+\[(?P<title>.+?)\]\s+Reason:\[(?P<reason>.+?)\]/i', $this->_channelData['message'], $matches)) { + } else if (preg_match('/\[(?P<nuke>(MOD|OLD|RE|UN)?NUKE)\]\s+ReqId:\[(?P<reqid>\d+)\]\s+\[(?P<title>.+?)\]\s+Reason:\[(?P<reason>.+?)\]/i', $message, $matches)) { $this->CurPre['source'] = '#a.b.teevee'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.teevee'); $this->CurPre['category'] = 'TV'; @@ -530,12 +623,12 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #a.b.console.ps3 * - * @access protected + * @param string $message The IRC message to parse. */ - protected function ab_console_ps3() + protected function ab_console_ps3(&$message) { //[Anonymous person filling request for: FULL 56 Ragnarok.Odyssey.ACE.PS3-iMARS NTSC BLURAY imars-ragodyace-ps3 56x100MB by Khaine13 on 2014-03-29 13:14:12][ReqID: 4888][You get a bonus of 6 for a total points earning of: 62 for filling with 10% par2s!][Your score will be adjusted once you have -filled 4888] - if (preg_match('/\s+FULL\s+\d+\s+(?P<title>.+?)\s+(?P<files>\d+x\d+[KMGTP]?B)\s+.+?\]\[ReqID:\s+(?P<reqid>\d+)\]\[/i', $this->_channelData['message'], $matches)) { + if (preg_match('/\s+FULL\s+\d+\s+(?P<title>.+?)\s+(?P<files>\d+x\d+[KMGTP]?B)\s+.+?\]\[ReqID:\s+(?P<reqid>\d+)\]\[/i', $message, $matches)) { $this->CurPre['source'] = '#a.b.console.ps3'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.console.ps3'); $this->CurPre['category'] = 'PS3'; @@ -546,14 +639,13 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #a.b.games.wii * + * @param string $message The IRC message to parse. * @param string $poster The name of the poster. - * - * @access protected */ - protected function ab_games_wii(&$poster) + protected function ab_games_wii(&$message, &$poster) { //A new NZB has been added: Go_Diego_Go_Great_Dinosaur_Rescue_PAL_WII-ZER0 PAL DVD5 zer0-gdggdr 93x50MB - To download this file: -sendnzb 12811 - if ($this->checkSimilarity($poster, 'googlebot') && preg_match('/A\s+new\s+NZB\s+has\s+been\s+added:\s+(?P<title>.+?)\s+.+?(?P<files>\d+x\d+[KMGTP]?B)\s+-\s+To.+?file:\s+-sendnzb\s+(?P<reqid>\d+)\s*/i', $this->_channelData['message'], $matches)) { + if ($this->checkSimilarity($poster, 'googlebot') && preg_match('/A\s+new\s+NZB\s+has\s+been\s+added:\s+(?P<title>.+?)\s+.+?(?P<files>\d+x\d+[KMGTP]?B)\s+-\s+To.+?file:\s+-sendnzb\s+(?P<reqid>\d+)\s*/i', $message, $matches)) { $matches['nuke'] = 'NUKE'; $this->CurPre['source'] = '#a.b.games.wii'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.games.wii'); @@ -561,7 +653,7 @@ class IRCScraper extends IRCClient $this->siftMatches($matches); //[kiczek added reason info for: Samurai_Shodown_IV_-_Amakusas_Revenge_USA_VC_NEOGEO_Wii-OneUp][VCID: 5027][Value: bad.dirname_bad.filenames_get.repack] - } else if ($this->checkSimilarity($poster, 'binarybot') && preg_match('/added\s+(nuke|reason)\s+info\s+for:\s+(?P<title>.+?)\]\[VCID:\s+(?P<reqid>\d+)\]\[Value:\s+(?P<reason>.+?)\]/i', $this->_channelData['message'], $matches)) { + } else if ($this->checkSimilarity($poster, 'binarybot') && preg_match('/added\s+(nuke|reason)\s+info\s+for:\s+(?P<title>.+?)\]\[VCID:\s+(?P<reqid>\d+)\]\[Value:\s+(?P<reason>.+?)\]/i', $message, $matches)) { $matches['nuke'] = 'NUKE'; $this->CurPre['source'] = '#a.b.games.wii'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.games.wii'); @@ -573,14 +665,13 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #a.b.games.xbox360 * + * @param string $message The IRC message to parse. * @param string $poster The name of the poster. - * - * @access protected */ - protected function ab_games_xbox360(&$poster) + protected function ab_games_xbox360(&$message, &$poster) { //A new NZB has been added: South.Park.The.Stick.of.Truth.PAL.XBOX360-COMPLEX PAL DVD9 complex-south.park.sot 74x100MB - To download this file: -sendnzb 19909 - if ($this->checkSimilarity($poster, 'googlebot') && preg_match('/A\s+new\s+NZB\s+has\s+been\s+added:\s+(?P<title>.+?)\s+.+?(?P<files>\d+x\d+[KMGTP]?B)\s+-\s+To.+?file:\s+-sendnzb\s+(?P<reqid>\d+)\s*/i', $this->_channelData['message'], $matches)) { + if ($this->checkSimilarity($poster, 'googlebot') && preg_match('/A\s+new\s+NZB\s+has\s+been\s+added:\s+(?P<title>.+?)\s+.+?(?P<files>\d+x\d+[KMGTP]?B)\s+-\s+To.+?file:\s+-sendnzb\s+(?P<reqid>\d+)\s*/i', $message, $matches)) { $matches['nuke'] = 'NUKE'; $this->CurPre['source'] = '#a.b.games.xbox360'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.games.xbox360'); @@ -588,7 +679,7 @@ class IRCScraper extends IRCClient $this->siftMatches($matches); //[egres added nuke info for: Injustice.Gods.Among.Us.XBOX360-SWAG][GameID: 7088][Value: Y] - } else if ($this->checkSimilarity($poster, 'binarybot') && preg_match('/added\s+(nuke|reason)\s+info\s+for:\s+(?P<title>.+?)\]\[VCID:\s+(?P<reqid>\d+)\]\[Value:\s+(?P<reason>.+?)\]/i', $this->_channelData['message'], $matches)) { + } else if ($this->checkSimilarity($poster, 'binarybot') && preg_match('/added\s+(nuke|reason)\s+info\s+for:\s+(?P<title>.+?)\]\[VCID:\s+(?P<reqid>\d+)\]\[Value:\s+(?P<reason>.+?)\]/i', $message, $matches)) { $matches['nuke'] = 'NUKE'; $this->CurPre['source'] = '#a.b.games.xbox360'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.games.xbox360'); @@ -600,12 +691,12 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #a.b.sony.psp * - * @access protected + * @param string $message The IRC message to parse. */ - protected function ab_sony_psp() + protected function ab_sony_psp(&$message) { //A NZB is available: Satomi_Hakkenden_Hachitama_no_Ki_JPN_PSP-MOEMOE JAP UMD moe-satomi 69x20MB - To download this file: -sendnzb 21924 - if (preg_match('/A NZB is available:\s(?P<title>.+?)\s+.+?(?P<files>\d+x\d+[KMGPT]?B)\s+-.+?file:\s+-sendnzb\s+(?P<reqid>\d+)\s*/i', $this->_channelData['message'], $matches)) { + if (preg_match('/A NZB is available:\s(?P<title>.+?)\s+.+?(?P<files>\d+x\d+[KMGPT]?B)\s+-.+?file:\s+-sendnzb\s+(?P<reqid>\d+)\s*/i', $message, $matches)) { $this->CurPre['source'] = '#a.b.sony.psp'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.sony.psp'); $this->CurPre['category'] = 'PSP'; @@ -616,12 +707,12 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #a.b.games_nintendods * - * @access protected + * @param string $message The IRC message to parse. */ - protected function ab_games_nintendods() + protected function ab_games_nintendods(&$message) { //NEW [NDS] PRE: Honda_ATV_Fever_USA_NDS-EXiMiUS - if (preg_match('/NEW\s+\[NDS\]\s+PRE:\s+(?P<title>.+)/i', $this->_channelData['message'], $matches)) { + if (preg_match('/NEW\s+\[NDS\]\s+PRE:\s+(?P<title>.+)/i', $message, $matches)) { $this->CurPre['source'] = '#a.b.games.nintendods'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.games.nintendods'); $this->CurPre['category'] = 'NDS'; @@ -632,12 +723,12 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #scnzb (boneless) * - * @access protected + * @param string $message The IRC message to parse. */ - protected function scnzb() + protected function scnzb(&$message) { //[Complete][512754] Formula1.2014.Malaysian.Grand.Prix.Team.Principals.Press.Conference.720p.HDTV.x264-W4F NZB: http://scnzb.eu/1pgOmwj - if (preg_match('/\[Complete\]\[(?P<reqid>\d+)\]\s*(?P<title>.+?)\s+NZB:/i', $this->_channelData['message'], $matches)) { + if (preg_match('/\[Complete\]\[(?P<reqid>\d+)\]\s*(?P<title>.+?)\s+NZB:/i', $message, $matches)) { $this->CurPre['source'] = '#scnzb'; $this->CurPre['groupid'] = $this->getGroupID('alt.binaries.boneless'); $this->siftMatches($matches); @@ -647,35 +738,35 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #tvnzb (sickbeard) * - * @access protected + * @param string $message The IRC message to parse. */ -/* protected function tvnzb() - { - //[SBINDEX] Rev.S03E02.HDTV.x264-TLA :: TV > HD :: 210.13 MB :: Aired: 31/Mar/2014 :: http://lolo.sickbeard.com/getnzb/aa10bcef235c604612dd61b0627ae25f.nzb - if (preg_match('/\[SBINDEX\]\s+(?P<title>.+?)\s+::\s+(?P<sbcat>.+?)\s+::\s+(?P<size>.+?)\s+::\s+Aired/i', $this->_channelData['message'], $matches)) { - if (preg_match('/^(?P<first>.+?)\s+>\s+(?P<last>.+?)$/', $matches['sbcat'], $match)) { - $matches['category'] = $match['first'] . '-' . $match['last']; + /* protected function tvnzb(&$message) + { + //[SBINDEX] Rev.S03E02.HDTV.x264-TLA :: TV > HD :: 210.13 MB :: Aired: 31/Mar/2014 :: http://lolo.sickbeard.com/getnzb/aa10bcef235c604612dd61b0627ae25f.nzb + if (preg_match('/\[SBINDEX\]\s+(?P<title>.+?)\s+::\s+(?P<sbcat>.+?)\s+::\s+(?P<size>.+?)\s+::\s+Aired/i', $message, $matches)) { + if (preg_match('/^(?P<first>.+?)\s+>\s+(?P<last>.+?)$/', $matches['sbcat'], $match)) { + $matches['category'] = $match['first'] . '-' . $match['last']; + } + $this->CurPre['source'] = '#tvnzb'; + $this->siftMatches($matches); } - $this->CurPre['source'] = '#tvnzb'; - $this->siftMatches($matches); - } - }*/ + }*/ /** * Gets new PRE from #Pre on zenet * - * @access protected + * @param string $message The IRC message to parse. */ - protected function zenet_pre() + 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>.+?)\)$/i', $this->_channelData['message'], $matches)) { + if (preg_match('/^\(PRE\)\s+\((?P<category>.+?)\)\s+\((?P<title>.+?)\)$/i', $message, $matches)) { $this->CurPre['source'] = '#Pre@zenet'; $this->siftMatches($matches); //(NUKE) (German_TOP100_Single_Charts_31_03_2014-MCG) (selfmade.compilations.not.allowed) //(UNNUKE) (The.Biggest.Loser.AU.S09E29.PDTV.x264-RTA) (get.samplefix) - } else if (preg_match('/\((?P<nuke>(MOD|OLD|RE|UN)?NUKE)\)\s+\((?P<title>.+?)\)\s+\((?P<reason>.+?)\)/i', $this->_channelData['message'], $matches)) { + } else if (preg_match('/\((?P<nuke>(MOD|OLD|RE|UN)?NUKE)\)\s+\((?P<title>.+?)\)\s+\((?P<reason>.+?)\)/i', $message, $matches)) { $this->CurPre['source'] = '#Pre@zenet'; $this->siftMatches($matches); } @@ -684,19 +775,19 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #pre on Corrupt-net * - * @access protected + * @param string $message The IRC message to parse. */ - protected function corrupt_pre() + 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', $this->_channelData['message'], $matches)) { + if (preg_match('/^PRE:\s+\[(?P<category>.+?)\]\s+(?P<title>.+)$/i', $message, $matches)) { $this->CurPre['source'] = '#pre@corrupt'; $this->siftMatches($matches); //NUKE: Miclini-Sunday_Morning_P1-DIRFIX-DAB-03-30-2014-G4E [dirfix.must.state.name.of.release.being.fixed] [EthNet] //UNNUKE: Youssoupha-Sur_Les_Chemins_De_Retour-FR-CD-FLAC-2009-0MNi [flac.rule.4.12.states.ENGLISH.artist.and.title.must.be.correct.and.this.is.not.ENGLISH] [LocalNet] //MODNUKE: Miclini-Sunday_Morning_P1-DIRFIX-DAB-03-30-2014-G4E [nfo.must.state.name.of.release.being.fixed] [EthNet] - } else if (preg_match('/(?P<nuke>(MOD|OLD|RE|UN)?NUKE):\s+(?P<title>.+?)\s+\[(?P<reason>.+?)\]/i', $this->_channelData['message'], $matches)) { + } else if (preg_match('/(?P<nuke>(MOD|OLD|RE|UN)?NUKE):\s+(?P<title>.+?)\s+\[(?P<reason>.+?)\]/i', $message, $matches)) { $this->CurPre['source'] = '#pre@corrupt'; $this->siftMatches($matches); } @@ -705,12 +796,12 @@ class IRCScraper extends IRCClient /** * Gets new PRE from #a.b.inner-sanctum. * - * @access protected + * @param string $message The IRC message to parse. */ - protected function inner_sanctum() + protected function inner_sanctum(&$message) { //[FILLED] [ 341953 | Emilie_Simon-Mue-CD-FR-2014-JUST | 16x79 | MP3 | *Anonymous* ] [ Pred 10m 54s ago ] - if (preg_match('/FILLED\]\s+\[\s+(?P<reqid>\d+)\s+\|\s+(?P<title>.+?)\s+\|\s+(?P<files>\d+x\d+)\s+\|\s+(?P<category>.+?)\s+\|\s+.+?\s+\]\s+\[\s+Pred\s+(?P<predago>.+?)\s+ago\s+\]/i', $this->_channelData['message'], $matches)) { + if (preg_match('/FILLED\]\s+\[\s+(?P<reqid>\d+)\s+\|\s+(?P<title>.+?)\s+\|\s+(?P<files>\d+x\d+)\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); @@ -720,14 +811,13 @@ class IRCScraper extends IRCClient /** * Get new PRE from Alt-Bin groups. * + * @param string $message The IRC message from the bot. * @param string $channel The IRC channel name. - * - * @access protected */ - protected function alt_bin(&$channel) + 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> - 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+Files<(?P<files>\d+)>/i', $this->_channelData['message'], $matches)) { + 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+Files<(?P<files>\d+)>/i', $message, $matches)) { $this->CurPre['source'] = str_replace('#alt.binaries', '#a.b', $channel); $this->CurPre['groupid'] = $this->getGroupID(str_replace('#', '', $channel)); $this->siftMatches($matches); @@ -738,12 +828,10 @@ class IRCScraper extends IRCClient * Check if we already have the PRE. * * @return bool True if we already have, false if we don't. - * - * @access protected */ protected function checkForDupe() { - $this->OldPre = $this->db->queryOneRow(sprintf('SELECT category, size FROM predb WHERE md5 = %s', $this->CurPre['md5'])); + $this->OldPre = $this->db->queryOneRow(sprintf('SELECT category, size FROM prehash WHERE md5 = %s', $this->CurPre['md5'])); if ($this->OldPre === false) { $this->insertNewPre(); } else { @@ -753,8 +841,6 @@ class IRCScraper extends IRCClient /** * Insert new PRE into the DB. - * - * @access protected */ protected function insertNewPre() { @@ -762,18 +848,18 @@ class IRCScraper extends IRCClient return; } - $query = 'INSERT INTO predb ('; + $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['reason']) ? 'nukereason, ' : ''); $query .= (!empty($this->CurPre['files']) ? 'files, ' : ''); - $query .= (!empty($this->CurPre['reqid']) ? 'requestid, ' : ''); - $query .= (!empty($this->CurPre['groupid']) ? 'groupid, ' : ''); + $query .= (!empty($this->CurPre['reqid']) ? 'requestID, ' : ''); + $query .= (!empty($this->CurPre['groupid']) ? 'groupID, ' : ''); $query .= (!empty($this->CurPre['nuked']) ? 'nuked, ' : ''); - $query .= 'predate, md5, sha1, title) VALUES ('; + $query .= 'predate, md5, title) VALUES ('; $query .= (!empty($this->CurPre['size']) ? $this->db->escapeString($this->CurPre['size']) . ', ' : ''); $query .= (!empty($this->CurPre['category']) ? $this->db->escapeString($this->CurPre['category']) . ', ' : ''); @@ -785,15 +871,12 @@ class IRCScraper extends IRCClient $query .= (!empty($this->CurPre['nuked']) ? $this->CurPre['nuked'] . ', ' : ''); $query .= (!empty($this->CurPre['predate']) ? $this->CurPre['predate'] . ', ' : 'NOW(), '); - $query .= '%s, %s, %s)'; + $query .= '%s, %s)'; - $this->db->ping(true); - - $this->db->queryExec( + $this->db->exec( sprintf( - $query, + $query, $this->CurPre['md5'], - $this->CurPre['sha1'], $this->db->escapeString($this->CurPre['title']) ) ); @@ -805,8 +888,6 @@ class IRCScraper extends IRCClient /** * Updates PRE data in the DB. - * - * @access protected */ protected function updatePre() { @@ -814,14 +895,14 @@ class IRCScraper extends IRCClient return; } - $query = 'UPDATE predb SET '; + $query = 'UPDATE prehash SET '; $query .= (!empty($this->CurPre['size']) ? 'size = ' . $this->db->escapeString($this->CurPre['size']) . ', ' : ''); $query .= (!empty($this->CurPre['source']) ? 'source = ' . $this->db->escapeString($this->CurPre['source']) . ', ' : ''); $query .= (!empty($this->CurPre['files']) ? 'files = ' . $this->db->escapeString($this->CurPre['files']) . ', ' : ''); $query .= (!empty($this->CurPre['reason']) ? 'nukereason = ' . $this->db->escapeString($this->CurPre['reason']) . ', ' : ''); - $query .= (!empty($this->CurPre['reqid']) ? 'requestid = ' . $this->CurPre['reqid'] . ', ' : ''); - $query .= (!empty($this->CurPre['groupid']) ? 'groupid = ' . $this->CurPre['groupid'] . ', ' : ''); + $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'] . ', ' : ''); $query .= (!empty($this->CurPre['nuked']) ? 'nuked = ' . $this->CurPre['nuked'] . ', ' : ''); $query .= ( @@ -830,16 +911,14 @@ class IRCScraper extends IRCClient : '' ); - if ($query === 'UPDATE predb SET '){ + if ($query === 'UPDATE prehash SET ') { return; } $query .= 'title = ' . $this->db->escapeString($this->CurPre['title']); $query .= ' WHERE md5 = ' . $this->CurPre['md5']; - $this->db->ping(true); - - $this->db->queryExec($query); + $this->db->exec($query); $this->doEcho(false); @@ -850,8 +929,6 @@ class IRCScraper extends IRCClient * Echo new or update pre to CLI. * * @param bool $new - * - * @access protected */ protected function doEcho($new = true) { @@ -860,19 +937,19 @@ class IRCScraper extends IRCClient $nukeString = ''; if ($this->nuked !== false) { switch((int)$this->CurPre['nuked']) { - case PreDb::PRE_NUKED: + case PreHash::PRE_NUKED: $nukeString = '[ NUKED ] '; break; - case PreDb::PRE_UNNUKED: + case PreHash::PRE_UNNUKED: $nukeString = '[UNNUKED] '; break; - case PreDb::PRE_MODNUKE: + case PreHash::PRE_MODNUKE: $nukeString = '[MODNUKE] '; break; - case PreDb::PRE_OLDNUKE: + case PreHash::PRE_OLDNUKE: $nukeString = '[OLDNUKE] '; break; - case PreDb::PRE_RENUKED: + case PreHash::PRE_RENUKED: $nukeString = '[RENUKED] '; break; default: @@ -909,8 +986,6 @@ class IRCScraper extends IRCClient * @param string $groupName * * @return mixed - * - * @access protected */ protected function getGroupID($groupName) { @@ -923,8 +998,6 @@ class IRCScraper extends IRCClient /** * After updating or inserting new PRE, reset these. - * - * @access protected */ protected function resetPreVariables() { @@ -934,7 +1007,6 @@ class IRCScraper extends IRCClient array( 'title' => '', 'md5' => '', - 'sha1' => '', 'size' => '', 'predate' => '', 'category' => '', @@ -946,4 +1018,4 @@ class IRCScraper extends IRCClient 'files' => '' ); } -} +} \ 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..cb4e7f05b --- /dev/null +++ b/lib/Net_SmartIRC/Net/SmartIRC.php @@ -0,0 +1,3381 @@ +<?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 + */ + protected $_socket; + + /** + * @var string + * @access public + */ + public $_address; + + /** + * @var integer + * @access private + */ + protected $_port; + + /** + * @var string + * @access private + */ + protected $_bindaddress = null; + + /** + * @var integer + * @access private + */ + protected $_bindport = 0; + + /** + * @var string + * @access private + */ + protected $_nick; + + /** + * @var string + * @access private + */ + protected $_username; + + /** + * @var string + * @access private + */ + protected $_realname; + + /** + * @var string + * @access private + */ + protected $_usermode; + + /** + * @var string + * @access private + */ + protected $_password; + + /** + * @var array + * @access private + */ + protected $_performs = array(); + + /** + * @var boolean + * @access private + */ + protected $_state = false; + + /** + * @var array + * @access private + */ + protected $_actionhandler = array(); + + /** + * @var array + * @access private + */ + protected $_timehandler = array(); + + /** + * @var integer + * @access private + */ + protected $_debug = SMARTIRC_DEBUG_NOTICE; + + /** + * @var array + * @access private + */ + protected $_messagebuffer = array(); + + /** + * @var integer + * @access private + */ + protected $_messagebuffersize; + + /** + * @var boolean + * @access private + */ + protected $_usesockets = false; + + /** + * @var integer + * @access private + */ + protected $_receivedelay = 100; + + /** + * @var integer + * @access private + */ + protected $_senddelay = 250; + + /** + * @var integer + * @access private + */ + protected $_logdestination = SMARTIRC_STDOUT; + + /** + * @var resource + * @access private + */ + protected $_logfilefp = 0; + + /** + * @var string + * @access private + */ + protected $_logfile = 'Net_SmartIRC.log'; + + /** + * @var integer + * @access private + */ + protected $_disconnecttime = 1000; + + /** + * @var boolean + * @access private + */ + protected $_loggedin = false; + + /** + * @var boolean + * @access private + */ + protected $_benchmark = false; + + /** + * @var integer + * @access private + */ + protected $_benchmark_starttime; + + /** + * @var integer + * @access private + */ + protected $_benchmark_stoptime; + + /** + * @var integer + * @access private + */ + protected $_actionhandlerid = 0; + + /** + * @var integer + * @access private + */ + protected $_timehandlerid = 0; + + /** + * @var array + * @access private + */ + protected $_motd = array(); + + /** + * @var array + * @access private + */ + protected $_channels = array(); + + /** + * @var boolean + * @access private + */ + protected $_channelsyncing = false; + + /** + * @var array + * @access private + */ + protected $_users = array(); + + /** + * @var boolean + * @access private + */ + protected $_usersyncing = false; + + /** + * Stores the path to the modules that can be loaded. + * + * @var string + * @access private + */ + protected $_modulepath = ''; + + /** + * Stores all objects of the modules. + * + * @var string + * @access private + */ + protected $_modules = array(); + + /** + * @var string + * @access private + */ + protected $_ctcpversion; + + /** + * @var mixed + * @access private + */ + protected $_mintimer = false; + + /** + * @var integer + * @access private + */ + protected $_maxtimer = 300000; + + /** + * @var integer + * @access private + */ + protected $_txtimeout = 300; + + /** + * @var integer + * @access public + */ + public $_rxtimeout = 300; + + /** + * @var integer + * @access private + */ + protected $_selecttimeout; + + /** + * @var integer + * @access public + */ + public $_lastrx; + + /** + * @var integer + * @access private + */ + protected $_lasttx; + + /** + * @var boolean + * @access private + */ + protected $_autoreconnect = false; + + /** + * @var integer + * @access private + */ + protected $_reconnectdelay = 10000; + + /** + * @var boolean + * @access private + */ + protected $_autoretry = false; + + /** + * @var integer + * @access private + */ + protected $_autoretrymax = 5; + + /** + * @var integer + * @access private + */ + protected $_autoretrycount = 0; + + /** + * @var boolean + * @access private + */ + protected $_connectionerror = false; + + /** + * @var boolean + * @access private + */ + protected $_runasdaemon = false; + + /** + * @var array + */ + protected $channelList = array(); + + /** + * All IRC replycodes, the index is the replycode name. + * + * @see $SMARTIRC_replycodes + * @var array + * @access public + */ + public $replycodes; + + /** + * All numeric IRC replycodes, the index is the numeric replycode. + * + * @see $SMARTIRC_nreplycodes + * @var array + * @access public + */ + public $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 + */ + public $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 + */ + public $user; + + /** + * Constructor. Initiates the messagebuffer and "links" the replycodes from + * global into properties. Also some PHP runtime settings are configured. + * + * @access public + */ + public function __construct() + { + 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 + */ + public function setUseSockets($boolean) + { + $this->_usesockets = false; + if ($boolean === true) { + if (@extension_loaded('sockets')) { + $this->_usesockets = true; + } else { + $this->log(SMARTIRC_DEBUG_NOTICE, 'WARNING: your PHP build doesn\'t support real sockets, will use fsocks instead', __FILE__, __LINE__); + } + } + } + + /** + * 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 + * @param int $port + * + * @return bool + * @access public + */ + 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 + */ + public function setDebug($level) + { + $this->_debug = $level; + } + + /** + * Enables/disables the benchmark engine. + * + * @param boolean $boolean + * + * @return void + * @access public + */ + public function setBenchmark($boolean) + { + if (is_bool($boolean)) { + $this->_benchmark = $boolean; + } else { + $this->_benchmark = false; + } + } + + /** + * 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + public function setLogfile($file) + { + $this->_logfile = $file; + } + + /** + * Sets the delaytime before closing the socket when disconnect. + * + * @param integer $milliseconds + * + * @return void + * @access public + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 $file + * @param string $entry the new log entry + * @param string $line + * + * @return void + * @access protected + */ + protected 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 (!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 + */ + public function getMotd() + { + return $this->_motd; + } + + /** + * Returns the usermode. + * + * @return string + * @access public + */ + public function getUsermode() + { + return $this->_usermode; + } + + /** + * Returns a reference to the channel object of the specified channelname. + * + * @param string $channelname + * + * @return object + * @access public + */ + 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 + */ + 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 + */ + public function connect($address, $port) + { + $this->_address = $address; + $this->_port = $port; + $this->_autoretrycount = 0; + $connected = false; + if ($this->_autoretry === true && ($this->_autoretrycount < $this->_autoretrymax)) { + while ($this->_autoretrycount < $this->_autoretrymax) { + $connected = $this->connectHelper($address, $port); + if ($connected === true) { + break; + } else { + $this->_delayReconnect(); + $this->_autoretrycount++; + } + } + } else { + $connected = $this->connectHelper($address, $port); + } + if ($connected === false) { + $this->_connectionerror = true; + } + + return $connected; + } + + /** + * Helper method for connecting. + * + * @return boolean + * @access protected + */ + protected function connectHelper() + { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connecting', __FILE__, __LINE__); + $errno = $errstr = 0; + + 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, 'Warning: ' . $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 "' . $this->_address . '" reason: "' . $error . '"'; + $this->log(SMARTIRC_DEBUG_NOTICE, 'Warning: ' . $error_msg, __FILE__, __LINE__); + + if (($this->_autoretry == true) && + ($this->_autoretrycount < $this->_autoretrymax) + ) { + echo 'ERROR connecting to (' . $this->_address . ':' . $this->_port . + ') error: (' . $error . ') retry (' . $this->_autoretrycount . + '/' . $this->_autoretrymax . + '). Sleeping for (' . $this->_reconnectdelay . ') ms.' . PHP_EOL; + + return false; + } else { + echo 'ERROR connecting to (' . $this->_address . ':' . $this->_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 = $this->_lasttx = time(); + $this->_updatestate(); + + return $result; + } + + /** + * 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 + */ + public function disconnect($quickdisconnect = false) + { + if ($this->_connectionerror === false && $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__); + } + + 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 + */ + public function reconnect() + { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: reconnecting...', __FILE__, __LINE__); + $this->disconnect(true); + $this->connect($this->_address, $this->_port); + $this->login($this->_nick, $this->_realname, $this->_usermode, $this->_username, $this->_password); + $this->joinChannels($this->channelList); + } + + /** + * Join one or more channel. + * + * @param array $channelarray array('#channelname1' => 'password', '#channelname2' => null); + * @param int $priority + * + * @return bool + */ + public function joinChannels($channelarray, $priority = SMARTIRC_MEDIUM) + { + if ($this->_connectionerror === true || $this->_state() === SMARTIRC_STATE_DISCONNECTED) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'Warning: you must connect to IRC before joining channels!', __FILE__, __LINE__); + + return false; + } + + $this->channelList = $channelarray; + + return $this->join($channelarray, $priority); + } + + /** + * 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 bool + * @access public + */ + public function login($nick, $realname, $usermode = 0, $username = null, $password = null) + { + if ($this->_connectionerror === true || $this->_state() === SMARTIRC_STATE_DISCONNECTED) { + $this->log(SMARTIRC_DEBUG_NOTICE, 'Warning: you must connect to IRC before logging in!', __FILE__, __LINE__); + + return false; + } + + $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, 'Warning: login() usermode (' . $usermode . ') is not valid, will use 0 instead', __FILE__, __LINE__); + $usermode = 0; + } + $this->_usermode = $usermode; + + $this->_send('NICK ' . $this->_nick, SMARTIRC_CRITICAL); + $this->_send('USER ' . $this->_username . ' ' . $this->_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); + } + + return true; + } + + // </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 + */ + public function perform($cmd) + { + $this->_performs[] = $cmd; + } + + /** + * checks if the passed nickname is our own nickname + * + * @param string $nickname + * + * @return boolean + * @access public + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + public function listen() + { + while (true) { + if ($this->listenOnce() === false) { + break; + } + } + + 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 + */ + public function listenOnce() + { + if ($this->checkConnection()) { + $this->_rawreceive(); + if ($this->checkConnection()) { + return true; + } + } + + return false; + } + + /** + * Check if the connection is still up. + * + * @return bool + */ + protected function checkConnection() + { + if ($this->_connectionerror || $this->_state() === SMARTIRC_STATE_DISCONNECTED) { + if ($this->_autoreconnect) { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connection error detected, will reconnect!', __FILE__, __LINE__); + $this->reconnect(); + + return ($this->_connectionerror && $this->_state() === SMARTIRC_STATE_DISCONNECTED); + } else { + $this->log(SMARTIRC_DEBUG_CONNECTION, 'DEBUG_CONNECTION: connection error detected, will disconnect!', __FILE__, __LINE__); + $this->disconnect(); + + return false; + } + } + + return true; + } + + /** + * 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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 + */ + 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; + } + + public 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; + } + + public 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; + } + + /** + * 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 + */ + public function send($data, $priority = SMARTIRC_MEDIUM) + { + return $this->_send($data, $priority); + } + + // <private methods> + /** + * changes a already used nickname to a new nickname plus 3 random digits + * + * @return void + * @access private + */ + protected 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 + */ + public 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 + */ + protected 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 + */ + protected 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 + */ + protected 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 + */ + protected 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 bool + * @access private + */ + protected 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; + + return false; + } + + $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]; + // Fix for ZNC. + $messagecode = (isset($lineex[1]) ? $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); + } + } + + return true; + } + + /** + * 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 + */ + protected 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 + */ + protected 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 + * + * @param int $microseconds + * + * @return void + * @access private + */ + protected function _calculateselecttimeout($microseconds) + { + if (($this->_selecttimeout > $microseconds) || $this->_selecttimeout === null) { + $this->_selecttimeout = $microseconds; + } + } + + /** + * updates _mintimer to the smallest timer interval + * + * @return void + * @access private + */ + protected 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 + */ + protected 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 + */ + protected 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 + */ + protected 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 + */ + protected 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 + */ + protected 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 + */ + protected 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 + */ + protected function _handlemessage($messagecode, &$ircdata) + { + $found = false; + $_methodname = $methodname = $_codetype = ''; + + 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 + */ + protected 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 + */ + protected 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 + */ + protected 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 + */ + protected 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 + */ + protected 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 + */ + protected 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]); + } + } + } + } + + /** + * checks if the passed handlertype is valid + * + * @param integer $handlertype + * + * @return boolean + * @access private + */ + protected function _isValidType($handlertype) + { + if ($handlertype & SMARTIRC_TYPE_ALL) { + return true; + } else { + return false; + } + } + + protected function isError($object) + { + return (bool)(is_object($object) && (strtolower(get_class($object)) == 'net_smartirc_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..65e623ff8 --- /dev/null +++ b/lib/Net_SmartIRC/Net/SmartIRC/defines.php @@ -0,0 +1,235 @@ +<?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; +} diff --git a/lib/Net_SmartIRC/Net/SmartIRC/irccommands.php b/lib/Net_SmartIRC/Net/SmartIRC/irccommands.php new file mode 100644 index 000000000..e2007d54c --- /dev/null +++ b/lib/Net_SmartIRC/Net/SmartIRC/irccommands.php @@ -0,0 +1,558 @@ +<?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 $messagearray + * @param int $priority + * + * @internal 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 bool + * @access public + */ + function join($channelarray, $priority = SMARTIRC_MEDIUM) + { + foreach ($channelarray as $channel => $password) { + $this->_send('JOIN ' . $channel . ($password === null ? '' : ' ' . $password), $priority); + } + + return true; + } + + /** + * 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..67bf0ed7c --- /dev/null +++ b/lib/Net_SmartIRC/Net/SmartIRC/messagehandler.php @@ -0,0 +1,528 @@ +<?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..6bf2e68ec --- /dev/null +++ b/lib/Net_SmartIRC/modules/PingFix.php @@ -0,0 +1,36 @@ +<?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 / 3) { + $this->irc->_send('PING ' . $this->irc->_address, SMARTIRC_CRITICAL); + } + } +} diff --git a/lib/prehash.php b/lib/prehash.php index 4e058f205..cb561b981 100644 --- a/lib/prehash.php +++ b/lib/prehash.php @@ -12,14 +12,13 @@ require_once("nzbcontents.php"); require_once("simple_html_dom.php"); require_once("IRCScraper.php"); require_once("Info.php"); -require_once("namefixer.php"); /** * Class for inserting names/categories/md5 etc from PreDB sources into the DB, * also for matching names on files / subjects. * - * Class PreDb + * Class PreHash */ Class PreHash { @@ -39,9 +38,9 @@ Class PreHash const PRE_FOREIGN = true; // Nuke status. - const PRE_NONUKE = 0; // Pre is not nuked. + const PRE_NONUKE = 0; // Pre is not nuked. const PRE_UNNUKED = 1; // Pre was un nuked. - const PRE_NUKED = 2; // Pre is nuked. + const PRE_NUKED = 2; // Pre is nuked. const PRE_MODNUKE = 3; // Nuke reason was modified. const PRE_RENUKED = 4; // Pre was re nuked. const PRE_OLDNUKE = 5; // Pre is nuked for being old. @@ -65,35 +64,37 @@ Class PreHash * @var ColorCLI */ protected $c; + /** + * @var bool + */ + private $echo; /** * @param bool $echo + * */ - public function __construct($echo = false) + function __construct($echo = false) { + $s = new Sites(); + $this->site = $s->get(); $this->echooutput = $echo; $this->db = new DB(); - $this->c = new ColorCLI(); + $this->c = new ColorCLI; $this->functions = new Functions(); } - /** - * Retrieve pre info from PreDB sources and store them in the DB. - * - * @return int The quantity of new titles retrieved. - */ + // Retrieve pre info from predb sources and store them in the DB. + // Returns the quantity of new titles retrieved. public function updatePre() { + $f = new Functions(); $newNames = 0; $newestRel = $this->db->queryOneRow("SELECT value AS adddate FROM tmux WHERE setting = 'lastpretime'"); - - // Wait 10 minutes in between pulls. if ((int)$newestRel['adddate'] < (time() - 600)) { if ($this->echooutput) { echo $this->c->header("Retrieving titles from preDB sources."); } - if (self::PRE_WOMBLE) { $newNames += $newWomble = $this->retrieveWomble(); if ($this->echooutput) { @@ -196,25 +197,18 @@ Class PreHash return $newNames; } - /** - * Attempts to match PreDB titles / NFOs to releases. - * - * @param $nntp - */ + // Attempts to match predb to releases. public function checkPre($nntp) { $matched = $this->matchPredb(); if ($this->echooutput) { - echo $this->c->header( - 'Matched ' . number_format(($matched > 0) ? $matched : 0) . ' predDB titles to release search names.' - ); + $count = ($matched > 0) ? $matched : 0; + echo $this->c->header('Matched ' . number_format($count) . ' prehash titles to release search names.'); } - $nfos = $this->matchNfo($nntp); if ($this->echooutput) { - echo $this->c->header( - "\nAdded " . number_format(($nfos > 0) ? $nfos : 0) . ' missing NFOs from preDB sources.' - ); + $count = ($nfos > 0) ? $nfos : 0; + echo $this->c->header("\nAdded " . number_format($count) . ' missing NFOs from preDB sources.'); } } @@ -240,7 +234,6 @@ Class PreHash } $md5 = $this->db->escapeString(md5($matches2['title'])); - $sha1 = $this->db->escapeString(sha1($matches2['title'])); $oldName = $this->db->queryOneRow(sprintf('SELECT md5, source, ID, nfo FROM prehash WHERE md5 = %s', $md5)); // If we have it already and have the NFO, continue. if ($oldName !== false && $oldName['nfo'] != NULL) { @@ -276,10 +269,13 @@ Class PreHash $updated++; } elseif ($this->db->exec( sprintf(' - INSERT INTO prehash (title, nfo, size, category, predate, source, md5, sha1) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s)', + INSERT INTO prehash (title, nfo, size, category, predate, source, md5) + VALUES (%s, %s, %s, %s, %s, %s, %s)', $this->db->escapeString($matches2['title']), - $nfo, $size, $category, $time, $source, $md5, $sha1))) { + $nfo, $size, $category, $time, $source, $md5 + ) + ) + ) { $newNames++; } } @@ -318,7 +314,6 @@ Class PreHash $title = $matches2['title']; $md5 = $this->db->escapeString(md5($title)); - $sha1 = $this->db->escapeString(sha1($title)); $oldName = $this->db->queryOneRow(sprintf('SELECT md5, source, ID FROM prehash WHERE md5 = %s', $md5)); // If we have it already and the source is womble or omg, continue. @@ -344,9 +339,12 @@ Class PreHash $updated++; } elseif ($this->db->exec( sprintf(' - INSERT INTO prehash (title, size, category, predate, source, md5, sha1) - VALUES (%s, %s, %s, %s, %s, %s, %s)', - $this->db->escapeString($title), $size, $category, $time, $source, $md5, $sha1))) { + INSERT INTO prehash (title, size, category, predate, source, md5) + VALUES (%s, %s, %s, %s, %s, %s)', + $this->db->escapeString($title), $size, $category, $time, $source, $md5 + ) + ) + ) { $newNames++; } } @@ -385,7 +383,6 @@ Class PreHash } $md5 = $this->db->escapeString(md5($matches2['title'])); - $sha1 = $this->db->escapeString(sha1($matches2['title'])); $dupeCheck = $this->db->queryOneRow(sprintf('SELECT md5 FROM prehash WHERE md5 = %s', $md5)); // If we already have it, skip. @@ -394,8 +391,8 @@ Class PreHash continue; } elseif ($this->db->exec( sprintf(' - INSERT INTO prehash (title, size, category, predate, source, md5, sha1, files) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s)', + INSERT INTO prehash (title, size, category, predate, source, md5, files) + VALUES (%s, %s, %s, %s, %s, %s, %s)', $this->db->escapeString($matches2['title']), ((!isset($matches2['size1']) && empty($matches2['size1'])) ? 'NULL' @@ -408,7 +405,6 @@ Class PreHash $this->functions->from_unixtime(strtotime($matches2['predate'])), $this->db->escapeString('zenet'), $md5, - $sha1, $this->db->escapeString($matches2['files'])))) { $newNames++; } @@ -445,7 +441,6 @@ Class PreHash continue; } $md5 = $this->db->escapeString(md5($matches4['title'])); - $sha1 = $this->db->escapeString(sha1($matches4['title'])); $oldName = $this->db->queryOneRow(sprintf('SELECT md5 FROM prehash WHERE md5 = %s', $md5)); // If we have it already, skip. @@ -461,8 +456,8 @@ Class PreHash if ($this->db->exec( sprintf(' - INSERT INTO prehash (title, size, category, predate, source, md5, sha1, files, nuked, nukereason) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', + INSERT INTO prehash (title, size, category, predate, source, md5, files, nuked, nukreason) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)', $this->db->escapeString($matches4['title']), ((!isset($matches4['size']) && empty($matches4['size'])) ? 'NULL' @@ -472,7 +467,6 @@ Class PreHash $this->functions->from_unixtime(strtotime($matches4['date'])), $this->db->escapeString('prelist'), $md5, - $sha1, $this->db->escapeString($matches4['files']), ($nuked === '' ? self::PRE_NONUKE : $nuked), ($nukereason === '' ? 'NULL' : $this->db->escapeString($nukereason))))) { @@ -509,14 +503,13 @@ Class PreHash continue; } $md5 = $this->db->escapeString(md5($matches2['title'])); - $sha1 = $this->db->escapeString(sha1($matches2['title'])); $oldName = $this->db->queryOneRow(sprintf('SELECT md5 FROM prehash WHERE md5 = %s', $md5)); if ($oldName !== false) { continue; } elseif ($this->db->exec( sprintf(' - INSERT INTO prehash (title, size, category, predate, source, md5, sha1, files) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s)', + INSERT INTO prehash (title, size, category, predate, source, md5, files) + VALUES (%s, %s, %s, %s, %s, %s, %s)', $this->db->escapeString($matches2['title']), ((!isset($matches2['size']) && empty($matches2['size'])) ? 'NULL' @@ -526,7 +519,6 @@ Class PreHash $this->functions->from_unixtime(strtotime($matches2['date'])), $this->db->escapeString('orlydb'), $md5, - $sha1, ((!isset($matches2['files']) && empty($matches2['files'])) ? 'NULL' : $this->db->escapeString($matches2['files'])) @@ -567,7 +559,6 @@ Class PreHash continue; } $md5 = $this->db->escapeString(md5($release->title)); - $sha1 = $this->db->escapeString(sha1($release->title)); $oldName = $this->db->queryOneRow(sprintf('SELECT ID, nfo FROM prehash WHERE md5 = %s', $md5)); $nfo = $size = ''; @@ -576,7 +567,7 @@ Class PreHash } if (preg_match('/Filesize.*<td>(?P<size>\d*)<\/td>\s*<td>.*?<\/td>\s*<td>.*?<\/td>\s*<\/tr>\s*<\/table>\s*/is', $release->description, $description)) { - $size = ((isset($description['size']) && !empty($description['size'])) ? $this->db->escapeString($this->functions->bytesToSizeString($description['size'])) : 'NULL'); + $size = ((isset($description['size']) && !empty($description['size'])) ? $this->db->escapeString($this->bytesToSizeString($description['size'])) : 'NULL'); } if ($oldName !== false) { @@ -597,13 +588,12 @@ Class PreHash continue; } else if ($this->db->exec( sprintf(' - INSERT INTO prehash (title, predate, source, md5, sha1, nfo, size) - VALUES (%s, %s, %s, %s, %s, %s, %s)', + INSERT INTO prehash (title, predate, source, md5, nfo, size) + VALUES (%s, %s, %s, %s, %s, %s)', $this->db->escapeString($release->title), $this->functions->from_unixtime(strtotime($release->pubDate)), $this->db->escapeString('srrdb'), $md5, - $sha1, $nfo, $size))) { $newNames++; @@ -665,18 +655,19 @@ Class PreHash continue; } $md5 = $this->db->escapeString(md5($release->title)); - $sha1 = $this->db->escapeString(sha1($release->title)); $oldname = $this->db->queryOneRow(sprintf('SELECT md5 FROM prehash WHERE md5 = %s', $md5)); if ($oldname !== false) { continue; } elseif ($this->db->exec( sprintf(' - INSERT INTO prehash (title, predate, source, md5, sha1) - VALUES (%s, NOW(), %s, %s, %s)', + INSERT INTO prehash (title, predate, source, md5) + VALUES (%s, NOW(), %s, %s)', $this->db->escapeString($release->title), $this->db->escapeString('predbme'), - $md5, - $sha1))) { + $md5 + ) + ) + ) { $newNames++; } } @@ -721,26 +712,25 @@ Class PreHash foreach ($matches as $match) { foreach ($match as $m) { if (preg_match('/<td class="cell_reqid">(?P<requestid>\d+)<\/td>.+?<td class="cell_filecount">(?P<files>\d+x\d+)<\/td>.+?<td class="cell_request">(?P<title>.+)<\/td>.+<td class="cell_statuschange">(?P<predate>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})<\/td>/s', $m, $matches2)) { - if (isset($matches2["requestid"]) && isset($matches2["title"])) { + if (isset($matches2["requestID"]) && isset($matches2["title"])) { // If too short, skip. if (strlen($matches2["title"]) < 15) { continue; } $md5 = $this->db->escapeString(md5($matches2["title"])); - $sha1 = $this->db->escapeString(sha1($matches2["title"])); + $dupeCheck = $this->db->queryOneRow(sprintf('SELECT ID, requestID FROM prehash WHERE md5 = %s', $md5)); if ($dupeCheck === false) { $this->db->exec( sprintf(" - INSERT INTO prehash (title, predate, source, md5, sha1, requestID, groupID, files, category) - VALUES (%s, %s, %s, %s, %s, %s, %d, %s, 'Movies')", + INSERT INTO prehash (title, predate, source, md5, requestID, groupID, files, category) + VALUES (%s, %s, %s, %s, %s, %d, %s, 'Movies')", $this->db->escapeString($matches2["title"]), $this->functions->from_unixtime(strtotime($matches2["predate"])), $this->db->escapeString('abMooVee'), $md5, - $sha1, - $matches2["requestid"], + $matches2["requestID"], $groupid, $this->db->escapeString($matches2['files']) ) @@ -752,7 +742,7 @@ Class PreHash UPDATE prehash SET requestID = %s, groupID = %d, files = %s WHERE md5 = %s', - $matches2["requestid"], + $matches2["requestID"], $groupid, $this->db->escapeString($matches2['files']), $md5 @@ -792,39 +782,37 @@ Class PreHash if (preg_match_all('/<tr class="(even|odd)".+?<\/tr>/s', $buffer, $matches)) { foreach ($matches as $match) { foreach ($match as $m) { - if (preg_match('/<td class="cell_reqid">(?P<requestid>\d+)<\/td>.+?<td class="cell_filecount">(?P<files>\d+x\d+)<\/td>.+?<td class="cell_request">(?P<title>.+)<\/td>.+<td class="cell_statuschange">(?P<predate>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})<\/td>/s', $m, $matches2)) { - if (isset($matches2["requestid"]) && isset($matches2["title"])) { + if (preg_match('/<td class="cell_reqid">(?P<requestID>\d+)<\/td>.+?<td class="cell_filecount">(?P<files>\d+x\d+)<\/td>.+?<td class="cell_request">(?P<title>.+)<\/td>.+<td class="cell_statuschange">(?P<predate>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})<\/td>/s', $m, $matches2)) { + if (isset($matches2["requestID"]) && isset($matches2["title"])) { // Skip if too short. if (strlen($matches2["title"]) < 15) { continue; } $md5 = $this->db->escapeString(md5($matches2["title"])); - $sha1 = $this->db->escapeString(sha1($matches2["title"])); $dupeCheck = $this->db->queryOneRow(sprintf('SELECT ID, requestID FROM prehash WHERE md5 = %s', $md5)); if ($dupeCheck === false) { $this->db->exec( sprintf(" - INSERT INTO prehash (title, predate, source, md5, sha1, requestID, groupID, files, category) - VALUES (%s, %s, %s, %s, %s, %s, %d, %s, 'TV')", + INSERT INTO prehash (title, predate, source, md5, requestID, groupID, files, category) + VALUES (%s, %s, %s, %s, %s, %d, %s, 'TV')", $this->db->escapeString($matches2["title"]), $this->functions->from_unixtime(strtotime($matches2["predate"])), $this->db->escapeString('abTeeVee'), $md5, - $sha1, - $matches2["requestid"], + $matches2["requestID"], $groupid, $this->db->escapeString($matches2['files']) ) ); $newNames++; - } else if (empty($dupeCheck['requestid'])) { + } else if (empty($dupeCheck['requestID'])) { $this->db->exec( sprintf(' UPDATE prehash SET requestID = %s, groupID = %d, files = %s WHERE md5 = %s', - $matches2["requestid"], + $matches2["requestID"], $groupid, $this->db->escapeString($matches2['files']), $md5 @@ -865,39 +853,38 @@ Class PreHash foreach ($matches as $match) { foreach ($match as $m) { if (preg_match('/<td class="cell_reqid">(?P<requestid>\d+)<\/td>.+?<td class="cell_type">(?P<category>.+?)<\/td>.+?<td class="cell_filecount">(?P<files>\d+x\d+)<\/td>.+?<td class="cell_request">(?P<title>.+)<\/td>.+<td class="cell_statuschange">(?P<predate>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})<\/td>/s', $m, $matches2)) { - if (isset($matches2["requestid"]) && isset($matches2["title"])) { + if (isset($matches2["requestID"]) && isset($matches2["title"])) { // If too short, skip. if (strlen($matches2["title"]) < 15) { continue; } $md5 = $this->db->escapeString(md5($matches2["title"])); - $sha1 = $this->db->escapeString(sha1($matches2["title"])); + $dupeCheck = $this->db->queryOneRow(sprintf('SELECT ID, requestID FROM prehash WHERE md5 = %s', $md5)); if ($dupeCheck === false) { $this->db->exec( sprintf(" - INSERT INTO prehash (title, predate, source, md5, sha1, requestID, groupID, files, category) - VALUES (%s, %s, %s, %s, %s, %s, %d, %s, %s)", + INSERT INTO prehash (title, predate, source, md5, requestID, groupID, files, category) + VALUES (%s, %s, %s, %s, %s, %d, %s, %s)", $this->db->escapeString($matches2["title"]), $this->functions->from_unixtime(strtotime($matches2["predate"])), $this->db->escapeString('abErotica'), $md5, - $sha1, - $matches2["requestid"], + $matches2["requestID"], $groupid, $this->db->escapeString($matches2['files']), $this->db->escapeString('XXX-' . $matches2['category']) ) ); $newNames++; - } else if (empty($dupeCheck['requestid'])) { + } else if (empty($dupeCheck['requestID'])) { $this->db->exec( sprintf(' UPDATE prehash SET requestID = %s, groupID = %d, files = %s WHERE md5 = %s', - $matches2["requestid"], + $matches2["requestID"], $groupid, $this->db->escapeString($matches2['files']), $md5 @@ -938,39 +925,38 @@ Class PreHash foreach ($matches as $match) { foreach ($match as $m) { if (preg_match('/<td class="cell_reqid">(?P<requestid>\d+)<\/td>.+<td class="cell_type">(?P<category>.+?)<\/td>.+?<td class="cell_filecount">(?P<files>\d+x\d+)<\/td>.+?<td class="cell_request">(?P<title>.+)<\/td>.+<td class="cell_statuschange">(?P<predate>\d{4}-\d{2}-\d{2}( \d{2}:\d{2}:\d{2})?)<\/td>/s', $m, $matches2)) { - if (isset($matches2["requestid"]) && isset($matches2["title"])) { + if (isset($matches2["requestID"]) && isset($matches2["title"])) { - // If too short, skip. + // If too short, skip. if (strlen($matches2["title"]) < 15) { continue; } $md5 = $this->db->escapeString(md5($matches2["title"])); - $sha1 = $this->db->escapeString(sha1($matches2["title"])); + $dupeCheck = $this->db->queryOneRow(sprintf('SELECT ID, requestID FROM prehash WHERE md5 = %s', $md5)); if ($dupeCheck === false) { $this->db->exec( sprintf(" - INSERT INTO prehash (title, predate, source, md5, sha1, requestID, groupID, files, category) - VALUES (%s, %s, %s, %s, %s, %s, %d, %s, %s)", + INSERT INTO prehash (title, predate, source, md5, requestID, groupID, files, category) + VALUES (%s, %s, %s, %s, %s, %d, %s, %s)", $this->db->escapeString($matches2["title"]), $this->functions->from_unixtime(strtotime($matches2["predate"])), $this->db->escapeString('abForeign'), $md5, - $sha1, - $matches2["requestid"], + $matches2["requestID"], $groupid, $this->db->escapeString($matches2["files"]), $this->db->escapeString($matches2["category"]) ) ); $newNames++; - } else if (empty($dupeCheck['requestid'])) { + } else if (empty($dupeCheck['requestID'])) { $this->db->exec( sprintf(' UPDATE prehash SET requestID = %s, groupID = %d, files = %s, category = %s WHERE md5 = %s', - $matches2["requestid"], + $matches2["requestID"], $groupid, $this->db->escapeString($matches2["files"]), $this->db->escapeString($matches2["category"]), @@ -996,7 +982,7 @@ Class PreHash */ protected function retrieveAbgx() { - $newnames = 0; + $newNames = 0; $groups = new Groups(); $groupname = $request = $title = ''; @@ -1019,11 +1005,10 @@ Class PreHash preg_match('/^Req (\d+) - (\S+) .+/', $release->title, $request); $requestid = $request[1]; $md5 = md5($title[1]); - $sha1 = sha1($title[1]); $predate = $title[2]; - $oldname = $this->db->queryOneRow(sprintf('SELECT md5, requestiID, groupID FROM prehash WHERE md5 = %s', $this->db->escapeString($md5))); - if ($oldname !== false && empty($oldname['requestid'])) { + $oldname = $this->db->queryOneRow(sprintf('SELECT md5, requestID, groupID FROM prehash WHERE md5 = %s', $this->db->escapeString($md5))); + if ($oldname !== false && empty($oldname['requestID'])) { $this->db->exec( sprintf(' UPDATE prehash @@ -1038,16 +1023,15 @@ Class PreHash else if ($oldname === false) { if ($this->db->exec( sprintf(' - INSERT INTO prehash (title, predate, source, md5, sha1, requestID, groupID) - VALUES (%s, %s, %s, %s, %s, %d, %d)', + INSERT INTO prehash (title, predate, source, md5, requestID, groupID) + VALUES (%s, %s, %s, %s, %d, %d)', $this->db->escapeString($title[1]), $this->functions->from_unixtime(strtotime($predate)), $this->db->escapeString('abgx'), $this->db->escapeString($md5), - $this->db->escapeString($sha1), $requestid, $groupid))) { - $newnames++; + $newNames++; } } } @@ -1055,16 +1039,19 @@ Class PreHash if ($this->echooutput) { echo $this->c->error("Update from ABGX failed."); } - return $newnames; + + return $newNames; } } else { if ($this->echooutput) { echo $this->c->error("Update from ABGX failed."); } - return $newnames; + + return $newNames; } } - return $newnames; + + return $newNames; } /** @@ -1075,7 +1062,7 @@ Class PreHash protected function retrieveUsenetCrawler() { $db = new DB(); - $newnames = 0; + $newNames = 0; $data = $this->getUrl("http://www.usenet-crawler.com/predb?q=&c=&offset=0#results"); if ($data === false) { @@ -1085,7 +1072,7 @@ Class PreHash $html = str_get_html($data); $releases = @$html->find('table[id="browsetable"]'); if (!isset($releases[0])) { - return $newnames; + return $newNames; } $rows = $releases[0]->find('tr'); $count = 0; @@ -1110,7 +1097,6 @@ Class PreHash } $md5 = md5($title); - $sha1 = sha1($title); // Check DB if we already have it. $check = $db->queryOneRow(sprintf('SELECT ID FROM prehash WHERE md5 = %s', $db->escapeString($md5))); if ($check !== false) { @@ -1122,20 +1108,20 @@ Class PreHash preg_match('/([\d\.]+MB)/', $data[3]->innertext, $match); $size = isset($match[1]) ? $match[1] : 'NULL'; if (strlen($title) > 15 && $category != 'NUKED') { - if ($db->exec(sprintf('INSERT INTO prehash (title, predate, source, md5, sha1, category, size) VALUES (%s, %s, %s, %s, %s, %s, %s)', - $db->escapeString($title), $this->functions->from_unixtime($predate), $db->escapeString('usenet-crawler'), $db->escapeString($md5), $db->escapeString($sha1), - $db->escapeString($category), $db->escapeString($size)))) { - $newnames++; + if ($db->exec(sprintf('INSERT INTO prehash (title, predate, source, md5, category, size) VALUES (%s, %s, %s, %s, %s, %s)', $db->escapeString($title), $this->functions->from_unixtime($predate), $db->escapeString('usenet-crawler'), $db->escapeString($md5), $db->escapeString($category), $db->escapeString($size)))) { + $newNames++; } } } - return $newnames; + + return $newNames; } // Update a single release as it's created. public function matchPre($cleanerName, $releaseID) { $db = new DB(); + $f = new Functions(); $x = $db->queryOneRow(sprintf('SELECT ID FROM prehash WHERE title = %s', $db->escapeString($cleanerName))); if (isset($x['ID'])) { $db->exec(sprintf('UPDATE releases SET prehashID = %d WHERE ID = %d', $x['ID'], $releaseID)); @@ -1144,38 +1130,28 @@ Class PreHash return false; } - // When a searchname is the same as the title, tie it to the prehash. Try to update the categoryID at the same time. + // When a searchname is the same as the title, tie it to the predb. Try to update the categoryID at the same time. public function matchPredb() { - /* - * For future reference, mysql 5.6 innodb has fulltext searching support. - * INSERT INTO releases (name) VALUES ('[149787]-[FULL]-[#a.b.teevee]-[ The.Amazing.World.of.Gumball.S01E28.The.Club.720p.HDTV.x264-W4F ]-[1/1] - "The.Amazing.World.of.Gumball.S01E28.The.Club.720p.HDTV.x264-W4F.nzb" yEnc'); - * ALTER TABLE releases ADD FULLTEXT(name); - * SELECT * FROM releases WHERE MATCH (name) AGAINST ('"The.Amazing.World.of.Gumball.S01E28.The.Club.720p.HDTV.x264-W4F"' IN BOOLEAN MODE); - * - * In myisam this is much faster than SELECT * FROM releases WHERE name LIKE '%The.Amazing.World.of.Gumball.S01E28.The.Club.720p.HDTV.x264-W4F%'; - * So I'm guessing in innodb it will be the same. - */ $db = new DB(); + $f = new Functions(); $consoletools = new ConsoleTools(); $updated = 0; if ($this->echooutput) { - echo $this->c->header('Querying DB for release searchnames not matched with preDB titles.'); + echo $this->c->header('Querying DB for release searchnames not matched with prehash titles.'); } $res = $db->queryDirect('SELECT p.ID AS prehashID, r.ID AS releaseID FROM prehash p INNER JOIN releases r ON p.title = r.searchname WHERE r.prehashID = 0'); $total = $res->rowCount(); - echo $this->c->primary(number_format($total) . ' releases to match.'); if ($total > 0) { + echo "\n"; foreach ($res as $row) { $db->exec(sprintf('UPDATE releases SET prehashID = %d WHERE ID = %d', $row['prehashID'], $row['releaseID'])); if ($this->echooutput) { - $consoletools->overWritePrimary('Matching up preDB titles with release searchnames: ' . $consoletools->percentString( ++$updated, $total)); + $consoletools->overWritePrimary('Matching up prehash titles with release search names: ' . $consoletools->percentString(++$updated, $total)); } } - if ($this->echooutput) { - echo "\n"; - } + echo "\n"; } return $updated; } @@ -1184,16 +1160,15 @@ Class PreHash public function matchNfo($nntp) { if (!isset($nntp)) { - exit($this->c->error("Not connected to usenet(binaries->updateAllGroups).\n")); + exit($this->c->error("Not connected to usenet(prehash->matchNFO).\n")); } $db = new DB(); $nfos = 0; - if ($this->echooutput) { - echo $this->c->primary('Matching up prehash NFOs with releases missing an NFO.'); - } + if ($this->echooutput) + echo $this->c->header("Matching up prehash NFOs with releases missing an NFO."); - $res = $db->queryDirect('SELECT r.ID, p.nfo, p.title, r.completion, r.guid, r.groupID FROM releases r INNER JOIN prehash p ON r.prehashID = p.ID WHERE r.nfostatus != 1 AND p.nfo IS NOT NULL LIMIT 100'); + $res = $db->queryDirect("SELECT r.ID, p.nfo, p.title, r.completion, r.guid, r.groupID FROM releases r INNER JOIN prehash p ON r.prehashID = p.ID WHERE r.nfostatus != 1 AND p.nfo IS NOT NULL LIMIT 100"); $total = $res->rowCount(); if ($total > 0) { $nfo = new Info($this->echooutput); @@ -1215,58 +1190,44 @@ Class PreHash if ($row['nfo'] === 'srrdb' && preg_match('/You\'ve reached the daily limit/i', $buffer)) { continue; } - if ($nfo->addAlternateNfo($buffer, $row, $nntp)) { - if ($this->echooutput) { + if ($this->echooutput) echo '+'; - } $nfos++; } else { - if ($this->echooutput) { + if ($this->echooutput) echo '-'; - } } } } + + return $nfos; } - return $nfos; } // Matches the MD5 within the prehash table to release files and subjects (names) which are hashed. public function parseTitles($time, $echo, $cats, $namestatus, $show) { $db = new DB(); - $namefixer = new Namefixer($this->echooutput); + $namefixer = new Namefixer(); $consoletools = new ConsoleTools(); $updated = $checked = 0; $matches = ''; - $tq = ''; - if ($time == 1) { - if (DB_TYPE === 'mysql') { - $tq = 'AND r.adddate > (NOW() - INTERVAL 3 HOUR) ORDER BY rf.releaseID, rf.size DESC'; - } else if (DB_TYPE === 'pgsql') { - $tq = "AND r.adddate > (NOW() - INTERVAL '3 HOURS') ORDER BY rf.releaseID, rf.size DESC"; - } - } - $ct = ''; - if ($cats == 1) { - $ct = 'AND r.categoryID IN (2020, 5050, 6070, 8010)'; - } + $tq = ""; + if ($time == 1) + $tq = $tq = 'AND r.adddate > (NOW() - INTERVAL 3 HOUR) ORDER BY rf.releaseID, rf.size DESC'; + $ct = ""; + if ($cats == 1) + $ct = " and r.categoryID in (2020, 5050, 6070, 8010)"; if ($this->echooutput) { - $te = ''; - if ($time == 1) { - $te = ' in the past 3 hours'; - } - echo $this->c->header('Fixing search names' . $te . " using the prehash md5."); + $te = ""; + if ($time == 1) + $te = " in the past 3 hours"; + echo $this->c->header("Fixing search names" . $te . " using the prehash md5."); } - if (DB_TYPE === 'mysql') { - $regex = "AND (r.ishashed = 1 OR rf.name REGEXP'[a-fA-F0-9]{32}')"; - } else if (DB_TYPE === 'pgsql') { - $regex = "AND (r.ishashed = 1 OR rf.name ~ '[a-fA-F0-9]{32}')"; - } - + $regex = "AND (r.ishashed = 1 OR rf.name REGEXP'[a-fA-F0-9]{32}')"; if ($cats === 3) { $query = sprintf('SELECT r.ID AS releaseID, r.name, r.searchname, r.categoryID, r.groupID, ' . 'dehashstatus, rf.name AS filename FROM releases r ' @@ -1278,7 +1239,6 @@ Class PreHash . 'LEFT OUTER JOIN releasefiles rf ON r.ID = rf.releaseID ' . 'WHERE isrenamed = 0 AND dehashstatus BETWEEN -6 AND 0 %s %s %s', $regex, $ct, $tq); } - $res = $db->queryDirect($query); $total = $res->rowCount(); echo $this->c->primary(number_format($total) . " releases to process."); @@ -1314,12 +1274,11 @@ Class PreHash { $db = new DB(); if ($search !== '') { - $like = (DB_TYPE === 'mysql' ? 'LIKE' : 'ILIKE'); $search = explode(' ', trim($search)); if (count($search > 1)) { - $search = "$like '%" . implode("%' AND title $like '%", $search) . "%'"; + $search = "LIKE '%" . implode("%' AND title LIKE '%", $search) . "%'"; } else { - $search = "$like '%" . $search . "%'"; + $search = "LIKE '%" . $search . "%'"; } $search = 'WHERE title ' . $search; $count = $db->queryOneRow(sprintf('SELECT COUNT(*) AS cnt FROM prehash %s', $search)); @@ -1332,24 +1291,52 @@ Class PreHash return array('arr' => $parr, 'count' => $count); } + // Returns a single row for a release. + public function getForRelease($prehashID) + { + $db = new DB(); + + return $db->query(sprintf('SELECT * FROM prehash WHERE ID = %d', $prehashID)); + } + public function getCount() { $db = new DB(); - $count = $db->queryOneRow('SELECT COUNT(*) AS cnt FROM prehash'); - return $count['cnt']; + $count = $db->queryOneRow("SELECT count(*) as cnt from prehash"); + + return $count["cnt"]; } - // Returns a single row for a release. - public function getForRelease($preID) + public function getOne($prehashID) { $db = new DB(); - return $db->query(sprintf('SELECT * FROM prehash WHERE ID = %d', $preID)); + + return $db->queryOneRow(sprintf('SELECT * FROM prehash WHERE ID = %d', $prehashID)); } - public function getOne($preID) + public function getWebPage($url) { - $db = new DB(); - return $db->queryOneRow(sprintf('SELECT * FROM prehash WHERE ID = %d', $preID)); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, $url); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); + $output = curl_exec($ch); + curl_close($ch); + + return $output; + } + + function fileContents($path, $use = false, $context = '') + { + if ($context === '') { + $str = @file_get_contents($path); + } else { + $str = @file_get_contents($path, $use, $context); + } + if ($str === false) { + return false; + } else { + return $str; + } } /** @@ -1361,8 +1348,8 @@ Class PreHash */ protected function getUrl($url) { - return $this->functions->getUrl( - $url, + return getUrl( + $url, 'get', '', 'en', @@ -1372,4 +1359,22 @@ Class PreHash ); } -} + /** + * Get human readable size string from bytes. + * + * @param int $bytes Bytes number to convert. + * @param int $precision How many floating point units to add. + * + * @return string + */ + function bytesToSizeString($bytes, $precision = 0) + { + if ($bytes == 0) { + return '0B'; + } + + $unit = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'); + + return round($bytes / pow(1024, ($i = floor(log($bytes, 1024)))), $precision) . $unit[(int)$i]; + } +} \ No newline at end of file