From 2c349bd9b7e5229a70040e5824724d77f3e47016 Mon Sep 17 00:00:00 2001 From: xandros15 Date: Wed, 25 May 2016 15:37:28 +0200 Subject: [PATCH] #6 create new catalog structure for modules --- module/{ => aigis}/Aigis.php | 599 ++++++++++++------------- module/{ => api-proxy}/ApiProxy.php | 126 +++--- module/{ => basic}/Basic.php | 290 ++++++------ module/{ => basic}/Chatlog.php | 164 +++---- module/{ => basic}/Commands.php | 441 +++++++++--------- module/{ => ctcp}/Ctcp.php | 17 +- module/dictionary/Dictionary.php | 61 --- module/dictionary/dict/dictionary.json | 5 - module/{ => fun}/Fun.php | 507 +++++++++++---------- module/settings/.gitignore | 2 - module/{ => thpl}/Thpl.php | 504 ++++++++++----------- module/{ => uri}/Url.php | 62 +-- 12 files changed, 1348 insertions(+), 1430 deletions(-) rename module/{ => aigis}/Aigis.php (95%) rename module/{ => api-proxy}/ApiProxy.php (90%) rename module/{ => basic}/Basic.php (84%) rename module/{ => basic}/Chatlog.php (94%) rename module/{ => basic}/Commands.php (82%) rename module/{ => ctcp}/Ctcp.php (83%) delete mode 100644 module/dictionary/Dictionary.php delete mode 100644 module/dictionary/dict/dictionary.json rename module/{ => fun}/Fun.php (95%) delete mode 100644 module/settings/.gitignore rename module/{ => thpl}/Thpl.php (95%) rename module/{ => uri}/Url.php (82%) diff --git a/module/Aigis.php b/module/aigis/Aigis.php similarity index 95% rename from module/Aigis.php rename to module/aigis/Aigis.php index 0db8240..da51cad 100644 --- a/module/Aigis.php +++ b/module/aigis/Aigis.php @@ -1,301 +1,300 @@ -setCommand([ - 'trigger' => 'pin', - 'action' => 'generatePin', - 'arguments' => 0, - 'channels' => ['#aigis'] - ]); - $this->setCommand([ - 'trigger' => 'unit', - 'action' => 'unit', - 'determiter' => ' ', - 'arguments' => -1, - 'channels' => ['#aigis'], - 'help' => 'Type "!unit {unit_name}" to get link to information about this unit.', - ]); - $this->setCommand([ - 'trigger' => 'cg', - 'action' => 'cg', - 'determiter' => ' ', - 'arguments' => 1, - 'channels' => ['#aigis'], - 'help' => 'Type "!cg {unit_name}" to get link to unit gallery.', - ]); - $this->setCommand([ - 'trigger' => 'dmm', - 'action' => 'getLinkToInfoDmmEvent', - 'arguments' => 0, - 'channels' => ['#aigis'], - 'help' => 'Type "!dmm" to get link to info about current dmm event.', - ]); - - parent::loadSettings($this); - } - - protected function cg($arguments) - { - $request = trim($arguments[0]); - - if ($this->hasRequestDelay($request, $this->lastCgRequest)) { - return; - } - - $units = $this->findUnitsViaName($request); - - if (!$units) { - $this->reply($this->getProposition($request)); - return; - } - - if (!$this->hasOwnList($units, 'image')) { - $this->reply("I don't have this cg (yet?)."); - return; - } - - foreach ($units as $unit) { - if (!$unit->ownImageList) { - continue; - } - - $uri = sprintf(self::GALLERY_URL, $unit->id); - - $response = sprintf( - '%s: %s %s: %s', - CT::textOrange('Romanji'), - $unit->original, - CT::textPink('NSFW'), - $uri - ); - $this->reply($response); - } - } - - protected function unit($arguments) - { - $request = trim($arguments[0]); - - if ($this->hasRequestDelay($request, $this->lastUnitRequest)) { - return; - } - - $units = $this->findUnitsViaName($request); - - if (!$units) { - $this->reply($this->getProposition($request)); - return; - } - - //TODO: better unique link - $linkHolder = []; - foreach ($units as $unit) { - $link = (isset($arguments[1]) && strtolower($arguments[1]) == 'seesaw') ? $unit->link : $unit->linkgc; - - if (!$link || isset($linkHolder[$link])) { - continue; - } - - $linkHolder[$link] = true; - - $response = sprintf( - '%s: %s %s: %s', - CT::textOrange('Romaji'), - $unit->original, - CT::textOrange('Link'), - $link - ); - - $this->reply($response); - } - } - - const SIMILARLY_LEVEL = 60; - const MAX_SIMILAR = 5; - - protected function getSimilar($request) - { - parent::RedBeanConnect(self::DB_NAME); - $unitNames = R::getCol('SELECT `name` FROM ' . self::TB_NAME); - $similarNames = []; - foreach ($unitNames as $name) { - similar_text($request, $name, $percent); - if ($percent >= self::SIMILARLY_LEVEL) { - $similarNames[$name] = $percent; - } - } - ksort($similarNames); - - R::close(); - $mostSimilarNames = array_slice($similarNames, 0, self::MAX_SIMILAR); - return array_keys($mostSimilarNames); - } - - protected function getProposition($request) - { - $similar = $this->getSimilar($request); - - if (!$similar) { - $response = sprintf('Not found %s', $request); - } elseif (count($similar) == 1) { - $response = vsprintf('Did you mean %s?', $similar); - } else { - $lastElement = array_pop($similar); - $response = sprintf('Did you mean %s or %s?', - implode(', ', $similar), - $lastElement - ); - } - return $response; - - } - - protected function findUnitsViaName($name) - { - parent::RedBeanConnect(self::DB_NAME); - - $limit = ' LIMIT 5 '; - if (preg_match('/^[\x{30A0}-\x{30FF}\x{31F0}-\x{31FF}]+$/iu', $name)) { - $units = R::findAll(self::TB_NAME, "`original` like ? {$limit}", ["%{$name}%"]); - } else { - $units = R::findAll(self::TB_NAME, "`name` like ? {$limit}", [$name]); - } - - R::close(); - - return $units; - } - - protected function hasOwnList($model, $ownListName) - { - parent::RedBeanConnect(self::DB_NAME); - $found = false; - $ownListName = strtolower($ownListName); - $ownListName = ucfirst($ownListName); - $property = "own{$ownListName}List"; - if (is_array($model)) { - foreach ($model as $singleModel) { - if ($singleModel->{$property}) { - $found = true; - break; - } - } - } elseif ($model instanceof OODBBean) { - $found = (bool) ($model->{$property}); - } else { - throw new \InvalidArgumentException('Var $model must be an array or instance of OODBean.'); - } - R::close(); - - return $found; - } - - protected function unsetRequestDelay(array &$list) - { - foreach ($list as $id => $timeToClear) { - if (time() >= $timeToClear) { - unset($list[$id]); - } - } - } - - protected function setRequestDelay($id, array &$list) - { - $list[$id] = time() + self::CLEAR_TIME; - } - - protected function hasRequestDelay($id, array &$list) - { - $this->unsetRequestDelay($list); - if (isset($list[$id])) { - return true; - } - - $this->setRequestDelay($id, $list); - - return false; - } - - protected function getLinkToInfoDmmEvent() - { - $profileUrl = 'http://www.ulmf.org/bbs/member.php?u=65410'; - $dom = $this->getDOM(); - $dom->loadHTML($this->loadStreamUrl($profileUrl)); - $link = $dom->getElementById('signature'); - if ($link) { - $link = $link->getElementsByTagName('a') - ->item(0) - ->getAttribute('href'); - if ($link) { - $this->reply("Dmm event info by Petite Soeur: {$link}"); - } - } else { - $this->reply("Somethings wrong with dom."); - } - } - - const TB_NAME_OAUTH = 'oauth'; - const MAX_TOKENS = 3; - - public function generatePin() - { - parent::RedBeanConnect(self::DB_NAME); - $tokens = R::find(self::TB_NAME_OAUTH); - $response = (count($tokens) >= self::MAX_TOKENS) ? $this->trashOrReturnPin() : $this->createPin(); - $this->message($response, $this->bot->getUserNick(), IRC::NOTICE); - R::close(); - } - - private function trashOrReturnPin() - { - $tokens = R::find(self::TB_NAME_OAUTH, 'ORDER BY time ASC'); - foreach ($tokens as $token) { - if (($timeLeft = $this->checkTokenTime($token->time))) { - return sprintf("Here your pin: '%s'. Token lifetime left: %s", $token->pin, $timeLeft); - } else { - R::trash($token); - } - } - return $this->createPin(); - } - - private function createPin() - { - $token = R::dispense(self::TB_NAME_OAUTH); - $token->time = time() + (60 * 60); - $token->pin = substr(md5(sha1(uniqid(time()))), 0, 8); - $token->token = md5(sha1(uniqid(time()))); - R::store($token); - return "Here your pin: '{$token->pin}'"; - } - - private function checkTokenTime($time) - { - $left = $time - time(); - if ($left < 0) { - return false; - } - return sprintf('%d min %d sec', (int) floor($left / 60), (int) $left % 60); - } +setCommand([ + 'trigger' => 'pin', + 'action' => 'generatePin', + 'arguments' => 0, + 'channels' => ['#aigis'] + ]); + $this->setCommand([ + 'trigger' => 'unit', + 'action' => 'unit', + 'determiter' => ' ', + 'arguments' => -1, + 'channels' => ['#aigis'], + 'help' => 'Type "!unit {unit_name}" to get link to information about this unit.', + ]); + $this->setCommand([ + 'trigger' => 'cg', + 'action' => 'cg', + 'determiter' => ' ', + 'arguments' => 1, + 'channels' => ['#aigis'], + 'help' => 'Type "!cg {unit_name}" to get link to unit gallery.', + ]); + $this->setCommand([ + 'trigger' => 'dmm', + 'action' => 'getLinkToInfoDmmEvent', + 'arguments' => 0, + 'channels' => ['#aigis'], + 'help' => 'Type "!dmm" to get link to info about current dmm event.', + ]); + + parent::loadSettings($this); + } + + protected function cg($arguments) + { + $request = trim($arguments[0]); + + if ($this->hasRequestDelay($request, $this->lastCgRequest)) { + return; + } + + $units = $this->findUnitsViaName($request); + + if (!$units) { + $this->reply($this->getProposition($request)); + return; + } + + if (!$this->hasOwnList($units, 'image')) { + $this->reply("I don't have this cg (yet?)."); + return; + } + + foreach ($units as $unit) { + if (!$unit->ownImageList) { + continue; + } + + $uri = sprintf(self::GALLERY_URL, $unit->id); + + $response = sprintf( + '%s: %s %s: %s', + CT::textOrange('Romanji'), + $unit->original, + CT::textPink('NSFW'), + $uri + ); + $this->reply($response); + } + } + + protected function unit($arguments) + { + $request = trim($arguments[0]); + + if ($this->hasRequestDelay($request, $this->lastUnitRequest)) { + return; + } + + $units = $this->findUnitsViaName($request); + + if (!$units) { + $this->reply($this->getProposition($request)); + return; + } + + //TODO: better unique link + $linkHolder = []; + foreach ($units as $unit) { + $link = (isset($arguments[1]) && strtolower($arguments[1]) == 'seesaw') ? $unit->link : $unit->linkgc; + + if (!$link || isset($linkHolder[$link])) { + continue; + } + + $linkHolder[$link] = true; + + $response = sprintf( + '%s: %s %s: %s', + CT::textOrange('Romaji'), + $unit->original, + CT::textOrange('Link'), + $link + ); + + $this->reply($response); + } + } + + const SIMILARLY_LEVEL = 60; + const MAX_SIMILAR = 5; + + protected function getSimilar($request) + { + parent::RedBeanConnect(self::DB_NAME); + $unitNames = R::getCol('SELECT `name` FROM ' . self::TB_NAME); + $similarNames = []; + foreach ($unitNames as $name) { + similar_text($request, $name, $percent); + if ($percent >= self::SIMILARLY_LEVEL) { + $similarNames[$name] = $percent; + } + } + ksort($similarNames); + + R::close(); + $mostSimilarNames = array_slice($similarNames, 0, self::MAX_SIMILAR); + return array_keys($mostSimilarNames); + } + + protected function getProposition($request) + { + $similar = $this->getSimilar($request); + + if (!$similar) { + $response = sprintf('Not found %s', $request); + } elseif (count($similar) == 1) { + $response = vsprintf('Did you mean %s?', $similar); + } else { + $lastElement = array_pop($similar); + $response = sprintf('Did you mean %s or %s?', + implode(', ', $similar), + $lastElement + ); + } + return $response; + + } + + protected function findUnitsViaName($name) + { + parent::RedBeanConnect(self::DB_NAME); + + $limit = ' LIMIT 5 '; + if (preg_match('/^[\x{30A0}-\x{30FF}\x{31F0}-\x{31FF}]+$/iu', $name)) { + $units = R::findAll(self::TB_NAME, "`original` like ? {$limit}", ["%{$name}%"]); + } else { + $units = R::findAll(self::TB_NAME, "`name` like ? {$limit}", [$name]); + } + + R::close(); + + return $units; + } + + protected function hasOwnList($model, $ownListName) + { + parent::RedBeanConnect(self::DB_NAME); + $found = false; + $ownListName = strtolower($ownListName); + $ownListName = ucfirst($ownListName); + $property = "own{$ownListName}List"; + if (is_array($model)) { + foreach ($model as $singleModel) { + if ($singleModel->{$property}) { + $found = true; + break; + } + } + } elseif ($model instanceof OODBBean) { + $found = (bool) ($model->{$property}); + } else { + throw new \InvalidArgumentException('Var $model must be an array or instance of OODBean.'); + } + R::close(); + + return $found; + } + + protected function unsetRequestDelay(array &$list) + { + foreach ($list as $id => $timeToClear) { + if (time() >= $timeToClear) { + unset($list[$id]); + } + } + } + + protected function setRequestDelay($id, array &$list) + { + $list[$id] = time() + self::CLEAR_TIME; + } + + protected function hasRequestDelay($id, array &$list) + { + $this->unsetRequestDelay($list); + if (isset($list[$id])) { + return true; + } + + $this->setRequestDelay($id, $list); + + return false; + } + + protected function getLinkToInfoDmmEvent() + { + $profileUrl = 'http://www.ulmf.org/bbs/member.php?u=65410'; + $dom = $this->getDOM(); + $dom->loadHTML($this->loadStreamUrl($profileUrl)); + $link = $dom->getElementById('signature'); + if ($link) { + $link = $link->getElementsByTagName('a') + ->item(0) + ->getAttribute('href'); + if ($link) { + $this->reply("Dmm event info by Petite Soeur: {$link}"); + } + } else { + $this->reply("Somethings wrong with dom."); + } + } + + const TB_NAME_OAUTH = 'oauth'; + const MAX_TOKENS = 3; + + public function generatePin() + { + parent::RedBeanConnect(self::DB_NAME); + $tokens = R::find(self::TB_NAME_OAUTH); + $response = (count($tokens) >= self::MAX_TOKENS) ? $this->trashOrReturnPin() : $this->createPin(); + $this->message($response, $this->bot->getUserNick(), IRC::NOTICE); + R::close(); + } + + private function trashOrReturnPin() + { + $tokens = R::find(self::TB_NAME_OAUTH, 'ORDER BY time ASC'); + foreach ($tokens as $token) { + if (($timeLeft = $this->checkTokenTime($token->time))) { + return sprintf("Here your pin: '%s'. Token lifetime left: %s", $token->pin, $timeLeft); + } else { + R::trash($token); + } + } + return $this->createPin(); + } + + private function createPin() + { + $token = R::dispense(self::TB_NAME_OAUTH); + $token->time = time() + (60 * 60); + $token->pin = substr(md5(sha1(uniqid(time()))), 0, 8); + $token->token = md5(sha1(uniqid(time()))); + R::store($token); + return "Here your pin: '{$token->pin}'"; + } + + private function checkTokenTime($time) + { + $left = $time - time(); + if ($left < 0) { + return false; + } + return sprintf('%d min %d sec', (int) floor($left / 60), (int) $left % 60); + } } \ No newline at end of file diff --git a/module/ApiProxy.php b/module/api-proxy/ApiProxy.php similarity index 90% rename from module/ApiProxy.php rename to module/api-proxy/ApiProxy.php index 29504f6..b11daa3 100644 --- a/module/ApiProxy.php +++ b/module/api-proxy/ApiProxy.php @@ -1,64 +1,64 @@ -setCommand([ - 'trigger' => 'api', - 'action' => 'getResponseFromQuery', - 'arguments' => -1, - 'channels' => ['#touhoupl'], - 'permit' => true - ]); - parent::loadSettings($this); - } - - public function saveSettings() - { - return parent::saveSettings(); - } - - //> !api param:value query1 query2 - protected function getResponseFromQuery(array $arguments = []) - { - if (!$arguments) { - return; - } - $trzeciAgrumentDoCallbacka = implode(' ', $arguments); - $params = []; - $query = preg_replace_callback(self::QUERY_REGEX, - function($m) use (&$params) { - $params[$m[1]] = $m[2]; - },$trzeciAgrumentDoCallbacka); - - $url = self::URL_API . '?' . http_build_query(['q' => trim($query)] + $params); - - $response = json_decode($this->loadStreamUrl($url), true); - - if ($response) { - return $this->reply($this->flat($response)); - } - } - - private function flat(array $array) - { - $string = ''; - foreach ($array as $key => $value) { - if (is_array($value)) { - $value = $this->flat($value); - } elseif (is_string($value)) { - $string .= $key . ':' . $value . ' '; - } - } - return rtrim($string, ' '); - } +setCommand([ + 'trigger' => 'api', + 'action' => 'getResponseFromQuery', + 'arguments' => -1, + 'channels' => ['#touhoupl'], + 'permit' => true + ]); + parent::loadSettings($this); + } + + public function saveSettings() + { + return parent::saveSettings(); + } + + //> !api param:value query1 query2 + protected function getResponseFromQuery(array $arguments = []) + { + if (!$arguments) { + return; + } + $trzeciAgrumentDoCallbacka = implode(' ', $arguments); + $params = []; + $query = preg_replace_callback(self::QUERY_REGEX, + function($m) use (&$params) { + $params[$m[1]] = $m[2]; + },$trzeciAgrumentDoCallbacka); + + $url = self::URL_API . '?' . http_build_query(['q' => trim($query)] + $params); + + $response = json_decode($this->loadStreamUrl($url), true); + + if ($response) { + $this->reply($this->flat($response)); + } + } + + private function flat(array $array) + { + $string = ''; + foreach ($array as $key => $value) { + if (is_array($value)) { + $value = $this->flat($value); + } elseif (is_string($value)) { + $string .= $key . ':' . $value . ' '; + } + } + return rtrim($string, ' '); + } } \ No newline at end of file diff --git a/module/Basic.php b/module/basic/Basic.php similarity index 84% rename from module/Basic.php rename to module/basic/Basic.php index ced9c0f..79eba89 100644 --- a/module/Basic.php +++ b/module/basic/Basic.php @@ -1,147 +1,143 @@ -on(IRC::JOIN, 'addChannel'); - $this->on(IRC::KICK, 'reJoin'); - $this->on(IRC::RplWelcome, 'ghostInDaShell'); - $this->on(IRC::RplWelcome, 'joinOnLogin'); - $this->on(IRC::ErrNickNameInUse, 'nickNameInUse'); - $this->on(IRC::PING, 'pong'); - $this->on(IRC::ErrErroneusNickname, 'CloseBot', ['To Large Nickname']); - $this->on(IRC::RplNamReply, 'addNickToChannel'); - $this->on(IRC::RplEndOfNames, 'addNickToChannel', [true]); - $this->on(IRC::ErrBannedFromChan, 'unban'); - if(Config::$serverName == 'quakenet'){ - $this->on(IRC::RplWelcome, 'loginToQ'); - } - - - if ($this->bot->getUserNick() == self::NICKSERV) { - $this->on(IRC::NOTICE, 'nickServ'); - } - } - protected function loginToQ() - { - $this->message('auth tokido ' . Config::$personal->password, 'Q@CServe.quakenet.org'); - } - - protected function addChannel() - { - if (Config::getNick() == $this->bot->getUserNick()) { - $channel = ($this->bot->getSource()) ? $this->bot->getSource() : $this->bot->getMessage(); - $this->bot->channelList[$channel] = []; - } - } - - protected function reJoin() - { - if (Config::getNick() == $this->bot->getOffset()) { - $this->message($this->bot->getSource(), null, IRC::JOIN); - } - } - - protected function nickServ() - { - if (strpos($this->bot->getMessage(), 'This nickname is registered') !== false && !empty(Config::$personal->identify)) { - $this->message(Config::$personal->identify, null, IRC::IDENTIFY); - } - - if ($this->ghost == true && strpos($this->bot->getMessage(), 'Ghost with your nick has been killed') !== false) { - $this->message(Config::$personal->nick, null, IRC::NICK, true); - } - } - - protected function unban() - { - $this->message('UNBAN ' . $this->bot->getSource(), self::CHANSERV, IRC::PRIVMSG, true); - $this->message($this->bot->getSource(), null, IRC::JOIN); - } - - protected function pong() - { - /* tell me where i need to send pong? */ - if (Config::getServerName() == 'quakenet') { - $this->message($this->bot->getMessage(), null, IRC::PING, true); - } else { - $this->message(Config::$server . ':' . Config::$port, null, IRC::PING, true); - } - } - - protected function addNickToChannel($done = false) - { - $source = $this->bot->getSource(); - if ($done && !empty($this->bot->channelList[$source])) { - array_push((array) $this->bot->channelList[$source], explode(' ', $this->nameReplyBuffer[$source])); - unset($this->nameReplyBuffer[$source]); - } else { - if (empty($this->nameReplyBuffer[$source])) { - $this->nameReplyBuffer[$source] = ''; - } - if (isset($this->bot->channelList[$source])) { - $this->nameReplyBuffer[$source] .= $this->bot->getMessage(); - } - } - } - - protected function nickNameInUse() - { - Config::setNick(Config::getNick() . ++$this->nickCounter); - $this->message(Config::getNick(), null, IRC::NICK); - $this->ghost = true; - } - - protected function ghostInDaShell() - { - if ($this->ghost) { - $message = 'GHOST' . Config::$personal->nick . ' ' . Config::$personal->identify; - $this->message($message, self::NICKSERV, IRC::PRIVMSG); - $this->ghost = false; - } - } - - protected function CloseBot($message) - { - die($message); - } - - protected function joinOnLogin() - { - $channel = Config::$channels; - if (empty($channel)) { - return; - } elseif (is_array($channel)) { - $this->message(implode(',', $channel), null, IRC::JOIN); - } else { - $this->message($channel, null, IRC::JOIN); - } - } -} +on(IRC::JOIN, 'addChannel'); + $this->on(IRC::KICK, 'reJoin'); + $this->on(IRC::RplWelcome, 'ghostInDaShell'); + $this->on(IRC::RplWelcome, 'joinOnLogin'); + $this->on(IRC::ErrNickNameInUse, 'nickNameInUse'); + $this->on(IRC::PING, 'pong'); + $this->on(IRC::ErrErroneusNickname, 'CloseBot', ['To Large Nickname']); + $this->on(IRC::RplNamReply, 'addNickToChannel'); + $this->on(IRC::RplEndOfNames, 'addNickToChannel', [true]); + $this->on(IRC::ErrBannedFromChan, 'unban'); + if (Config::$serverName == 'quakenet') { + $this->on(IRC::RplWelcome, 'loginToQ'); + } + + + if ($this->bot->getUserNick() == self::NICKSERV) { + $this->on(IRC::NOTICE, 'nickServ'); + } + } + + protected function loginToQ() + { + $this->message('auth tokido ' . Config::$personal->password, 'Q@CServe.quakenet.org'); + } + + protected function addChannel() + { + if (Config::getNick() == $this->bot->getUserNick()) { + $channel = ($this->bot->getSource()) ? $this->bot->getSource() : $this->bot->getMessage(); + $this->bot->channelList[$channel] = []; + } + } + + protected function reJoin() + { + if (Config::getNick() == $this->bot->getOffset()) { + $this->message($this->bot->getSource(), null, IRC::JOIN); + } + } + + protected function nickServ() + { + if (strpos($this->bot->getMessage(), + 'This nickname is registered') !== false && !empty(Config::$personal->identify) + ) { + $this->message(Config::$personal->identify, null, IRC::IDENTIFY); + } + + if ($this->ghost == true && strpos($this->bot->getMessage(), + 'Ghost with your nick has been killed') !== false + ) { + $this->message(Config::$personal->nick, null, IRC::NICK, true); + } + } + + protected function unban() + { + $this->message('UNBAN ' . $this->bot->getSource(), self::CHANSERV, IRC::PRIVMSG, true); + $this->message($this->bot->getSource(), null, IRC::JOIN); + } + + protected function pong() + { + /* tell me where i need to send pong? */ + if (Config::getServerName() == 'quakenet') { + $this->message($this->bot->getMessage(), null, IRC::PING, true); + } else { + $this->message(Config::$server . ':' . Config::$port, null, IRC::PING, true); + } + } + + protected function addNickToChannel($done = false) + { + $source = $this->bot->getSource(); + if ($done && !empty($this->bot->channelList[$source])) { + array_push((array) $this->bot->channelList[$source], explode(' ', $this->nameReplyBuffer[$source])); + unset($this->nameReplyBuffer[$source]); + } else { + if (empty($this->nameReplyBuffer[$source])) { + $this->nameReplyBuffer[$source] = ''; + } + if (isset($this->bot->channelList[$source])) { + $this->nameReplyBuffer[$source] .= $this->bot->getMessage(); + } + } + } + + protected function nickNameInUse() + { + Config::setNick(Config::getNick() . ++$this->nickCounter); + $this->message(Config::getNick(), null, IRC::NICK); + $this->ghost = true; + } + + protected function ghostInDaShell() + { + if ($this->ghost) { + $message = 'GHOST' . Config::$personal->nick . ' ' . Config::$personal->identify; + $this->message($message, self::NICKSERV, IRC::PRIVMSG); + $this->ghost = false; + } + } + + protected function CloseBot($message) + { + die($message); + } + + protected function joinOnLogin() + { + $channel = Config::$channels; + if (empty($channel)) { + return; + } elseif (is_array($channel)) { + $this->message(implode(',', $channel), null, IRC::JOIN); + } else { + $this->message($channel, null, IRC::JOIN); + } + } +} diff --git a/module/Chatlog.php b/module/basic/Chatlog.php similarity index 94% rename from module/Chatlog.php rename to module/basic/Chatlog.php index 072427b..d672bf0 100644 --- a/module/Chatlog.php +++ b/module/basic/Chatlog.php @@ -1,82 +1,82 @@ -saveData(); - } - - public function saveData($out = false) - { - $timestamp = '[' . date('H:i') . ']'; - $source = $this->bot->getSource(); - $message = $this->bot->getMessage(); - $userNick = $this->bot->getUserNick(); - $folder = implode(DIRECTORY_SEPARATOR, [Config::$logFolder, Config::getServerName()]); - /* $userName = $this->getUserName(); */ - /* $userHost = $this->getUserHost(); */ - if (!$out) { - switch ($this->bot->getType()) { - case IRC::PRIVMSG: - $text = "{$timestamp} <{$userNick}> {$message}" . IRC_EOL; - if (strpos($source, '#') === 0) { - $filename = $source . '_' . date('Y-m-d'); - $filepatch = implode(DIRECTORY_SEPARATOR, [$folder, substr($source, 1)]); - } else { - $filename = $source; - $filepatch = $folder; - } - static::push($text, $filepatch, $filename . '.log'); - return $text; - case IRC::JOIN: - break; - /* $text = "{$timestamp} {$userNick} (~{$userName}@{$userHost}) has joined.\r\n"; - $filename = $message; - return \Library\IRC\SaveData::push($text, $filepatch, $filename . '.log'); */ - case IRC::PART: - break; - /* $info = ($this->message) ? ' (' . $this->message . ')' : ''; - $text = $timestamp . ' ' . $this->userNick . ' (~' . $this->userName . '@' . $this->userHost . ') has parted.' . $info . "\r\n"; - $filename = $this->source; - return \Library\IRC\SaveData::push($text, $filepatch, $filename . '.log'); */ - case IRC::QUIT: - break; - /* $info = ($this->message) ? ' (' . $this->message . ')' : ''; - $text = $timestamp . ' ' . $this->userNick . ' (~' . $this->userName . '@' . $this->userHost . ') has quit.' . $info . "\r\n"; - $filename = 'QUIT'; //$this->msgChan; - return \Library\IRC\SaveData::push($text, $filepatch, $filename . '.log'); */ - case IRC::KICK: - break; - /* $info = ($this->message) ? ' (' . $this->message . ')' : ''; - $special = explode(' ', $this->source); - $text = $timestamp . ' * ' . $special [1] . ' was kicked by ' . $special[0] . ' ' . $info . "\r\n"; - return \Library\IRC\SaveData::push($text, $filepatch, $filename . '.log'); */ - - case IRC::NOTICE: - break; - /* return \Library\IRC\SaveData::push($text, $filepatch, $filename . '.log'); */ - } - } else { - - } - } - - public static function push($msg, $pathname, $filename) - { - $pathname = strtolower($pathname); - $filename = strtolower($filename); - if (!is_dir($pathname)) { - mkdir($pathname, 0777, true); - } - $dir = implode(DIRECTORY_SEPARATOR, [$pathname, $filename]); - return file_put_contents($dir, $msg, FILE_APPEND); - } -} +saveData(); + } + + public function saveData($out = false) + { + $timestamp = '[' . date('H:i') . ']'; + $source = $this->bot->getSource(); + $message = $this->bot->getMessage(); + $userNick = $this->bot->getUserNick(); + $folder = implode(DIRECTORY_SEPARATOR, [Config::$logFolder, Config::getServerName()]); + /* $userName = $this->getUserName(); */ + /* $userHost = $this->getUserHost(); */ + if (!$out) { + switch ($this->bot->getType()) { + case IRC::PRIVMSG: + $text = "{$timestamp} <{$userNick}> {$message}" . IRC_EOL; + if (strpos($source, '#') === 0) { + $filename = $source . '_' . date('Y-m-d'); + $filepatch = implode(DIRECTORY_SEPARATOR, [$folder, substr($source, 1)]); + } else { + $filename = $source; + $filepatch = $folder; + } + static::push($text, $filepatch, $filename . '.log'); + return $text; + case IRC::JOIN: + break; + /* $text = "{$timestamp} {$userNick} (~{$userName}@{$userHost}) has joined.\r\n"; + $filename = $message; + return \Library\IRC\SaveData::push($text, $filepatch, $filename . '.log'); */ + case IRC::PART: + break; + /* $info = ($this->message) ? ' (' . $this->message . ')' : ''; + $text = $timestamp . ' ' . $this->userNick . ' (~' . $this->userName . '@' . $this->userHost . ') has parted.' . $info . "\r\n"; + $filename = $this->source; + return \Library\IRC\SaveData::push($text, $filepatch, $filename . '.log'); */ + case IRC::QUIT: + break; + /* $info = ($this->message) ? ' (' . $this->message . ')' : ''; + $text = $timestamp . ' ' . $this->userNick . ' (~' . $this->userName . '@' . $this->userHost . ') has quit.' . $info . "\r\n"; + $filename = 'QUIT'; //$this->msgChan; + return \Library\IRC\SaveData::push($text, $filepatch, $filename . '.log'); */ + case IRC::KICK: + break; + /* $info = ($this->message) ? ' (' . $this->message . ')' : ''; + $special = explode(' ', $this->source); + $text = $timestamp . ' * ' . $special [1] . ' was kicked by ' . $special[0] . ' ' . $info . "\r\n"; + return \Library\IRC\SaveData::push($text, $filepatch, $filename . '.log'); */ + + case IRC::NOTICE: + break; + /* return \Library\IRC\SaveData::push($text, $filepatch, $filename . '.log'); */ + } + } else { + + } + } + + public static function push($msg, $pathname, $filename) + { + $pathname = strtolower($pathname); + $filename = strtolower($filename); + if (!is_dir($pathname)) { + mkdir($pathname, 0777, true); + } + $dir = implode(DIRECTORY_SEPARATOR, [$pathname, $filename]); + return file_put_contents($dir, $msg, FILE_APPEND); + } +} diff --git a/module/Commands.php b/module/basic/Commands.php similarity index 82% rename from module/Commands.php rename to module/basic/Commands.php index 78df4a5..7f4aaab 100644 --- a/module/Commands.php +++ b/module/basic/Commands.php @@ -1,224 +1,217 @@ -setCommand([ - 'trigger' => 'cmd', - 'action' => 'trigger', - 'arguments' => -1, - 'permit' => true - ]); - - $this->setCommand([ - 'trigger' => 'bye', - 'action' => 'quit', - 'permit' => true - ]); - $this->setCommand([ - 'trigger' => 'restart', - 'action' => 'restart', - 'permit' => true - ]); - $this->setCommand([ - 'arguments' => -1, - 'trigger' => 'say', - 'action' => 'say', - 'permit' => true - ]); - $this->setCommand([ - 'arguments' => 1, - 'trigger' => 'part', - 'action' => 'part', - 'help' => 'Type "!part #" for part a channel.', - 'permit' => true - ]); - $this->setCommand([ - 'arguments' => 1, - 'trigger' => 'join', - 'action' => 'join', - 'help' => 'Type "!join #" for join to channel.', - 'permit' => true - ]); - $this->setCommand([ - 'arguments' => -1, - 'trigger' => 'help', - 'action' => 'help', - 'help' => 'Type "!help" for help or "!help " for help for command.', - 'permit' => false - ]); - parent::loadSettings($this); - } - - protected function quit() - { - $this->reply('bye bye'); - $this->message('Sayounara', null, 'QUIT', true); - exit(); - } - - protected function restart() - { - // Exit from Sever - $this->message('I will be back', null, 'QUIT', true); - // Reconnect to Server - $this->bot->connectToServer(); - } - - protected function say(array $arguments = []) - { - if (!$arguments) { - return; - } - $target = $arguments[0]; - unset($arguments[0]); - $this->message(implode(' ', $arguments), $target); - } - - protected function part(array $arguments) - { - $channel = $arguments[0]; - - if (strpos($channel, '#') !== 0) { - $channel = '#' . $channel; - } - - $this->message('Cya, nerds', $channel, 'PART'); - } - - protected function join(array $arguments) - { - $channel = $arguments[0]; - if (strpos($channel, '#') !== 0) { - $channel = '#' . $channel; - } - $this->message($channel, null, 'JOIN'); - } - - protected function help(array $arguments = []) - { - $commandList = []; - foreach ($this->bot->module as $module) { - if (!$module->commands) { - continue; - } - foreach ($module->commands as $name => $command) { - if ($command['permit']) { - continue; - } - if (!$this->checkCommand($command, Module::CHECK_CHAN)) { - continue; - } - if (!empty($arguments[0])) { - if ($arguments[0] == $name) { - return $this->reply(($command['help']) ? $command['help'] : "Just type \"!{$command['trigger']}\""); - } - } else { - $commandList[] = $command['trigger']; - } - } - } - if ($commandList) { - $this->reply('I\'m a spy so I know some commands. "!' . implode('"; "!', $commandList) . '";'); - $this->reply('Type "!help " for help'); - } - } - - protected function trigger(array $arguments = []) - { - $mode = trim($arguments[0]); - $parsedArguments = []; - if ($mode != self::TRIGGER_DELETE) { - foreach ($arguments as $argument) { - if (strpos($argument, ':') === false) { - $parsedArguments[] = trim($argument); - } else { - $column = explode(':', $argument, 2); - $parsedArguments[trim($column[0])] = trim($column[1]); - } - } - $parsedArguments['trigger'] = isset($parsedArguments['trigger']) ? $parsedArguments['trigger'] : null; - $parsedArguments['channels'] = isset($parsedArguments['channels']) ? explode(',', $parsedArguments['channels']) : null; - $parsedArguments['reply'] = isset($parsedArguments['reply']) ? str_replace('_', ' ', $parsedArguments['reply']) : null; - $parsedArguments['notice'] = isset($parsedArguments['notice']) ? str_replace('_', ' ', $parsedArguments['notice']) : null; - $parsedArguments['regex'] = isset($parsedArguments['regex']) ? $parsedArguments['regex'] : null; - $parsedArguments['nick'] = isset($parsedArguments['nick']) ? $parsedArguments['nick'] : null; - $parsedArguments['name'] = isset($parsedArguments['name']) ? $parsedArguments['name'] : null; - $parsedArguments['host'] = isset($parsedArguments['host']) ? $parsedArguments['host'] : null; - - //array_map('trim', $arguments['channels']); - $command = [ - 'trigger' => (string) $parsedArguments['trigger'], - 'reply' => (string) $parsedArguments['reply'], - 'notice' => (string) $parsedArguments['notice'], - 'channels' => (array) $parsedArguments['channels'], - 'ban' => [ - 'regex' => (string) $parsedArguments['regex'], - 'nick' => (string) $parsedArguments['nick'], - 'name' => (string) $parsedArguments['name'], - 'host' => (string) $parsedArguments['host'] - ] - ]; - } - switch ($mode) { - case self::TRIGGER_ADD: - if (empty($parsedArguments['trigger'])) { - return $this->reply('You shall type a trigger.'); - } - if (empty($parsedArguments['reply']) && empty($parsedArguments['notice'])) { - return $this->reply('You shall type reply message.'); - } - if ($this->setCommand($command)) { - $this->reply("Command {$command['trigger']} was loaded."); - } else { - $this->reply("Command {$command['trigger']} exists."); - } - break; - case self::TRIGGER_DELETE: - if (isset($arguments[1])) { - $name = trim(strtolower($arguments[1])); - if ($this->unsetCommand($name)) { - return $this->reply("Command {$name} was deleted."); - } else { - return $this->reply("Command {$name} not found."); - } - } else { - return $this->reply("Must type a name of command."); - } - case self::TRIGGER_EDIT: - if (empty($parsedArguments['trigger'])) { - return $this->reply('You shall type a trigger.'); - } - return $this->reply('Option not avaible.'); - default: - return false; - } - } - - public function propertyToSave() - { - return [ - 'commands' => $this->commands - ]; - } -} +setCommand([ + 'trigger' => 'cmd', + 'action' => 'trigger', + 'arguments' => -1, + 'permit' => true + ]); + + $this->setCommand([ + 'trigger' => 'bye', + 'action' => 'quit', + 'permit' => true + ]); + $this->setCommand([ + 'trigger' => 'restart', + 'action' => 'restart', + 'permit' => true + ]); + $this->setCommand([ + 'arguments' => -1, + 'trigger' => 'say', + 'action' => 'say', + 'permit' => true + ]); + $this->setCommand([ + 'arguments' => 1, + 'trigger' => 'part', + 'action' => 'part', + 'help' => 'Type "!part #" for part a channel.', + 'permit' => true + ]); + $this->setCommand([ + 'arguments' => 1, + 'trigger' => 'join', + 'action' => 'join', + 'help' => 'Type "!join #" for join to channel.', + 'permit' => true + ]); + $this->setCommand([ + 'arguments' => -1, + 'trigger' => 'help', + 'action' => 'help', + 'help' => 'Type "!help" for help or "!help " for help for command.', + 'permit' => false + ]); + parent::loadSettings($this); + } + + protected function quit() + { + $this->reply('bye bye'); + $this->message('Sayounara', null, 'QUIT', true); + exit(); + } + + protected function restart() + { + // Exit from Sever + $this->message('I will be back', null, 'QUIT', true); + // Reconnect to Server + $this->bot->connectToServer(); + } + + protected function say(array $arguments = []) + { + if (!$arguments) { + return; + } + $target = $arguments[0]; + unset($arguments[0]); + $this->message(implode(' ', $arguments), $target); + } + + protected function part(array $arguments) + { + $channel = $arguments[0]; + + if (strpos($channel, '#') !== 0) { + $channel = '#' . $channel; + } + + $this->message('Cya, nerds', $channel, 'PART'); + } + + protected function join(array $arguments) + { + $channel = $arguments[0]; + if (strpos($channel, '#') !== 0) { + $channel = '#' . $channel; + } + $this->message($channel, null, 'JOIN'); + } + + protected function help(array $arguments = []) + { + $commandList = []; + foreach ($this->bot->module as $module) { + if (!$module->commands) { + continue; + } + foreach ($module->commands as $name => $command) { + if ($command['permit']) { + continue; + } + if (!$this->checkCommand($command, Module::CHECK_CHAN)) { + continue; + } + if (!empty($arguments[0])) { + if ($arguments[0] == $name) { + $this->reply(($command['help']) ? $command['help'] : "Just type \"!{$command['trigger']}\""); + } + } else { + $commandList[] = $command['trigger']; + } + } + } + if ($commandList) { + $this->reply('I\'m a spy so I know some commands. "!' . implode('"; "!', $commandList) . '";'); + $this->reply('Type "!help " for help'); + } + } + + protected function trigger(array $arguments = []) + { + $mode = trim($arguments[0]); + $parsedArguments = []; + if ($mode != self::TRIGGER_DELETE) { + foreach ($arguments as $argument) { + if (strpos($argument, ':') === false) { + $parsedArguments[] = trim($argument); + } else { + $column = explode(':', $argument, 2); + $parsedArguments[trim($column[0])] = trim($column[1]); + } + } + $parsedArguments['trigger'] = isset($parsedArguments['trigger']) ? $parsedArguments['trigger'] : null; + $parsedArguments['channels'] = isset($parsedArguments['channels']) ? explode(',', + $parsedArguments['channels']) : null; + $parsedArguments['reply'] = isset($parsedArguments['reply']) ? str_replace('_', ' ', + $parsedArguments['reply']) : null; + $parsedArguments['notice'] = isset($parsedArguments['notice']) ? str_replace('_', ' ', + $parsedArguments['notice']) : null; + $parsedArguments['regex'] = isset($parsedArguments['regex']) ? $parsedArguments['regex'] : null; + $parsedArguments['nick'] = isset($parsedArguments['nick']) ? $parsedArguments['nick'] : null; + $parsedArguments['name'] = isset($parsedArguments['name']) ? $parsedArguments['name'] : null; + $parsedArguments['host'] = isset($parsedArguments['host']) ? $parsedArguments['host'] : null; + + //array_map('trim', $arguments['channels']); + $command = [ + 'trigger' => (string) $parsedArguments['trigger'], + 'reply' => (string) $parsedArguments['reply'], + 'notice' => (string) $parsedArguments['notice'], + 'channels' => (array) $parsedArguments['channels'], + 'ban' => [ + 'regex' => (string) $parsedArguments['regex'], + 'nick' => (string) $parsedArguments['nick'], + 'name' => (string) $parsedArguments['name'], + 'host' => (string) $parsedArguments['host'] + ] + ]; + } + switch ($mode) { + case self::TRIGGER_ADD: + if (empty($parsedArguments['trigger'])) { + $this->reply('You shall type a trigger.'); + } + if (empty($parsedArguments['reply']) && empty($parsedArguments['notice'])) { + $this->reply('You shall type reply message.'); + } + if ($this->setCommand($command)) { + $this->reply("Command {$command['trigger']} was loaded."); + } else { + $this->reply("Command {$command['trigger']} exists."); + } + break; + case self::TRIGGER_DELETE: + if (isset($arguments[1])) { + $name = trim(strtolower($arguments[1])); + if ($this->unsetCommand($name)) { + $this->reply("Command {$name} was deleted."); + } else { + $this->reply("Command {$name} not found."); + } + } else { + $this->reply("Must type a name of command."); + } + case self::TRIGGER_EDIT: + if (empty($parsedArguments['trigger'])) { + $this->reply('You shall type a trigger.'); + } + $this->reply('Option not avaible.'); + default: + //todo @throw Exception + } + } + + public function propertyToSave() + { + return [ + 'commands' => $this->commands + ]; + } +} diff --git a/module/Ctcp.php b/module/ctcp/Ctcp.php similarity index 83% rename from module/Ctcp.php rename to module/ctcp/Ctcp.php index 13ada5f..1937603 100644 --- a/module/Ctcp.php +++ b/module/ctcp/Ctcp.php @@ -1,18 +1,11 @@ setDictionary(); - } - - private function setDictionary() - { - if (!file_exists($this->dir)) - file_put_contents($this->dir, json_encode([])); - $this->dictionary = json_decode(file_get_contents($this->dir), TRUE); - } - - public function addRule($in = []) - { - if (empty($in)) - return; - if (!is_array($in)) - $in = explode(' ', strtolower($in)); - else - $in = array_map("strtolower", $in); - array_shift($in); - $in[1] = implode(' ',array_slice($in,1)); - $this->dictionary[$in[0]] = $in[1]; - return file_put_contents($this->dir, json_encode($this->dictionary, JSON_PRETTY_PRINT)); - } - - public function cenStr($str = '') - { - if (empty($str)) - return; - print_r($this->dictionary); - echo "\r\n"; - print_r($str); - echo "\r\n"; - return str_ireplace(array_keys($this->dictionary), array_values($this->dictionary), $str); - } - -} diff --git a/module/dictionary/dict/dictionary.json b/module/dictionary/dict/dictionary.json deleted file mode 100644 index bd4479f..0000000 --- a/module/dictionary/dict/dictionary.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "chuj": "c**j", - "kurwa": "k***a", - "cipa": "c***a" -} \ No newline at end of file diff --git a/module/Fun.php b/module/fun/Fun.php similarity index 95% rename from module/Fun.php rename to module/fun/Fun.php index ddf87d1..3d73e16 100644 --- a/module/Fun.php +++ b/module/fun/Fun.php @@ -1,256 +1,253 @@ - 'rating:explicit', - 'SAFE' => 'rating:safe', - 'QUES' => 'rating:questionable' - ], - $api, $rate; - - public function loadSettings($object = null) - { - libxml_set_streams_context($this->ctx); - libxml_use_internal_errors(true); - $this->setCommand([ - 'trigger' => 'c', - 'action' => 'c', - 'arguments' => -1, - 'determiter' => ',', - 'help' => 'Randomize arguments. Determiter is set as ",". Example: "!c apple, banana, oranges".', - 'ban'=> [ - 'host' => 'FBF0D8DB.5BE561A6.7DCB3F4E.IP' - ] - - ]); - - $this->setCommand([ - 'trigger' => 'random', - 'action' => 'random', - 'arguments' => -1, - 'help' => '"!random" default search loli, but you can find anything you want. ' . - 'You can change rating by adding safe|nsfw|ques to arguments and change ' . - 'image server by adding yan (yande.re).', - 'ban' => - [ - 'nick' => 'Thebassa' - ] - ]); - - $this->setCommand([ - 'trigger' => 'biba', - 'reply' => 'Biba dance: https://www.youtube.com/watch?v=kpJcgkEdMRg' - ]); - - $this->setCommand([ - 'trigger' => 'maido', - 'reply' => 'Maido dance: https://www.youtube.com/watch?v=a-7_XdPktgc' - ]); - $this->setCommand([ - 'trigger' => 'mikuluka', - 'reply' => 'https://www.youtube.com/watch?v=ZllY2wBLYN4' - ]); - - $this->setCommand([ - 'trigger' => 'rolypoly', - 'reply' => 'Roly-poly: http://www.youtube.com/watch?v=3Xolk2cFzlo' - ]); - - $this->setCommand([ - 'trigger' => 'weaboo', - 'reply' => 'Weaboo song: https://www.youtube.com/watch?v=TBfWKmRFTjM' - ]); - - $this->setCommand([ - 'trigger' => 'xandros', - 'reply' => '[9:58pm] xandros, kup sobie slownik' - ]); - - $this->setCommand([ - 'trigger' => 'cycki', - 'action' => 'cycki' - ]); - $this->setCommand([ - 'action' => function () { - $this->user->mode($this->bot->getSource(),'+b', ['Thebassa']); - $this->user->kick($this->bot->getSource(), 'Thebassa', 'nie jestem zawiedziona'); - }, - 'trigger' => 'baka', - 'permit' => true, - ]); - - - - parent::loadSettings($this); - } - - protected function cycki() - { - $stream = $this->loadStreamUrl('http://api.oboobs.ru/noise/1/'); - $json = json_decode($stream); - if (!empty($json[0])) { - $json = $json[0]; - $message = IRCHelper::colorText('Tits', IRCHelper::COLOR_ORANGE) . ': '; - $message .= IRCHelper::colorText('NSFW', IRCHelper::COLOR_PINK) . ' '; - $message .= 'http://media.oboobs.ru/' . $json->preview; - } else { - $message = 'Can\'t get api'; - } - $this->reply($message); - } - - protected function c(array $arguments = []) - { - if (count(array_unique(array_map('trim', $arguments))) >= 2) { - $this->reply(trim($arguments[mt_rand(0, count($arguments) - 1)])); - } else { - $this->reply('Wrong arguments. Type "!Help c" to help'); - } - } - - protected function random(array $arguments = []) - { - $arguments = $this->setApi($arguments); - $arguments = $this->setRate($arguments); - if (!$arguments) { - return false; - } - - - - $tags = array_map('strtolower', array_merge($arguments, [$this->rate])); - $url = $this->api . 'tags=' . trim(implode('+', $tags)); - $html = $this->loadStreamUrl($url); - if (!$html) { - return $this->reply('I can\'t open api url.'); - } - $doc = $this->getDOM(); - if (!$doc->loadHTML($html)) { - return $this->reply('I can\'t open api url.'); - } - - if ($doc->getElementsByTagName('posts')->length == 0 || - empty($doc->getElementsByTagName('posts') - ->item(0) - ->getAttribute('count'))) { - return $this->reply('Sorry, I didn\'t find ' . trim(implode(' ', $arguments)) . '.'); - } - $count = $doc->getElementsByTagName('posts') - ->item(0) - ->getAttribute('count'); - - $random = mt_rand(0, $count - 1); - $pid = floor($random / 100); - - switch ($this->api) { - case self::API_GEL: - $url .= '&json=1&pid=' . $pid; - break; - case self::API_YAN: - $url = str_ireplace('.xml', '.json', $url) . '&limit=100&page=' . $pid; - break; - } - $newHtml = $this->loadStreamUrl($url); - if (!$newHtml) { - return $this->reply('Can\'t load html to dom.'); - } - $image = json_decode($newHtml)[$random % 100]; - $url = $this->shortIt($image->file_url, - ($this->api == self::API_GEL) ? - $image->hash : $image->md5); - $warn = ''; - switch ($image->rating) { - case self::RATING_NSFW: - $warn = IRCHelper::colorText('NSFW', IRCHelper::COLOR_PINK); - break; - case self::RATING_SAFE: - $warn = IRCHelper::colorText('Safe', IRCHelper::COLOR_GREEN); - break; - case static::RATING_QUESTIONABLE: - $warn = IRCHelper::colorText('Questionable', IRCHelper::COLOR_ORANGE); - break; - } - $tag = (!empty($arguments)) ? ' ' . trim(implode(' ', $arguments)) : ''; - $this->reply("Random{$tag}: {$warn} {$url} (from {$count} pic)"); - } - - private function shortIt($url, $md5) - { - if (!self::API_SHORT) { - return $url; - } - - parent::RedBeanConnect('short'); - if (($fetch = @R::findOne('short_url', '`title` = ?', [$md5]))) { - return self::API_SHORT . $fetch->keyword; - } - $timestamp = date('Y-m-d H:i:s'); - do { - $uniq = ''; - $base = strtolower(hash('sha256', uniqid())); - while (strlen($uniq) < 8) { - $uniq .= substr($base, (int) -(strlen($base) / (1 + strlen($uniq))), 1); - } - } while (@R::findOne('short_url', '`keyword` = ?', [$uniq])); - $sql = 'INSERT INTO `short`.`short_url` '; - $sql .="(`keyword`, `url`, `title`, `timestamp`, `ip`, `clicks`) "; - $sql .= "VALUES ('{$uniq}', '{$url}', '{$md5}', '{$timestamp}', '"; - $sql .= getHostByName(getHostName()) . "', '0')"; - R::exec($sql); - R::close(); - return 'http://exsubs.anidb.pl/short/' . $uniq; - } - - private function setApi(array $arguments) - { - $key = array_search(self::TRIGGER_GEL, array_map('strtoupper', $arguments)); - if ($key !== false) { - $this->api = self::API_GEL; - unset($arguments[$key]); - } else { - $this->api = self::API_YAN; - } - return $arguments; - } - - private function setRate(array $arguments) - { - $this->rate = '-' . $this->rateOption[self::TRIGGER_NSFW]; - if (!empty($arguments)) { - $upperArguments = array_map('strtoupper', $arguments); - foreach ($this->rateOption as $option => $value) { - if (($key = array_search($option, $upperArguments)) !== false) { - $this->rate = $value; - unset($arguments[$key]); - break; - } - } - } - if (empty($arguments)) { - $this->reply('What are you looking for? Type "!random" '); - return false; - } - return $arguments; - } + 'rating:explicit', + 'SAFE' => 'rating:safe', + 'QUES' => 'rating:questionable' + ], + $api, $rate; + + public function loadSettings($object = null) + { + libxml_set_streams_context($this->ctx); + libxml_use_internal_errors(true); + $this->setCommand([ + 'trigger' => 'c', + 'action' => 'c', + 'arguments' => -1, + 'determiter' => ',', + 'help' => 'Randomize arguments. Determiter is set as ",". Example: "!c apple, banana, oranges".', + 'ban'=> [ + 'host' => 'FBF0D8DB.5BE561A6.7DCB3F4E.IP' + ] + + ]); + + $this->setCommand([ + 'trigger' => 'random', + 'action' => 'random', + 'arguments' => -1, + 'help' => '"!random" default search loli, but you can find anything you want. ' . + 'You can change rating by adding safe|nsfw|ques to arguments and change ' . + 'image server by adding yan (yande.re).', + 'ban' => + [ + 'nick' => 'Thebassa' + ] + ]); + + $this->setCommand([ + 'trigger' => 'biba', + 'reply' => 'Biba dance: https://www.youtube.com/watch?v=kpJcgkEdMRg' + ]); + + $this->setCommand([ + 'trigger' => 'maido', + 'reply' => 'Maido dance: https://www.youtube.com/watch?v=a-7_XdPktgc' + ]); + $this->setCommand([ + 'trigger' => 'mikuluka', + 'reply' => 'https://www.youtube.com/watch?v=ZllY2wBLYN4' + ]); + + $this->setCommand([ + 'trigger' => 'rolypoly', + 'reply' => 'Roly-poly: http://www.youtube.com/watch?v=3Xolk2cFzlo' + ]); + + $this->setCommand([ + 'trigger' => 'weaboo', + 'reply' => 'Weaboo song: https://www.youtube.com/watch?v=TBfWKmRFTjM' + ]); + + $this->setCommand([ + 'trigger' => 'xandros', + 'reply' => '[9:58pm] xandros, kup sobie slownik' + ]); + + $this->setCommand([ + 'trigger' => 'cycki', + 'action' => 'cycki' + ]); + $this->setCommand([ + 'action' => function () { + $this->user->mode($this->bot->getSource(),'+b', ['Thebassa']); + $this->user->kick($this->bot->getSource(), 'Thebassa', 'nie jestem zawiedziona'); + }, + 'trigger' => 'baka', + 'permit' => true, + ]); + + + + parent::loadSettings($this); + } + + protected function cycki() + { + $stream = $this->loadStreamUrl('http://api.oboobs.ru/noise/1/'); + $json = json_decode($stream); + if (!empty($json[0])) { + $json = $json[0]; + $message = IRCHelper::colorText('Tits', IRCHelper::COLOR_ORANGE) . ': '; + $message .= IRCHelper::colorText('NSFW', IRCHelper::COLOR_PINK) . ' '; + $message .= 'http://media.oboobs.ru/' . $json->preview; + } else { + $message = 'Can\'t get api'; + } + $this->reply($message); + } + + protected function c(array $arguments = []) + { + if (count(array_unique(array_map('trim', $arguments))) >= 2) { + $this->reply(trim($arguments[mt_rand(0, count($arguments) - 1)])); + } else { + $this->reply('Wrong arguments. Type "!Help c" to help'); + } + } + + protected function random(array $arguments = []) + { + $arguments = $this->setApi($arguments); + $arguments = $this->setRate($arguments); + if (!$arguments) { + return false; + } + + + + $tags = array_map('strtolower', array_merge($arguments, [$this->rate])); + $url = $this->api . 'tags=' . trim(implode('+', $tags)); + $html = $this->loadStreamUrl($url); + if (!$html) { + return $this->reply('I can\'t open api url.'); + } + $doc = $this->getDOM(); + if (!$doc->loadHTML($html)) { + return $this->reply('I can\'t open api url.'); + } + + if ($doc->getElementsByTagName('posts')->length == 0 || + empty($doc->getElementsByTagName('posts') + ->item(0) + ->getAttribute('count'))) { + return $this->reply('Sorry, I didn\'t find ' . trim(implode(' ', $arguments)) . '.'); + } + $count = $doc->getElementsByTagName('posts') + ->item(0) + ->getAttribute('count'); + + $random = mt_rand(0, $count - 1); + $pid = floor($random / 100); + + switch ($this->api) { + case self::API_GEL: + $url .= '&json=1&pid=' . $pid; + break; + case self::API_YAN: + $url = str_ireplace('.xml', '.json', $url) . '&limit=100&page=' . $pid; + break; + } + $newHtml = $this->loadStreamUrl($url); + if (!$newHtml) { + return $this->reply('Can\'t load html to dom.'); + } + $image = json_decode($newHtml)[$random % 100]; + $url = $this->shortIt($image->file_url, + ($this->api == self::API_GEL) ? + $image->hash : $image->md5); + $warn = ''; + switch ($image->rating) { + case self::RATING_NSFW: + $warn = IRCHelper::colorText('NSFW', IRCHelper::COLOR_PINK); + break; + case self::RATING_SAFE: + $warn = IRCHelper::colorText('Safe', IRCHelper::COLOR_GREEN); + break; + case static::RATING_QUESTIONABLE: + $warn = IRCHelper::colorText('Questionable', IRCHelper::COLOR_ORANGE); + break; + } + $tag = (!empty($arguments)) ? ' ' . trim(implode(' ', $arguments)) : ''; + $this->reply("Random{$tag}: {$warn} {$url} (from {$count} pic)"); + } + + private function shortIt($url, $md5) + { + if (!self::API_SHORT) { + return $url; + } + + parent::RedBeanConnect('short'); + if (($fetch = @R::findOne('short_url', '`title` = ?', [$md5]))) { + return self::API_SHORT . $fetch->keyword; + } + $timestamp = date('Y-m-d H:i:s'); + do { + $uniq = ''; + $base = strtolower(hash('sha256', uniqid())); + while (strlen($uniq) < 8) { + $uniq .= substr($base, (int) -(strlen($base) / (1 + strlen($uniq))), 1); + } + } while (@R::findOne('short_url', '`keyword` = ?', [$uniq])); + $sql = 'INSERT INTO `short`.`short_url` '; + $sql .="(`keyword`, `url`, `title`, `timestamp`, `ip`, `clicks`) "; + $sql .= "VALUES ('{$uniq}', '{$url}', '{$md5}', '{$timestamp}', '"; + $sql .= getHostByName(getHostName()) . "', '0')"; + R::exec($sql); + R::close(); + return 'http://exsubs.anidb.pl/short/' . $uniq; + } + + private function setApi(array $arguments) + { + $key = array_search(self::TRIGGER_GEL, array_map('strtoupper', $arguments)); + if ($key !== false) { + $this->api = self::API_GEL; + unset($arguments[$key]); + } else { + $this->api = self::API_YAN; + } + return $arguments; + } + + private function setRate(array $arguments) + { + $this->rate = '-' . $this->rateOption[self::TRIGGER_NSFW]; + if (!empty($arguments)) { + $upperArguments = array_map('strtoupper', $arguments); + foreach ($this->rateOption as $option => $value) { + if (($key = array_search($option, $upperArguments)) !== false) { + $this->rate = $value; + unset($arguments[$key]); + break; + } + } + } + if (empty($arguments)) { + $this->reply('What are you looking for? Type "!random" '); + return false; + } + return $arguments; + } } \ No newline at end of file diff --git a/module/settings/.gitignore b/module/settings/.gitignore deleted file mode 100644 index a3a0c8b..0000000 --- a/module/settings/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -* -!.gitignore \ No newline at end of file diff --git a/module/Thpl.php b/module/thpl/Thpl.php similarity index 95% rename from module/Thpl.php rename to module/thpl/Thpl.php index 6ff678c..7fec4e3 100644 --- a/module/Thpl.php +++ b/module/thpl/Thpl.php @@ -1,251 +1,253 @@ -setCommand([ - 'trigger' => 'thsp', - 'help' => 'I know some spell cards from touhou. Type "!thsp [/ or :]" to get some information about it. ' . - '"!thsp list" list all cards', - 'arguments' => 1, - 'channels' => ['#touhoupl', '#xandros'], - 'action' => 'action' - ]); - $this->setCommand([ - 'trigger' => 'thwall', - 'help' => 'Searching best wallpapers from Touhou (I guess). ' - . 'Syntax: "!thwall [arguments|id]+". Accepts wildcards.', - 'arguments' => -1, - 'channels' => ['#touhoupl'], - 'action' => 'randomWall' - ]); - parent::loadSettings(); - } - - public function execute() - { - $this->on(IRC::PING, 'setLastForumPost'); - $this->on(null, 'sendLastForumPost', $this->forumTimeDelay); - /* $this->on(null, '', $this->pageTimeDelay); */ - } - - public function propertyToSave() - { - return [ - 'lastNewsTime' => $this->lastNewsTime, - 'lastPostTime' => $this->lastPostTime - ]; - } - protected function randomWall(array $arguments = []) - { - $id = []; - if ($arguments) { - foreach ($arguments as $argument => $value) { - if (strpos($value, '/') !== false) { - $value = str_replace('/', '', $value); - } - if(preg_match('~^\d+$~', $value) && empty($id)) { - $id = $value; - unset($arguments[$argument]); - continue; - } - $arguments[$argument] = $value; - } - $arguments = implode('%20', $arguments); - } - $apiUrl = self::API_WALL_URL; - $apiUrl .= ($arguments) ? '/' . $arguments : ''; - $apiUrl .= ($id) ? '/' . $id : ''; - $result = $this->loadStreamUrl($apiUrl); - $jsonResult = json_decode($result); - if (!$jsonResult) { - return $this->reply('Sorry, no results.'); - } - $data = [ - '{name}' => $jsonResult->name, - '{resolution}' => $jsonResult->info->{0} . 'x' . $jsonResult->info->{1}, - '{url}' => $jsonResult->url, - '{nsfw}' => $jsonResult->safe ? '' : IRCHelper::colorText('NSFW', IRCHelper::COLOR_PINK), - ]; - $message = 'Random tapcia - {name} [{resolution}] here: {url} {nsfw}'; - $message = str_replace(array_keys($data), array_values($data), $message); - $this->reply(trim($message)); - } - - protected function sendLastForumPost() - { - $this->channelToSend = array_intersect( - $this->channelPermit, $this->getJoinedChannel() - ); - - if (!$this->channelToSend) { - return false; - } - - if (!$this->forum) { - return; - } - $last = $this->lastPostTime; - foreach ($this->forum as $key => $subject) { - $msg = IRCHelper::colorText('Forum', IRCHelper::COLOR_ORANGE) . ': ' . $subject->lastPostDate . ' '; - $msg .= IRCHelper::colorTrim('[Touhou]', IRCHelper::COLOR_GREEN) . ' '; - $msg .= IRCHelper::colorTrim('(' . $subject->name . ')', IRCHelper::COLOR_RED) . ' ' ; - $msg .= IRCHelper::colorText('Temat', IRCHelper::COLOR_LIGHT_GREEN) . ': ' . $subject->topic . ' ' . $subject->lastPostLink; - $last = max([$subject->lastPostTime, $last]); - $this->sendMessage($msg); - unset($this->forum[$key]); - } - $this->lastPostTime = $last; - } - - protected function setLastForumPost() - { - $xml = $this->xmlObject(self::FORUM_API); - if (!is_object($xml)) { - return false; - } - $findKeyObject = function(array $array, $id) { - foreach ($array as $key => $object) { - if ($object->id == $id) { - return $key; - } - } - return false; - }; - foreach ($xml->entry as $item) { - $timestamp = strtotime($item->updated); - if ($this->lastPostTime >= $timestamp) { - continue; - } - if (!preg_match(self::URL_TO_ID_REGEX, $item->link->attributes()->href, $matches)) { - return false; - } - - $date = (new DateTime($item->updated)) - ->setTimezone(new DateTimeZone(Config::DEFAULT_TIMEZONE)); // TODO change localtime to global proprerty - $idSubject = (int) $matches[1]; - $idPost = (int) $matches[2]; - - $keySubject = $findKeyObject($this->forum, $idSubject); - - if ($keySubject === false) { - - $subject = new stdClass(); - $subject->id = $idSubject; - $subject->topic = str_replace('Odp: ', '', (string) $item->title); - $subject->name = $item->author->name; - $this->forum[] = $subject; - end($this->forum); - $keySubject = key($this->forum); - } - - $this->forum[$keySubject]->lastPostLink = sprintf(self::SHORT_URL . '/%d/%d', $idSubject, $idPost); - $this->forum[$keySubject]->lastPostDate = $date->format('d-m-Y H:i:s'); - $this->forum[$keySubject]->lastPostTime = $timestamp; - $this->forum[$keySubject]->lastPostId = $idPost; - } - return true; - } - - protected function getHelp() - { - if (!$json = json_decode($this->loadStreamUrl($this->api))) { - return 'Something really wrong with api. h-collector, FIX IT!'; - } - $text = 'I remember only those spells:'; - foreach ($json as $item => $value) { - $text .= " {$item}:[1-{$value->total}]"; - } - return $text; - } - - protected function action($arguments) - { - if (strtoupper($arguments[0]) == 'LIST') { - $this->reply($this->getHelp()); - return false; - } - if (!preg_match(self::SPELL_REGEX, $arguments[0], $matches)) { - $this->reply($this->getHelp()); - return false; - } - if (empty($matches[2])) { - $this->reply($this->getHelp()); - return false; - } - if (!$json = json_decode($this->loadStreamUrl(("$this->api/{$matches[1]}/" . (int) $matches[2])))) { - $this->reply($this->getHelp()); - return false; - } - - $string = IRCHelper::colorText('Name', IRCHelper::COLOR_ORANGE) . ': ' . $json->titleEN . ' '; - $string .= IRCHelper::colorText('Character', IRCHelper::COLOR_ORANGE) . ': ' . $json->titleEN . ' '; - $string .= IRCHelper::colorText('Stage', IRCHelper::COLOR_ORANGE) . ': ' . $json->titleEN; - - if (!empty($json->diff)) { - $string .= IRCHelper::colorText(' Difficult level', IRCHelper::COLOR_ORANGE) . ': ' . $json->diff; - } - if (!empty($json->youtube)) { - $string .= IRCHelper::colorText('YT', IRCHelper::COLOR_RED) . ': https://youtu.be/' . $json->youtube; - } - $this->reply($string); - } - - /** - * - * @param string $url - * @return object - * - */ - private function xmlObject($url) - { - $html = $this->loadStreamUrl($url); - $xml = simplexml_load_string($html); - return ($xml) ? $xml : false; - } - - /** - * send msg to #channel on network - * - * @return void - */ - private function sendMessage($message) - { - foreach ($this->channelToSend as $channel) { - $this->message($message, $channel); - } - } -} +setCommand([ + 'trigger' => 'thsp', + 'help' => 'I know some spell cards from touhou. Type "!thsp [/ or :]" to get some information about it. ' . + '"!thsp list" list all cards', + 'arguments' => 1, + 'channels' => ['#touhoupl', '#xandros'], + 'action' => 'action' + ]); + $this->setCommand([ + 'trigger' => 'thwall', + 'help' => 'Searching best wallpapers from Touhou (I guess). ' + . 'Syntax: "!thwall [arguments|id]+". Accepts wildcards.', + 'arguments' => -1, + 'channels' => ['#touhoupl'], + 'action' => 'randomWall' + ]); + parent::loadSettings(); + } + + public function execute() + { + $this->on(IRC::PING, 'setLastForumPost'); + $this->on(null, 'sendLastForumPost', $this->forumTimeDelay); + /* $this->on(null, '', $this->pageTimeDelay); */ + } + + public function propertyToSave() + { + return [ + 'lastNewsTime' => $this->lastNewsTime, + 'lastPostTime' => $this->lastPostTime + ]; + } + protected function randomWall(array $arguments = []) + { + $id = []; + if ($arguments) { + foreach ($arguments as $argument => $value) { + if (strpos($value, '/') !== false) { + $value = str_replace('/', '', $value); + } + if(preg_match('~^\d+$~', $value) && empty($id)) { + $id = $value; + unset($arguments[$argument]); + continue; + } + $arguments[$argument] = $value; + } + $arguments = implode('%20', $arguments); + } + $apiUrl = self::API_WALL_URL; + $apiUrl .= ($arguments) ? '/' . $arguments : ''; + $apiUrl .= ($id) ? '/' . $id : ''; + $result = $this->loadStreamUrl($apiUrl); + $jsonResult = json_decode($result); + if (!$jsonResult) { + $this->reply('Sorry, no results.'); + return; + } + $data = [ + '{name}' => $jsonResult->name, + '{resolution}' => $jsonResult->info->{0} . 'x' . $jsonResult->info->{1}, + '{url}' => $jsonResult->url, + '{nsfw}' => $jsonResult->safe ? '' : IRCHelper::colorText('NSFW', IRCHelper::COLOR_PINK), + ]; + $message = 'Random tapcia - {name} [{resolution}] here: {url} {nsfw}'; + $message = str_replace(array_keys($data), array_values($data), $message); + $this->reply(trim($message)); + } + + protected function sendLastForumPost() + { + $this->channelToSend = array_intersect( + $this->channelPermit, $this->getJoinedChannel() + ); + + if (!$this->channelToSend) { + return false; + } + + if (!$this->forum) { + return false; + } + $last = $this->lastPostTime; + foreach ($this->forum as $key => $subject) { + $msg = IRCHelper::colorText('Forum', IRCHelper::COLOR_ORANGE) . ': ' . $subject->lastPostDate . ' '; + $msg .= IRCHelper::colorTrim('[Touhou]', IRCHelper::COLOR_GREEN) . ' '; + $msg .= IRCHelper::colorTrim('(' . $subject->name . ')', IRCHelper::COLOR_RED) . ' ' ; + $msg .= IRCHelper::colorText('Temat', IRCHelper::COLOR_LIGHT_GREEN) . ': ' . $subject->topic . ' ' . $subject->lastPostLink; + $last = max([$subject->lastPostTime, $last]); + $this->sendMessage($msg); + unset($this->forum[$key]); + } + $this->lastPostTime = $last; + return true; + } + + protected function setLastForumPost() + { + $xml = $this->xmlObject(self::FORUM_API); + if (!is_object($xml)) { + return false; + } + $findKeyObject = function(array $array, $id) { + foreach ($array as $key => $object) { + if ($object->id == $id) { + return $key; + } + } + return false; + }; + foreach ($xml->entry as $item) { + $timestamp = strtotime($item->updated); + if ($this->lastPostTime >= $timestamp) { + continue; + } + if (!preg_match(self::URL_TO_ID_REGEX, $item->link->attributes()->href, $matches)) { + return false; + } + + $date = (new DateTime($item->updated)) + ->setTimezone(new DateTimeZone(Config::DEFAULT_TIMEZONE)); // TODO change localtime to global proprerty + $idSubject = (int) $matches[1]; + $idPost = (int) $matches[2]; + + $keySubject = $findKeyObject($this->forum, $idSubject); + + if ($keySubject === false) { + + $subject = new stdClass(); + $subject->id = $idSubject; + $subject->topic = str_replace('Odp: ', '', (string) $item->title); + $subject->name = $item->author->name; + $this->forum[] = $subject; + end($this->forum); + $keySubject = key($this->forum); + } + + $this->forum[$keySubject]->lastPostLink = sprintf(self::SHORT_URL . '/%d/%d', $idSubject, $idPost); + $this->forum[$keySubject]->lastPostDate = $date->format('d-m-Y H:i:s'); + $this->forum[$keySubject]->lastPostTime = $timestamp; + $this->forum[$keySubject]->lastPostId = $idPost; + } + return true; + } + + protected function getHelp() + { + if (!$json = json_decode($this->loadStreamUrl($this->api))) { + return 'Something really wrong with api. h-collector, FIX IT!'; + } + $text = 'I remember only those spells:'; + foreach ($json as $item => $value) { + $text .= " {$item}:[1-{$value->total}]"; + } + return $text; + } + + protected function action($arguments) + { + if (strtoupper($arguments[0]) == 'LIST') { + $this->reply($this->getHelp()); + return false; + } + if (!preg_match(self::SPELL_REGEX, $arguments[0], $matches)) { + $this->reply($this->getHelp()); + return false; + } + if (empty($matches[2])) { + $this->reply($this->getHelp()); + return false; + } + if (!$json = json_decode($this->loadStreamUrl(("$this->api/{$matches[1]}/" . (int) $matches[2])))) { + $this->reply($this->getHelp()); + return false; + } + + $string = IRCHelper::colorText('Name', IRCHelper::COLOR_ORANGE) . ': ' . $json->titleEN . ' '; + $string .= IRCHelper::colorText('Character', IRCHelper::COLOR_ORANGE) . ': ' . $json->titleEN . ' '; + $string .= IRCHelper::colorText('Stage', IRCHelper::COLOR_ORANGE) . ': ' . $json->titleEN; + + if (!empty($json->diff)) { + $string .= IRCHelper::colorText(' Difficult level', IRCHelper::COLOR_ORANGE) . ': ' . $json->diff; + } + if (!empty($json->youtube)) { + $string .= IRCHelper::colorText('YT', IRCHelper::COLOR_RED) . ': https://youtu.be/' . $json->youtube; + } + $this->reply($string); + } + + /** + * + * @param string $url + * @return object + * + */ + private function xmlObject($url) + { + $html = $this->loadStreamUrl($url); + $xml = simplexml_load_string($html); + return ($xml) ? $xml : false; + } + + /** + * send msg to #channel on network + * + * @return void + */ + private function sendMessage($message) + { + foreach ($this->channelToSend as $channel) { + $this->message($message, $channel); + } + } +} diff --git a/module/Url.php b/module/uri/Url.php similarity index 82% rename from module/Url.php rename to module/uri/Url.php index 12937b4..49f7609 100644 --- a/module/Url.php +++ b/module/uri/Url.php @@ -4,11 +4,11 @@ namespace Module; use DOMXPath; -use library\constants\IRC; -use library\helper\IRCHelper; -use library\helper\UrlHelper; +use Saya\IRC; +use Saya\Components\Helper\IRCHelper; +use Saya\Client\UrlHelper; use RuntimeException; -use library\Module; +use Saya\Client\Module; /** * @@ -16,7 +16,7 @@ * @subpackage Listener * @author Remigiusz Guszkiewicz */ -class Url extends \Library\Module +class Url extends Module { const TYPE_PAGE = 1, @@ -28,19 +28,19 @@ class Url extends \Library\Module private $ctxDomainList = [ - 'http://t.co/' => [], //twitter - 'https://t.co/' => [] //twitter - ], - $except = [ + 'http://t.co/' => [], //twitter + 'https://t.co/' => [] //twitter + ], + $except = [ //'touhou.pl' => 'block', - 'myanimelist.net' => 'block', - 'mega.co.nz' => 'block', - 'mega.nz' => 'block', - 'anidb.net' => 'pass' - ], - $openGraph = [ - 'kwejk.pl' => 'title', - 'twitch.tv' => 'description' + 'myanimelist.net' => 'block', + 'mega.co.nz' => 'block', + 'mega.nz' => 'block', + 'anidb.net' => 'pass' + ], + $openGraph = [ + 'kwejk.pl' => 'title', + 'twitch.tv' => 'description' ]; public function __construct() @@ -51,7 +51,11 @@ public function __construct() public static function getRegexUrl() { - return '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS'; + return '_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254' . + '(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|' . + '2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x' . + '{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}' . + '0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS'; } /** @@ -70,7 +74,7 @@ protected function findTitle() continue; } $openGraph = $this->getOpenGraph($url); - $title = $this->getTitle($url, $openGraph); + $title = $this->getTitle($url, $openGraph); if (!$title) { continue; } @@ -79,10 +83,11 @@ protected function findTitle() $this->reply($title); } } + private function trimtext($text, $lenght) { - if(strlen($text) > $lenght){ - return mb_substr($text, 0, $lenght - 5) . '(...)'; + if (strlen($text) > $lenght) { + return mb_substr($text, 0, $lenght - 5) . '(...)'; } return $text; } @@ -136,8 +141,8 @@ protected function getimagesizefromstring($string_data) protected function humanFilesize($bytes, $decimals = 2) { - $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; - $factor = floor((strlen($bytes) - 1) / 3); + $size = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + $factor = (int) floor((strlen($bytes) - 1) / 3); return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor]; } @@ -192,7 +197,7 @@ protected function getTitle($url, $openGraph = false) $html = mb_convert_encoding($html, 'HTML-ENTITIES', (isset($charset)) ? $charset : 'UTF-8'); try { - $doc = $this->getDOM(); + $doc = $this->getDOM(); $loaded = $doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); /* $doc->loadHTML('' . $html); */ @@ -201,17 +206,18 @@ protected function getTitle($url, $openGraph = false) if (!$loaded) { if (preg_match("#]*>(.*?)#Umsi", $html, $matches)) {//Umsi return $this->text(html_entity_decode( - preg_replace('/\s+/', ' ', $matches[1]) - ), self::TYPE_PAGE); + preg_replace('/\s+/', ' ', $matches[1]) + ), self::TYPE_PAGE); } throw new RuntimeException(libxml_get_last_error()->message); } if ($openGraph) { $metadata = (new DOMXPath($doc))->query(self::OPEN_GRAPH_QUERY); + /** @var $meta \DOMNode */ foreach ($metadata as $meta) { - $property = $meta->getAttribute('property'); - $content = $meta->getAttribute('content'); + $property = $meta->getAttribute('property'); + $content = $meta->getAttribute('content'); $rmetas[$property] = $content; } if (isset($rmetas['og:' . $openGraph])) {