diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml deleted file mode 100644 index 0936bc2..0000000 --- a/.idea/inspectionProfiles/Project_Default.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml deleted file mode 100644 index 3b31283..0000000 --- a/.idea/inspectionProfiles/profiles_settings.xml +++ /dev/null @@ -1,7 +0,0 @@ - - - - \ No newline at end of file diff --git a/.idea/vagrant.xml b/.idea/vagrant.xml deleted file mode 100644 index 9b58cdc..0000000 --- a/.idea/vagrant.xml +++ /dev/null @@ -1,9 +0,0 @@ - - - - - - diff --git a/admin/ban.php b/admin/ban.php deleted file mode 100644 index 5d0e762..0000000 --- a/admin/ban.php +++ /dev/null @@ -1,109 +0,0 @@ - '1' -AND cm.ban = '".Yes."' -AND cm.banTo < '".time()."'"); -while($row = dbarray($sql)){ - dbquery("INSERT INTO `".DB_CHATMESSAGE."` - ( - `uid`, - `cid`, - `isBot`, - `time`, - `message`, - `messageColor`, - `isMsg`, - `msgTo` - ) VALUES ( - '".(int)$row['uid']."', - '".(int)$row['cid']."', - '".Yes."', - NOW(), - '/unban ".cleanMySQL($row['nick'])."', - 'green', - '".No."', - '0' - )"); - - dbquery("DELETE FROM `".DB_CHATMEMBER."` WHERE `id`='".(int)$row['id']."'"); -} - -$rows = dbcount("(id)", DB_CHATMEMBER, "`ban`='".Yes."'"); -$sql = dbquery("SELECT count(cid) AS c FROM `".DB_CHATMEMBER."` WHERE `ban`='".Yes."' AND `cid`<>'1'"); -$count = dbarray($sql); - -opentable("Chat ban"); -echo ""; -if($unban){ - echo ""; - echo ""; - echo ""; -} - -if($count['c'] == 0){ - echo ""; - echo ""; - echo ""; -}else{ - $sql = dbquery("SELECT user.nick AS nick, cm.banTo AS banTo, cn.name AS name, cm.id AS cmid - FROM ".DB_CHATMEMBER." AS cm - LEFT JOIN ".DB_USERS." AS user ON user.user_id = cm.uid - LEFT JOIN ".DB_CHATNAME." AS cn ON cn.id = cm.cid - WHERE cm.ban='".Yes."' - AND cm.cid<>'1' - LIMIT ".$num.",10"); - while($row = dbarray($sql)){ - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - } -} - -echo ""; -echo ""; -echo ""; -echo "
".$locale['unbanOkay']."
".$locale['noBan']."
".$row['nick']."".showdate("forumdate", $row['banTo'])."".$row['name']."".$locale['unban']."
"; -echo makepagenav($num,10,$rows,3,FUSION_SELF."?aid=".$_GET['aid']."&","p"); -echo "
"; -closetable(); - -require_once THEMES."templates/footer.php"; \ No newline at end of file diff --git a/admin/index.php b/admin/index.php deleted file mode 100644 index 5bebbb9..0000000 --- a/admin/index.php +++ /dev/null @@ -1 +0,0 @@ -Access deniad \ No newline at end of file diff --git a/admin/log.php b/admin/log.php deleted file mode 100644 index 8e0a625..0000000 --- a/admin/log.php +++ /dev/null @@ -1,119 +0,0 @@ -"; - $log[] = null;//make empty line ;) - - $r = dbquery("SELECT ms.message AS message, ms.time AS mtime, user.nick AS nick,ms.isBot AS isBot - FROM `".DB_CHATMESSAGE."` AS ms - LEFT JOIN `".DB_CHATMEMBER."` AS cm ON cm.cid=ms.cid - LEFT JOIN `".DB_USERS."` AS user ON user.user_id=ms.uid - LEFT JOIN `".DB_CHATNAME."` AS cn ON ms.cid=cn.id - WHERE cn.name='".cleanMySQL($_GET['getLog'])."' - AND ms.isMsg='".No."' - AND cn.id<>'1'"); - while($row = dbarray($r)){ - $time = showdate("forumdate",strtotime($row['mtime'])); - if(preg_check("/^\//", $row['message'])){ - switch (getCommandType($row['message'])){ - case 'join': - $log[] = "[".$time."]".$config['botUserName'].": ".sprintf($locale['onJoin'],$row['nick']); - break; - case 'notInaktiv': - preg_match("/^\/notInaktiv\s(.*?)$/",$row['message'],$reg); - $log[] = "[".$time."]".$config['botUserName'].": ".sprintf($locale['onNotInaktiv'],$reg[1]); - break; - case 'inaktiv': - preg_match("/^\/inaktiv\s(.*?)$/",$row['message'],$reg); - $log[] = "[".$time."]".$config['botUserName'].": ".sprintf($locale['onInaktiv'],$reg[1]); - break; - case 'leave': - $log[] = "[".$time."]".$config['botUserName'].": ".sprintf($locale['onLeave'],$row['nick']); - break; - case 'exit': - $log[] = "[".$time."]".$config['botUserName'].": ".sprintf($locale['onExit'],$row['nick']); - break; - case 'nick': - preg_match("/\/nick\s([a-zA-Z0-9]*?)$/",$row['message'],$reg); - $log[] = "[".$time."]".$config['botUserName'].": ".sprintf($locale['onNick'],$reg[1],$row['nick']); - break; - case 'title': - preg_match("/^\/title\s(.*?)$/",$row['message'],$reg); - $log[] = "[".$time."]".$config['botUserName'].": ".sprintf($locale['onTitle'],$config['botUserName'],$reg[1]); - break; - case 'kick': - $log[] = "[".$time."]".$config['botUserName'].": ".sprintf($locale['onKick'],$row['nick']); - break; - case 'ban': - preg_match("/^\/ban\s(.*?)$/",$row['message'],$reg); - $log[] = "[".$time."]".$config['botUserName'].": ".sprintf($locale['onBan'],$row['nick'],$reg[1]); - break; - case 'unban': - preg_match("/^\/unban\s(.*?)$/",$row['message'],$reg); - $log[] = "[".$time."]".$config['botUserName'].": ".sprintf($locale['onUnBan'],$reg[1]); - break; - } - }else{ - if($row['isBot'] == Yes){ - $log[] = "[".$time."]".$config['botUserName'].": ".$row['message']; - }else{ - $log[] = "[".$time."]".$row['nick'].": ".$row['message']; - } - } - } - - $log[] = null; - $log[] = "<-- end log -->"; - $log[] = "Note nick may differ from the unit at the time punk shown in this log"; - - $string = "#".implode("\r\n#",$log); - require_once INCLUDES."class.httpdownload.php"; - $obj = new httpdownload(); - if(!$obj->set_bydata($string)){ - exit("Log error"); - } - - $obj->set_filename(str_replace("#",null,$_GET['getLog']).".log"); - $obj->download(); - exit; -} - -require_once THEMES."templates/admin_header.php"; - -opentable($locale['dawnlordLog']); -echo ""; - -$sql = dbquery("SELECT `name`,`id` FROM `".DB_CHATNAME."` WHERE `id`<>'1'"); -while($row = dbarray($sql)){ - echo ""; - echo ""; - echo ""; - echo ""; -} - -echo "
".$row['name']."".$locale['dawnlordLog']."
"; -closetable(); - -require_once THEMES."templates/footer.php"; \ No newline at end of file diff --git a/admin/setting.php b/admin/setting.php deleted file mode 100644 index e821ec5..0000000 --- a/admin/setting.php +++ /dev/null @@ -1,172 +0,0 @@ - $value){ - if(set_setting($key, $value, "chat")){ - $config[$key] = $value; - } - } - - $isUpdate = true; - } -} - -opentable("".$locale['chatTitle'].""); -echo "
"; -echo ""; -if(count($error) != 0){ - echo ""; - echo ""; - echo ""; - for($i=0;$i"; - echo ""; - echo ""; - } -}elseif($isUpdate){ - echo ""; - echo ""; - echo ""; -} - - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; -echo ""; - echo ""; -if($config['protokol'] == 'socket'){ - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; - echo ""; -} - echo ""; - echo ""; - echo ""; -echo "
".$locale['Error']."
".$error[$i]."
".$locale['configUpdate']."
".$locale['maxNickLanght']."
".$locale['startChannel']."
".$locale['botUserName']."
".$locale['botUserColor']."
".$locale['botTextColor']."
".$locale['inaktiv']."
".$locale['leave']."
".$locale['useSocket']."
".$locale['socketHost']."
".$locale['socketPort']."
"; - echo ""; - echo "
"; -echo "
"; -closetable(); - -require_once THEMES."templates/footer.php"; \ No newline at end of file diff --git a/api.php b/api.php deleted file mode 100644 index 4911d46..0000000 --- a/api.php +++ /dev/null @@ -1,59 +0,0 @@ -'1'"); - while($row = dbarray($sql)){ - $channels[] = array( - 'cid' => $row['id'], - 'name' => $row['name'] - ); - } - - return $channels; -} - - -function bot_message($cid,$message,$messageColor = 'black'){ - global $channelsCache; - - if($channelsCache === null){ - $c = get_channel(); - $channelsCache = array(); - for($i=0;$i"; - echo $locale['errorGeaust']; - echo ""; -} - -closetable(); -require_once THEMES."templates/footer.php"; \ No newline at end of file diff --git a/core.php b/core.php new file mode 100644 index 0000000..ccace56 --- /dev/null +++ b/core.php @@ -0,0 +1,28 @@ +connectionCount()); +} + +//finaly wee load and set up the diffrence libary so now wee can start the server and let it running until its goal is done. +server_start(); + +ShoutDown::onEnd(); \ No newline at end of file diff --git a/css/chat.css b/css/chat.css deleted file mode 100644 index 6ba8afa..0000000 --- a/css/chat.css +++ /dev/null @@ -1,229 +0,0 @@ -#chatContainer{ - width:100%; - height:400px; -} - -#leftContainer{ - width:80%; - height:100%; - border:1px solid black; - float:left; -} - -#rightContainer{ - width:19%; - height:100%; - border:1px solid black; - float:left; -} - -#channelList{ - width:100%; - height: 30px; - border:1px solid black; - border-radius:0px 0px 10px 10px; - background-size:100% 100%; - padding: 0px; -} - - - -#statusIndikator{ - float:right; - width:20px; - height:20px; - border: 1px solid black; - border-radius: 100px; - margin: 2px; - z-index: 2; - cursor: pointer; -} - -#channelMain{ - width:100%; - height:330px; - border:1px solid black; - overflow:auto; - background-size:100% 100%; -} - -#profilImage{ - width:100%; - height:100px; - border-bottom:1px solid black; - background-size:100% 100%; -} - -#optionBar{ - width:100%; - height:20px; - border-bottom: 1px solid black; -} - -#option{ - border:none; - height: 20px; - width: 100%; - text-align: center; -} - -.option{ - overflow:auto; -} - -#settingTable{ - width:100%; - border-collapse: collapse; -} - -#settingTable th,#settingTable td{ - border:1px solid black; - width:50%; -} - -#uploadTable{ - width: 100%; - border-collapse: collapse; -} - -#uploadTable th, #uploadTable td{ - border: 1px solid black; - width: 50%; -} - -#save{ - cursor: pointer; -} - -#text{ - width:100%; - height: 37px; -} - -#textbox{ - height: 37px; - width: 100%; - border:none; -} - -.bbImg{ - width:15px; - height:15px; -} - -.u_info_container{ - clear: both; -} - -.user{ - border-bottom: 1px solid black; -} - -.u_nick,.u_image{ - float: left; -} - -.u_image{ - width:10%; -} - -.u_nick{ - width:90%; - text-align: center; - font-weight: bolder; - cursor: pointer; -} - - -.smy{ - width:15px; - height:15px; -} - -.message{ - font-size:15px; - border:1px solid black; -} - -.smyBut{ - cursor: pointer; - width:20px; - height:20px; -} - -.channelNameContainer{ - font-size:15px; -} - -.chanenlContainer{ - border:1px solid black; - border-radius: 10px; - margin:5px; - cursor: pointer; -} - -.colorOne{ - background-color:#C6C6C6; -} - -.colorToo{ - background-color:#828282; -} - -.user_menu{ - display: none; - border-top: 1px solid black; -} - -.user_menu.table{ - width:100%; -} - -.userDawnloadedImage img{ - height: 15px; - width: 15px; -} - -.userDawnloadedImage{ - cursor: pointer; -} - -#viewImage{ - position: absolute; - top: 10px; - left: 10px; - right: 10px; - bottom: 10px; - background-color: red; - border-radius: 10px; - display: none; - border: 2px solid black; -} - -#viewImageTitle{ - position: absolute; - top: 0px; - left: 0px; - right: 0px; - height: 25px; - border-bottom: 1px solid black; - background-color: blue; - border-radius: 10px 10px 0 0; -} - -#viewImageTitle img{ - height: 20px; - width: 20px; - margin: 2.5px; - cursor: pointer; -} - -#viewImages{ - position: absolute; - top:25px; - left: 0; - right: 0; - bottom: 0; - background-size: 100% 100%; - background-repeat: no-repeat; -} \ No newline at end of file diff --git a/css/index.php b/css/index.php deleted file mode 100644 index 5bebbb9..0000000 --- a/css/index.php +++ /dev/null @@ -1 +0,0 @@ -Access deniad \ No newline at end of file diff --git a/include/ajax.php b/include/ajax.php new file mode 100644 index 0000000..c743457 --- /dev/null +++ b/include/ajax.php @@ -0,0 +1,20 @@ +render_user($callback); + } + + public static function renderChannels($callback){ + foreach(self::$channels as $name => $data){ + $callback($name, $data); + } + } + + public static function exists($name){ + if(!empty(self::$channels[$name])) + return true; + + //wee has not cache it yet so wee create it if it exists. + $sql = Database::query("SELECT * FROM `".table("channels")."` WHERE `name`=".Database::qlean($name)); + if($sql->rows() == 1){ + self::$channels[$name] = new ChannelData($sql->fetch()); + cli_title(); + return true; + } + + return false; + } + + /** + * Get the channel data handler + * @param string $name channel name + * @return ChannelData ChannelData if exists or null if not + */ + public static function get($name){ + if(self::exists($name)){ + return self::$channels[$name]; + } + + return null; + } + + public static function create($name, $title=null){ + if(self::exists($name)){ + return false; + } + + Database::insert("channels", [ + "name" => $name, + "title" => ($title == null ? $name : $title), + "start_group" => 0, + ]); + + $data = self::get($name); + $data->join(get_user(), 0); + } + + public static function delete($name){ + if(self::exists($name)){ + //the channel exists + $chanenl = self::get($name); + //wee tel the channel data handler this channel is now on delete + $channel->onDelete(); + //remove the channel (up to data handler to delete members) + Database::query("DELETE FROM `".table("channels")."` WHERE `id`=".Database::qlean($channel->id())); + } + } +} + +class ChannelData{ + private $data; + private $users = []; + private $logger = null; + + public function controlMemberStatus(){ + echo "here\r\n"; + $name = $this->name(); + $data = $this; + $this->render_user(function(ChannelMember $member) use($name, $data){ + if(time() >= strtotime("-5 MINUTES", $member->time())){ + send_channel($name, "GHOST ".$name.": ".$member->getUser()->nick()); + $data->leave($member->getUser()); + }elseif(time() >= strtotime("+2 MINUTES", $member->time())){ + //contole the user is mark as inaktiv + if(!$member->isInaktiv()){ + $member->markInaktiv(); + } + } + }); + } + + public function render_user($callback){ + $cache = $this; + User::run(function(UserData $user) use($callback, $cache){ + if($cache->is_member($user->id())){ + //okay wee has this as memeber :) + $callback($cache->users[$user->id()]); + } + + return null; + }); + } + + public function log($message){ + $this->logger->appendLine($message); + } + + public function __construct($data){ + $this->data = $data; + $this->logger = new Logger($this); + } + + public function id(){ + return $this->data["id"]; + } + + public function name(){ + return $this->data["name"]; + } + + public function title(){ + return $this->data["title"]; + } + + public function is_member($uid){ + //control if wee got the user cached + if(!empty($this->users[$uid])) + return true; + + //wee control if the user is member but not yet cached. + $sql = Database::query("SELECT * FROM `".table("channel_member")."` WHERE `cid`='".$this->id()."' AND `uid`=".Database::qlean($uid)); + + if($sql->rows() == 1){ + $this->users[$uid] = new ChannelMember($sql->fetch(), getUserById($uid), $this); + return true; + } + + return false; + } + + public function join(UserData $user, $gid = null){ + if(!$this->is_member($user->id())){ + Database::insert("channel_member", [ + "uid" => $user->id(), + "cid" => $this->id(), + "gid" => $gid == null ? 0 : $gid, + "activ" => time(), + "inaktiv" => NO, + ]); + + if($this->is_member($user->id())){ + send_channel($this->name(), "JOIN ".$this->name().": ".$user->nick()); + return true; + } + } + return false; + } + + public function leave(UserData $user){ + $query = Database::query("DELETE FROM `".table("channel_member")."` WHERE `uid`='".$user->id()."' AND `cid`='".$this->id()."'"); + if($query->rows() != 0){ + unset($this->users[$user->id()]); + return true; + } + + //let us control member count if 0 remove the channel + if(count($this->users) == 0){ + //okay remove the channel + Channel::delete($this->name()); + } + + return false; + } + + public function onDelete(){ + Database::query("DELETE FROM `".table("channel_member")."` WHERE `cid`='".$this->id()."'"); + $this->logger->end(); + } +} + +class ChannelMember{ + private $user; + private $data; + private $channel; + + public function __construct($data, UserData $user, ChannelData $channel){ + $this->user = $user; + $this->data = $data; + $this->channel = $channel; + } + + /** + * Get the user object + * @return UserData + * return the userdata object + */ + public function getUser(){ + return $this->user; + } + + /** + * Get the last time the user has sent a message + * @return int time + */ + public function time(){ + return $this->data['activ']; + } + + public function isInaktiv(){ + return $this->data["inaktiv"] == YES; + } + + public function markInaktiv(){ + $query = Database::query("UPDATE `".table("channel_member")."` SET `inaktiv`='".YES."' WHERE `id`='".$this->data["id"]."'"); + send_channel($this->channel->name(), "INAKTIV ".$this->channel->name().": ".$this->getUser()->nick()); + return $query->rows() != 0; + } +} diff --git a/include/command/globel/join.php b/include/command/globel/join.php new file mode 100644 index 0000000..97e811a --- /dev/null +++ b/include/command/globel/join.php @@ -0,0 +1,15 @@ +join_channel($channel); + }else{ + send("ERROR: invalid channel on join command"); + } +} diff --git a/include/command/globel/login.php b/include/command/globel/login.php new file mode 100644 index 0000000..d47a7c2 --- /dev/null +++ b/include/command/globel/login.php @@ -0,0 +1,14 @@ +getCurrent()->connectionData["token"] = $data; + } + send("LOGIN: ".($isOkay ? "true" : "false"), true); +} diff --git a/include/command/globel/title.php b/include/command/globel/title.php new file mode 100644 index 0000000..287b008 --- /dev/null +++ b/include/command/globel/title.php @@ -0,0 +1,9 @@ +is_member(get_user()->id())){ + send("TITLE ".$channel.": ".$c->title()); + }else{ + send("ERROR: not member in the channel"); + } +} \ No newline at end of file diff --git a/include/config.php b/include/config.php new file mode 100644 index 0000000..1b2e540 --- /dev/null +++ b/include/config.php @@ -0,0 +1,29 @@ + $db_host, + "user" => $db_user, + "pass" => $db_pass, + "data" => $db_name, + "prefix" => DB_PREFIX, + ]; +} + +class Config{ + private static $data = []; + + public static function init(){ + $sql = Database::query("SELECT `key`, `value` FROM `".table("config")."`"); + while($row = $sql->fetch()) + self::$data[$row["key"]] = $row["value"]; + } + + public static function get($key){ + return self::$data[$key]; + } +} diff --git a/include/database.php b/include/database.php new file mode 100644 index 0000000..dadca9b --- /dev/null +++ b/include/database.php @@ -0,0 +1,96 @@ +connect_error) + return $con->connect_error; + + $con->set_charset("UTF-8"); + + self::$prefix = $data["prefix"]; + ShoutDown::add(function(){ + Database::close();//close the connection when wee are done + }); + + return false; + } + + public static function query($request){ + $query = self::$connection->query($request); + if(is_bool($query) || $query == null) + return $query; + + return new DatabaseResult($query); + } + + public static function error(){ + return [self::$connection->error, self::$connection->errno]; + } + + public static function insert($table, array $data){ + $result = self::query($sql = self::createInsert($table, $data)); + if(!$result){ + echo "[SQL Insert error]\r\n"; + echo "[Message]".self::$connection->error."\r\n"; + echo "[Number] ".self::$connection->errno."\r\n"; + echo "[SQL] ".$sql."\r\n"; + exit; + } + } + + public static function qlean($item){ + return "'".self::$connection->real_escape_string($item)."'"; + } + + public static function close(){ + self::$connection->close(); + } + + private static function createInsert($table, array $data){ + $row = []; + $value = []; + + foreach($data as $key => $values){ + $row[] = $key; + if(is_array($values)) + $value = $values[0]; + else + $value[] = self::qlean($values); + } + + return "INSERT INTO `".table($table)."` (`".implode("`,`", $row)."`) VALUES (".implode(",", $value).")"; + } +} + +function table($name){ + return Database::$prefix."chat_".$name; +} + +class DatabaseResult{ + private $result; + + public function __construct(mysqli_result $result){ + $this->result = $result; + } + + public function rows(){ + return $this->result->num_rows; + } + + public function fetch(){ + return $this->result->fetch_assoc(); + } +} diff --git a/include/define.php b/include/define.php new file mode 100644 index 0000000..a59e6b1 --- /dev/null +++ b/include/define.php @@ -0,0 +1,3 @@ +controlMemberStatus(); + }); +} \ No newline at end of file diff --git a/include/logger.php b/include/logger.php new file mode 100644 index 0000000..3092298 --- /dev/null +++ b/include/logger.php @@ -0,0 +1,71 @@ +name()."'"); + if($query->rows() == 1){ + $this->init($query->fetch()); + }else{ + $this->create($data); + } + } + + function appendLine($line){ + $line = $line."\r\n"; + fwrite($this->buffer, $line, strlen($line)); + } + + function close(){ + if($this->buffer != null){ + fclose($this->buffer); + } + } + + function end(){ + Database::query("UPDATE `".table("logger")."` SET `closed`=NOW() WHERE `id`='".$this->id."'"); + $this->close(); + } + + private function create(ChannelData $data, $prefix = null){ + if($prefix != null) + $name = $prefix."_".$data->name(); + else + $name = $data->name(); + + $name .= ".txt"; + + //controle if the data is exits + $query = Database::query("SELECT * FROM `".table("logger")."` WHERE `file_name`='".$name."'"); + if($query->rows() != 0){ + $this->create($data, (is_numeric($prefix) ? $prefix++ : 1)); + return; + } + + Database::insert("logger", [ + 'channel' => $data->name(), + 'file_name' => $name, + 'channel' => $data->name(), + 'dir' => realpath(dirname(__FILE__)."/log/"), + ]); + + $this->init(Database::query("SELECT * FROM `".table("logger")."` WHERE `channel`='".$data->name()."'")->fetch()); + } + + private function init(array $data){ + $buffer=$this; + ShoutDown::add(function() use($buffer){ + $buffer->close(); + }); + $file = $data["dir"]."/".$data["file_name"]; + if(file_exists($file)) + $type = "a+"; + else + $type = "w+"; + + $this->buffer = fopen($file, $type); + $this->id = $data["id"]; + } +} \ No newline at end of file diff --git a/include/server.php b/include/server.php new file mode 100644 index 0000000..01a3047 --- /dev/null +++ b/include/server.php @@ -0,0 +1,189 @@ + $argv[1], + "port" => $argv[2] + ])); + fclose($fopen); + + ShoutDown::add(function (){ + if(is_cli()&&file_exists(WEBSOCKET_CONFIG_PATH)) + @unlink(WEBSOCKET_CONFIG_PATH); + }); + + WebSocketCache::$cache = $websocket = new WebSocket($argv[1], $argv[2]); + + if(!$websocket->init()){ + echo "WebSocket failed to initlize\r\n"; + return; + } + + cli_title(); + + $websocket->appendEvents("onmessage", function (WebSocketClient $client, $data){ + echo "[C]".$data."\r\n"; + Session::set_current(empty($client->connectionData["token"]) ? null : $client->connectionData["token"]); + handlePost($data); + }); + + $websocket->appendEvents("onclose", function(WebSocketClient $client){ + if(empty($client->connectionData["token"])) + return;//this user is never login :) + + $user = User::get($client->connectionData["token"]); + foreach($user->getChannelNames() as $name){ + $user->leave_channel($name); + } + + cli_title(User::numberUser(), 0); + }); + + $websocket->appendEvents("onconnect", function(){ + cli_title(); + }); + + $websocket->appendEvents("newcyclus", function(){ + echo "hehe\r\n"; + garbage_collect(); + }); + + $websocket->listen(); + + return false; +} +function serverAjaxStart(){} +function handlePost($message){ + // is this globel message or is it channel message. + // globel message "Command: data + // channel "Command Channel: data + $first = explode(" ", substr($message, 0, strpos($message, ": "))); + $data = substr($message, strpos($message, ": ")+2); + + // control if the user has a token. + if(Session::getCurrentToken()==null){ + if(count($first)==1&&$first[0]=="LOGIN"){ + if(!is_cli()&&cookie("identify")!=$data){ + send("ERROR: Token is broken"); + return; + } + globel_login($data); + }else{ + send("ERROR: You are not login yet", true); + } + return; + } + + if(count($first)==1){ + handleGlobelPost($first[0], $data); + return; + }else{ + handleChannelPost($first[0], $first[1], $data); + } + + //save the post (both in ajax and websocket) + Database::insert("message", [ + 'uid' => get_user()->id(), + 'message' => $message, + 'channel' => Channel::get($first[1])->id(), + 'sent' => time(), + ]); +} +function handleGlobelPost($command, $data){ + switch($command){ + case "JOIN": + globel_join($data); + break; + case "TITLE": + get_title($data); + break; + } +} +function handleChannelPost($command, $channel, $data){ + switch(strtolower($command)){ + case "title": + + break; + } +} +function send($msg, $private = false){ + if(is_cli()){ + WebSocketSend($msg, $private); + }else{} +} +/** + * Send a message to users in a given channel. + * @param string $channel name of channel + * @param string $message message to send to the channel + */ +function send_channel($channel, $message){ + Channel::get($channel)->log($message); + Channel::renderUsersInChannel($channel, function (ChannelMember $member) use($channel, $message){ + if(is_cli()){ + WebSocketSend($message, false, $member->getUser(), $channel); + } + }); +} +function WebSocketSend($msg, $private, $user = null, $channel = null){ + if($private){ + WebSocketCache::$cache->getCurrent()->write_line($msg); + return; + } + + WebSocketCache::$cache->render_clients(function (WebSocketClient $client) use($msg){ + if(array_key_exists("token", $client->connectionData)){ + $client->write_line($msg); + } + }); +} +function ip(){ + if(is_cli()){ + return WebSocketCache::$cache->getCurrent()->ip(); + } + + return $_SERVER['REMOTE_ADDR']; +} + +/** + * Ajax server need to set varibels and header. + * This is happens here + */ +function init_ajax(){ + Ajax::header([ + [ + "Content-Type", + "application/json" + ], + [ + "Cache-Control", + "no-store, no-cache, must-revalidate, max-age=0" + ], + [ + "Cache-Control", + "post-check=0, pre-check=0", + false + ], + [ + "Pragma", + "no-cache" + ] + ]); +} diff --git a/include/session.php b/include/session.php new file mode 100644 index 0000000..b722116 --- /dev/null +++ b/include/session.php @@ -0,0 +1,76 @@ +rows() != 0){ + //controle if wee got a cache of the session + if(!empty(self::$sessions[$token])){ + unset(self::$sessions[$token]); + } + + return true; + } + + return false; + } + + public static function set_current($token){ + if($token != null && !self::token_exists($token)) + return false; + + self::$current = $token; + return true; + } + + public static function getCurrentToken(){ + return self::$current; + } + + private static function token_exists($token){ + //if it not exists in the session array it not exists at all! + if(!empty(self::$sessions[$token])) + return true; + + $sql = Database::query("SELECT * FROM `".table("session_data")."` WHERE `token`=".Database::qlean($token)." OR `ip`=".Database::qlean(ip())); + if(!$sql){ + $error = Database::error(); + trigger_error("SQL FAIL\r\n[Number]".$error[0]."\r\n[Message]".$error[1]); + } + if($sql->rows() == 1){ + $row = $sql->fetch(); + if($row["ip"] == ip() && $row["token"] == $token){ + self::$token[$token] = new SessionData($token, $row); + return true; + } + Database::query("DELETE FROM `".table("session_data")."` WHERE `token`=".Database::qlean($token)." OR `ip`=".Database::qlean(ip())); + Database::query("DELETE FROM `".table("session")."` WHERE `sid`='".$row["id"]."'"); + } + return false; + } +} + + +class SessionData extends ArrayIterator{ + private $token; + + public function __construct($token){ + $this->token = $token; + } + + public function control(){ + + } +} diff --git a/include/shutdown.php b/include/shutdown.php new file mode 100644 index 0000000..9b6f1ac --- /dev/null +++ b/include/shutdown.php @@ -0,0 +1,14 @@ +"; + echo "
"; + + echo "
"; + echo "
"; + + echo "
"; + echo "
"; + + echo "
"; +echo ""; \ No newline at end of file diff --git a/include/style/css/main.css b/include/style/css/main.css new file mode 100644 index 0000000..69b90ac --- /dev/null +++ b/include/style/css/main.css @@ -0,0 +1,9 @@ +#chat_container{ + background-color: #0066ff; + height:550px; +} + + +.not_loaded{ + display:none; +} \ No newline at end of file diff --git a/include/style/js/main.js b/include/style/js/main.js new file mode 100644 index 0000000..c409985 --- /dev/null +++ b/include/style/js/main.js @@ -0,0 +1,239 @@ +window.onload = start_chat; +var wsr = null; +var unsuccessfulLogin = 0; +var config = []; +var container = []; + +var AjaxRespond = (function() { + function AjaxRespond(obj) { + this.obj = obj; + } + + AjaxRespond.prototype.toText = function() { + return this.obj.responseText; + }; + + AjaxRespond.prototype.toJson = function() { + return JSON.parse(this.toText()); + }; + + AjaxRespond.prototype.toXml = function() { + return this.obj.responseXML; + }; + + return AjaxRespond; +})(); + +function appendTab(handler){ + function createTab(handler){ + var container = document.createElement("span"); + container.className = "chat_tab"; + + if(typeof handler.icon !== "undefined"){ + //append icon + var icon = document.createElement("img"); + icon.className = "chat_tab_icon"; + container.appendChild(icon); + } + + //control for name + if(typeof handler.name !== "undefined"){ + container.appendChild(document.createTextNode(handler.name)); + } + + //append it to the tab list + document.getElementById("chat_tap_container").appendChild(container); + } + + //create tab + createTab(handler); +} + +var ChannelHandler = (function(){ + function ChannelHandler(name){ + this.name = name; + appendTab(this); + //wee want to get a title on this channel :) + send("TITLE: "+this.name); + } + + ChannelHandler.prototype.onBlur = function(){ + + }; + + ChannelHandler.prototype.onFocus = function(){ + + }; + + return ChannelHandler; +})(); + +function get(url, callback) { + var ajax = new XMLHttpRequest(); + ajax.open("GET", url, true); + ajax.send(); + ajax.onreadystatechange = function() { + if (this.readyState == 4 && this.status == 200) { + callback(new AjaxRespond(this)); + } + } +} + +function start_chat() { + console.log("Chat loading") + // wee send a get request to status.php to see what wee should do here :) + get("status.php", function(ajax) { + var json = ajax.toJson(); + config = json["config"]; + if (json['isWebSocket']) { + console.log("Chat connect to websocket"); + startWebSocket(json["host"], json["port"]); + } else { + + } + }); +} + +function startWebSocket(host, port) { + websocket = new WebSocket("ws://" + host + ":" + port); + + websocket.onerror = function(evt) { + console.log(evt.data); + console.log("Error on websocket connecttion: "+evt.data); + }; + + websocket.onmessage = function(evt) { + handleMessage(evt.data); + }; + + websocket.onopen = function() { + console.log("WebSocket connection is now open"); + init_server(); + }; + + websocket.onclose = function() { + console.log("WebSocket connection is now closed"); + }; + + wsr = websocket; +} + +function cookie(name) { + var cookieParts = document.cookie.split(";"); + for (i = 0; i < cookieParts.length; i++) { + var data = cookieParts[i].split("="); + if (data[0].trim() == name) { + return data[1].trim(); + } + } + + return null; +} + +function init_server() { + var elemtns = document.getElementsByClassName("not_loaded"); + for(var i=0;iid() == $id) + return $user; + return false; + }); +} + +class User{ + private static $user = []; + + public static function numberUser(){ + return count(self::$user); + } + + public static function run($callback){ + $sql = Database::query("SElECT * FROM `".table("user")."`"); + while($row = $sql->fetch()){ + if(!empty(self::$user[$row["token"]])) + $u = self::$user[$row["token"]]; + else + $u = self::$user[$row["token"]] = new UserData($row); + + if($return = $callback($u)) + return $return; + } + return null; + } + + public static function get($token){ + if(self::exists($token)){ + return self::$user[$token]; + } + + return null; + } + + public static function exists($token){ + if(!empty(self::$user)) + return true; + + $sql = Database::query("SELECT * FROM `".table("user")."` WHERE `token`=".Database::qlean($token)); + if($sql->rows() == 1){ + self::$user[$token] = new UserData($sql->fetch()); + cli_title(); + return true; + } + + return false; + } +} + +class UserData{ + private $data = []; + private $channels = []; + + public function __construct(array $data){ + $this->data = $data; + } + + public function id(){ + return $this->data["id"]; + } + + public function nick(){ + return $this->data["nick"]; + } + + public function join_channel($name){ + $channel = Channel::get($name); + if($channel == null){ + Channel::create($name); + return; + } + + if(!$channel->is_member($this->id())){ + if($channel->join($this)){ + $this->channels[$channel->id()] = $chanenl->name(); + } + } + } + + public function leave_channel($name){ + $channel = Channel::get($name); + if($channel != null){ + //control if member of this channel + if($channel->is_member($this->id())){ + $channel->leave($this); + unset($this->channels[$channel->id()]); + return true; + } + } + + return false; + } + + public function getChannelsId(){ + return array_values($this->channels); + } + + public function getChannelNames(){ + return array_keys($this->channels); + } + + public function ip(){ + return $this->data["ip"]; + } +} diff --git a/include/websocket.php b/include/websocket.php new file mode 100644 index 0000000..cd40b5f --- /dev/null +++ b/include/websocket.php @@ -0,0 +1,234 @@ +host = $host; + $this->port = $port; + } + public function connectionCount(){ + return count($this->clients); + } + public function render_clients($callback){ + foreach($this->clients as $client){ + $callback($client); + } + } + public function getCurrent(){ + return $this->currentClient; + } + public function init(){ + if(empty($this->host)||empty($this->port)) + return false; + + if(!function_exists("socket_create")) + return false; + + if(($this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP))===false) + return false; + + if(socket_set_option($this->socket, SOL_SOCKET, SO_REUSEADDR, 1)===false) + return false; + + if(!filter_var($this->host, FILTER_VALIDATE_IP)){ + $this->host = gethostbyname($this->host); + } + + if(@socket_bind($this->socket, $this->host, $this->port)===false){ + return false; + } + + if(socket_listen($this->socket, 20)===false){ + return false; + } + + $this->newClient($this->socket, true); + return true; + } + public function appendEvents($event, $callback){ + if(empty($this->events[$event])){ + $this->events[$event] = $callback; + return true; + } + + return false; + } + public function listen(){ + $this->run = true; // if the websocket is stopped befor start it here + while($this->run){ + $this->triggerEvents("newcyclus", null, false); + $read = $this->connections; + $write = $ex = null; + @socket_select($read, $write, $ex, null); + if(in_array($this->socket, $read)){ + $this->newClient(socket_accept($this->socket)); + }else{ + foreach($read as $socket){ + // wee set the current client :) + $controlDiconect = true; + $this->currentClient = $this->getClient($socket); + while($buffer = @socket_recv($socket, $buf, 1024, 0)>=1){ + $controlDiconect = false; + $this->triggerEvents("onmessage", $this->unmask($buf)); + } + + if($buffer == false || $buffer == 0){ + $this->removeClient($socket); + } + } + } + } + } + private function newClient($stream, $onStart = false){ + if($stream<0){ + echo "Fail to accept socket: ".$stream."\r\n"; + return; + } + $this->connections[] = $stream; + if(!$onStart && $this->handshake($stream)){ + $this->clients[] = $this->currentClient = new WebSocketClient($stream); + $this->triggerEvents("onconnect", null); + } + return $this->currentClient; + } + private function removeClient($stream){ + echo "Remove client: ".$stream."\r\n"; + // trigger event onclose + $this->triggerEvents("onclose", null); + unset($this->connections[array_search($stream, $this->connections)]); + for($i = 0; $iclients); $i++) + if($this->clients[$i]->isStream($stream)){ + array_slice($this->clients, $i, 1); + return; + } + + @socket_close($stream); + } + private function getClient($stream){ + for($i = 0; $iclients); $i++){ + if($this->clients[$i]->isStream($stream)){ + return $this->clients[$i]; + } + } + + return null; + } + private function handshake($stream){ + $head = array(); + // handshake :) + $lines = explode("\r\n", socket_read($stream, 1024)); + for($i = 0; $iremoveClient($stream); + echo "Missing Sec-WebSocket-Key\r\n"; + return false; + } + $key = $head['Sec-WebSocket-Key']; + $hkey = base64_encode(sha1($key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true)); + + $uhead = array(); + + $uhead[] = "HTTP/1.1 101 Web Socket Protocol Handshake"; + $uhead[] = "Upgrade: websocket"; + $uhead[] = "Connection: Upgrade"; + $uhead[] = "Sec-WebSocket-Accept: ".$hkey; + $handshake = implode("\r\n", $uhead)."\r\n\r\n"; + // exit($handshake); + if(socket_write($stream, $handshake, strlen($handshake))===false){ + exit("Handshake fail"); + } + echo "New client connected to server\r\n"; + return true; + } + private function unmask($text){ + $length = ord($text[1])&127; + if($length==126){ + $masks = substr($text, 4, 4); + $data = substr($text, 8); + }elseif($length==127){ + $masks = substr($text, 10, 4); + $data = substr($text, 14); + }else{ + $masks = substr($text, 2, 4); + $data = substr($text, 6); + } + $text = ""; + for($i = 0; $ievents[$name])){ + $buffer = $this->events[$name]; + if($enableClient) + $buffer($this->currentClient, $data); + else + $buffer($data); + } + } +} +class WebSocketClient{ + private $stream; + public $connectionData = []; + private $myIp = null; + public function __construct($stream){ + $this->stream = $stream; + } + public function isStream($stream){ + return $this->stream==$stream; + } + public function write_line($str){ + $string = $this->mask($str); + if(!$s = @socket_write($this->stream, $string, strlen($string))) + echo "[".$this->stream."]failed to write the line: ".$str."\r\n"; + + echo "[S]".$str."\r\n"; + } + public function close(){ + @socket_close($this->stream); + } + public function ip(){ + if($this->myIp==null){ + socket_getpeername($this->stream, $this->myIp); + } + return $this->myIp; + } + private function mask($data){ + $frame = array(); + $encoded = ""; + $frame[0] = 0x81; + $data_length = strlen($data); + + if($data_length<=125){ + $frame[1] = $data_length; + }else{ + $frame[1] = 126; + $frame[2] = $data_length>>8; + $frame[3] = $data_length&0xFF; + } + + for($i = 0; $icreateUser(0, $this->createNick(), 0, ""); + $query = dbquery("SELECT * FROM `".DB_PREFIX."chat_user` WHERE `token`='".cookie("identify")."' AND `is_user`='0'"); + }else{ + $this->createUser($userdata["user_id"], $userdata["user_name"], 1, $userdata["user_avatar"]); + $query = dbquery("SELECT * FROM `".DB_PREFIX."chat_user` WHERE `uid`='".$userdata['user_id']."' AND `is_user`='1'"); + } + } + + $this->data = dbarray($query); + + //control for token and see if it is a match else update the table user tokens :) + if($this->data["token"] != cookie("identify")){ + dbquery("UPDATE `".DB_PREFIX."chat_user` SET `token`='".cookie("identify")."' WHERE `id`='".$this->data["id"]."'"); + $this->data["token"] = cookie("identify"); + } + } + public function renderChannelList($callback){ + $list = ""; + $query = dbquery("SELECT c.id AS id, c.name AS name FROM `".DB_PREFIX."chat_channels` AS c + LEFT JOIN `".DB_PREFIX."chat_channel_member` AS m ON c.id=m.cid + WHERE m.uid='".$this->data["id"]."'"); + while($row = dbarray($query)){ + $list = $callback($row['id'], $row['name'], $list); + } + return $list; + } + private function createNick(){ + $use = "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890"; + $return = ""; + for($i = 0; i<4; $i++){ + $return .= $use[mt_rand(0, strlen($use)-1)]; + } + + return $return; + } + private function createUser($uid, $nick, $isUser, $profileimage){ + dbquery("INSERT INTO `".DB_PREFIX."chat_user` ( + `uid`, + `nick`, + `is_user`, + `profile`, + `token`, + `activ` + ) VALUES ( + '".$uid."', + '".$nick."', + '".$isUser."', + '".($profileimage == "" ? IMAGES."avatars/noavatar100.png" : $profileimage)."', + '".$this->getToken()."', + '".time()."' + )"); + } +} +class Session{ + private static $tokens = null; + private static $data = null; + private static $id = null; + private static $user; + + public static function login(User $user){ + self::$user = $user; + if(!$user->hasToken()){ + // delete all tokens there point to this ip addrresse :) + dbquery("DELETE FROM `".DB_PREFIX."chat_session_data` WHERE `ip`='".get_ip()."'"); + // no token giving :) + self::createToken($user); + }else{ + //control if wee has a valid session :) + $query = dbquery("SELECT * FROM `".DB_PREFIX."chat_session_data` WHERE `ip`='".get_ip()."' AND `token`='".$user->getToken()."'"); + if(dbrows($query) == 0){ + self::createToken($user); + } + } + + $user->login(); + } + + public static function has($key){ + return array_key_exists($key, self::getHandler()); + } + + public static function remove($key){ + if(self::has($key)){ + dbquery("DELETE FROM `".DB_PREFIX."chat_session` WHERE `sid`='".self::getID()."' AND `key`='".$key."'"); + unset(self::$data[$key]); + } + } + + public static function get($key){ + if(self::has($key)){ + self::updateActiv($key); + $array = self::getHandler(); + return $array[$key]; + } + + return null; + } + + public static function set($key, $value){ + if(self::has($key)){ + dbquery("UPDATE `".DB_PREFIX."chat_session` SET `active`='".time()."', `value`='".$value."' WHERE `sid`='".self::getID()."' AND `key`='".$key."'"); + }else{ + dbquery("INSERT INTO `".DB_PREFIX."chat_session` ( + `sid`, + `key`, + `value`, + `active` + ) VALUES ( + '".self::getID()."', + '".$key."', + '".$value."', + '".time()."' + )"); + } + + self::getHandler();//to be sure it is interlize :) + self::$data[$key] = $value; + } + + public static function garbage_collect(){ + $remove = time()-60*60*24; + dbquery("DELETE FROM `".DB_PREFIX."chat_session_data` WHERE `activ`<'".$remove."'"); + dbquery("DELETE FROM `".DB_PREFIX."chat_session` WHERE `active`<'".$remove."'"); + + } + + private static function updateActiv($key){ + dbquery("UPDATE `".DB_PREFIX."chat_session` SET `active`='".time()."' WHERE `sid`='".self::getID()."' AND `key`='".$key."'"); + } + + private static function getHandler(){ + if(self::$data == null){ + self::$data = []; + $query = dbquery("SELECT `key`, `value` FROM `".DB_PREFIX."chat_session` WHERE `sid`='".self::getID()."'"); + while($row = dbarray($query)) + self::$data[$row['key']] = $row['value']; + } + + return self::$data; + } + + private static function getID(){ + if(self::$id == null){ + $query = dbquery("SELECT `id` FROM `".DB_PREFIX."chat_session_data` WHERE `token`='".self::$user->getToken()."'"); + $row = dbarray($query); + self::$id = $row['id']; + } + + return self::$id; + } + + private static function createToken(User $user){ + $str = "qwertyuioplkjhgfdsazxcvbnmQWERTYUIOPLKJHGFDSAZXCVBNM1234567890"; + $use = ""; + for($i = 0; $i<1001; $i++) + $use .= $str[mt_rand(0, strlen($str)-1)]; + + $use = md5($use); + + if(in_array($use, self::getTokenList())) + return self::createToken($user); + + $user->setToken($use); + dbquery("INSERT INTO `".DB_PREFIX."chat_session_data` ( + `ip`, + `token`, + `activ` + )VALUES( + '".get_ip()."', + '".$use."', + '".time()."' + )"); + } + private static function getTokenList(){ + if(self::$tokens==null){ + $sql = dbquery("SELECT `token` FROM `".DB_PREFIX."chat_session_data`"); + while($row = dbarray($sql)) + self::$tokens[] = $row["token"]; + } + + return self::$tokens; + } +} + +$user = new User(); + +Session::garbage_collect(); +Session::login($user); + +//get the last id and set it to the session :) +$query = dbquery("SELECT `id` FROM `".DB_PREFIX."chat_message` ORDER BY id DESC LIMIT 1;"); +$row = dbarray($query); +Session::set("last_id", $row["id"] == "" ? 0 : $row['id']); + +//wee can start the page here ;) +require_once INCLUDES."infusions_include.php"; +require_once THEMES."templates/header.php"; +add_to_head(""); +add_to_head(""); +opentable("Chat"); +include "include/style/chat.php"; +closetable(); +require_once THEMES."templates/footer.php"; + diff --git a/infusion.php b/infusion.php deleted file mode 100644 index cb8b035..0000000 --- a/infusion.php +++ /dev/null @@ -1,146 +0,0 @@ - 'Chat', - 'url' => 'chat.php?onDemand=what', - 'visibility' => '0', -); - -$inf_droptable[1] = DB_CHATMESSAGE; -$inf_droptable[2] = DB_CHATMEMBER; -$inf_droptable[3] = DB_CHATNAME; -$inf_droptable[4] = DB_CHATUCONFIG; -$inf_droptable[5] = DB_IGNOERE; -$inf_droptable[6] = DB_CHATFILE; - -$inf_deldbrow[1] = DB_SETTINGS_INF." WHERE settings_inf='".$inf_folder."'"; -$inf_deldbrow[2] = DB_ADMIN." WHERE admin_rights='CHAD' OR admin_rights='CHADBAN' OR admin_rights='CHADLOG'"; - -$inf_adminpanel[1] = array( - 'title' => 'Chat setting', - 'image' => '', - 'panel' => 'admin/setting.php', - 'rights' => 'CHAD' -); - -$inf_adminpanel[2] = array( - 'title' => 'Chat bans', - 'image' => '', - 'panel' => 'admin/ban.php', - 'rights' => 'CHADBAN' -); - -$inf_adminpanel[3] = array( - 'title' => 'Chat log', - 'image' => '', - 'panel' => 'admin/log.php', - 'rights' => 'CHADLOG' -); - -//i can not find other way to do this. if you have one so sey it :) -if(isset($_POST['infusion'])){ - dbquery("ALTER TABLE `".DB_USERS."` ADD `nick` VARCHAR(255) NULL DEFAULT NULL AFTER `user_name`"); -} - -if (isset($_GET['defuse'])) { - dbquery("ALTER TABLE `".DB_USERS."` DROP `nick`"); -} - diff --git a/infusion_db.php b/infusion_db.php deleted file mode 100644 index 374a245..0000000 --- a/infusion_db.php +++ /dev/null @@ -1,26 +0,0 @@ - " - + "["+data.time+"] "; - if(type == "bot"){ - message += ""+this.Main.data.systemBot.name+": "; - }else if(type == "msg"){ - message += ""+this.Main.add_default_item_to_message(this.Main.add_smylie_to_string(data.message))+""; - }else{ - message += " " - + ""+data['obj'].nick+": "; - } - if(type != "msg"){ - message += ""+this.Main.add_default_item_to_message(this.Main.add_smylie_to_string(data.message))+" "; - + ""; - }else{ - message += ""; - } - - this.Main.getDom("main").append(message); - //vi scrooler nu tilbage til bunden :) - this.Main.getDom("main").getObject().scrollTop = this.Main.getDom("main").getObject().scrollHeight; - }; - - Message.prototype.addBotItems = function(data){ - if(!data.isBot){ - return ""; - } - - if(data['obj']['langKey'] === null && data['obj']['langData'] === null){ - return ""; - } - - return " langString='"+data['obj']['langKey']+"' langData='"+JSON.stringify(data['obj']['langData'])+"'"; - } - - return Message; -})(); diff --git a/js/sound.js b/js/sound.js deleted file mode 100644 index 1b644cd..0000000 --- a/js/sound.js +++ /dev/null @@ -1,28 +0,0 @@ -var Sound = (function(){ - - function Sound(obj){ - this.Obj = obj.getObject(); - }; - - Sound.prototype.play = function(){ - this.Obj.play(); - }; - - Sound.prototype.stop = function(){ - this.Obj.pause(); - this.Obj.currentTime = 0; - }; - - Sound.prototype.maxTime = function(sek){ - this.sek = sek; - this.Obj.addEventListener("timeupdate",this.stopTime); - }; - - Sound.prototype.stopTime = function(){ - if(system.get_object("sound").sek < system.get_object("sound").Obj.currentTime.toFixed(3)){ - system.get_object("sound").stop(); - } - }; - - return Sound; -})(); \ No newline at end of file diff --git a/js/status.js b/js/status.js deleted file mode 100644 index 5db6d98..0000000 --- a/js/status.js +++ /dev/null @@ -1,26 +0,0 @@ -var Status = (function(){ - function Status(sy){ - this.s = sy; - } - - Status.prototype.updateSprog = function(s){ - this.s = s; - }; - - Status.prototype.call = function(){ - J("#statusIndikator").css("backgroundColor","#0066FF"); - J("#statusIndikator").getObject().title = this.s.onWork; - }; - - Status.prototype.error = function(){ - J("#statusIndikator").css("backgroundColor","red"); - J("#statusIndikator").getObject().title = this.s.onServerError; - }; - - Status.prototype.okay = function(){ - J("#statusIndikator").css("backgroundColor","green"); - J("#statusIndikator").getObject().title = this.s.onOkay; - }; - - return Status; -})(); \ No newline at end of file diff --git a/js/system.js b/js/system.js deleted file mode 100644 index 30eaffe..0000000 --- a/js/system.js +++ /dev/null @@ -1,1423 +0,0 @@ -var system = null; -var System = (function () { - - System.prototype.option_name = {'online': 'online', 'setting': 'user', 'smylie': 'smyile', 'upload' : 'upload'}; - System.prototype.object = {}; - System.prototype.smylie = []; - System.prototype.is_socket = false; - System.prototype.user_config = {}; - System.prototype.chat_name = null; - System.prototype.user_in_channel = []; - System.prototype.null = ""; - System.prototype.li = 1; - System.prototype.liCache = []; - System.prototype.timer = null; - System.prototype.ajax = []; - System.prototype.ping_send = {'command' : null, 'channel' : null}; - System.prototype.u_num = 0; - System.prototype.channelCount = 0;//count number of channels :) - System.prototype.langName = null; - System.prototype.changeStatus = true; - - //config tag ;) - System.prototype.valid_config = ['sound','textColor','lang','time']; - - function System(data) { - this.data = data; - this.setDom(); - //vi sikre os at vi har tømt chatten inden vi går igang ;) - this.unset_screen(); - //vi sætter nu vent venligst billed ind ;) - this.set_background("lib/vent.png"); - //vi henter nu sprog - this.set_lang(); - //vi sætter nu status - this.new_status(); - //vi indstiller nu ajax ;) - if(this.get_protokol() != "ajax"){ - this.new_ajax(); - } - //vi sætter nu message ;) - this.init_message(); - //vi sætter nu cache - this.init_cache(); - //vi sætter nu lyd - this.init_sound(); - - //vi cloner JAjax isOpen - if(this.get_protokol() != "ajax"){ - this.new_ajax_query(); - this.is_socket = this.ajax[0].isOpen; - } - this.li = this.data.li; - - if (this.get_protokol() == "socket") { - this.prepare_start_socket(); - window.onbeforeunload = function(){ - - }; - }else{ - this.new_ajax_query({ - 'message' : '/getStatus', - 'channel' : 'Bot' - },'server.php?userBlock=' + this.data.browserBlock+'&sort='+this.data.user.sort+"&li=" + this.get_last_id()); - } - } - - System.prototype.reloadChatPage = function(){ - console.log("[start]reloadChatPage"); - this.stop_chat(); - this.new_ajax_query(undefined,'server.php?userBlock=' + this.data.browserBlock+'&sort='+this.data.user.sort+"&li=" + this.get_last_id()); - console.log("[done]reloadChatPage"); - }; - - System.prototype.uploadFilesClick = function(){ - this.getDom("upload").getObject().click();//vi har nu valgt denne upload knap :) - }; - - System.prototype.showFileName = function(){ - this.getDom("upload").onChange(function(){ - system.getDom("fileName").context(system.getDom("upload").context()); - }); - }; - - System.prototype.uploadFile = function(){ - var url = this.getDom("upload").context(); - - if(url == ''){ - alert("You missing to select file!"); - }else{ - var form = new FormData(); - form.append("fil",this.getDom("upload").getObject().files[0]); - var ajax = new JAjax({ - 'action' : 'upload.php', - 'method' : 'post', - 'protokol' : 'ajax', - 'error' : function(){ - system.stop_chat(); - system.get_object("status").error(); - }, - 'success' : function(data){ - if(typeof data['error'] !== "undefined"){ - - }else{ - system.new_ajax_query({ - 'message' : '/file '+data.fileID, - 'channel' : system.chat_name - },'server.php?userBlock=' + system.data.browserBlock+'&sort='+system.data.user.sort+"&li=" + system.get_last_id()); - } - }, - 'send' : form, - 'file' : true, - 'noHeader' : true - }); - - ajax.enable(); - } - }; - - System.prototype.init_sound = function(){ - this.set_object("sound",new Sound(this.getDom("newInChanMessage"))); - this.get_object("sound").maxTime(1); - }; - - System.prototype.get_last_id = function(){ - return this.li; - }; - - System.prototype.update_last_id = function(id){ - if(parseInt(id) > parseInt(this.get_last_id())){ - this.li = parseInt(id); - } - }; - - System.prototype.closhe_socket = function(){ - if(this.get_protokol() != "socket"){ - return; - } - - this.new_ajax_query({ - 'message' : '/exit', - 'channel' : 'Bot' - }) - }; - - System.prototype.send_ping = function(command_to_save,channel){ - this.new_ajax_query({ - 'message' : '/ping', - 'channel' : 'Bot' - },'server.php?userBlock='+this.data.browserBlock+'&sort='+this.data.user.sort+"&li="+this.get_last_id()); - - if(typeof command_to_save !== "undefined" && typeof channel !== "undefined"){ - this.ping_send = { - 'command' : command_to_save, - 'channel' : channel - }; - } - } - - System.prototype.onKeyPressWrite = function(e){ - if(e.keyCode == 13){ - e.preventDefault(); - var c= new Command(this.getDom("textbox").context()); - if(c.isCommand() && c.get() === "join"){ - this.send_ping(this.getDom("textbox").context(),'Bot'); - this.getDom('textbox').empty(); - return; - } - this.stop_chat(); - this.timer = 0; - this.new_ajax_query({ - 'message' : this.getDom("textbox").context(), - 'channel' : this.chat_name - },'server.php?userBlock=' + this.data.browserBlock+'&sort='+this.data.user.sort+"&li=" + this.get_last_id()); - - this.getDom("textbox").empty(); - } - }; - - System.prototype.clickConfig = function(key,value){ - if(this.valid_config.valueOf(key) == -1){ - //config findes ikke! - this.get_object("message").bot_message(this.convert_lang_string("config_not_valid",{'config' : key}),"mis"); - return null; - } - - this.new_ajax_query({ - 'message' : '/config ['+key+']['+value+']', - 'channel' : this.chat_name - },'server.php?userBlock=' + this.data.browserBlock+'&sort='+this.data.user.sort+"&li=" + this.get_last_id()); - }; - - System.prototype.get_my_stat = function(){ - return this.data.user; - }; - - System.prototype.handle_in_message = function (json,is_from_cache) { - if (typeof json === "undefined" || typeof json.message === "undefined") { - return; - } - - if(this.timer !== null){ - this.stop_chat(); - } - - for (var i = 0; i < json.message.length; i++) { - var msg = json.message[i]; - - if(!is_from_cache){ - if(this.liCache.lastIndexOf(msg['id']) != -1){ - continue; - } - - this.update_last_id(msg['id']); - this.liCache.push(msg['id']); - } - - if (msg.cid == 1 && !is_from_cache) { - this.handle_prodcast_message(msg); - } else { - if(this.user_config.sound == true || this.user_config.sound == 'true'){ - this.get_object("sound").play(); - } - if(!is_from_cache){ - this.get_object("cache").add(msg.cid, msg);//vi har nu tilføget denne besked til cache ;) - } - this.handle_nomal_msg(msg,is_from_cache); - } - } - - if(this.timer !== null){ - this.start_chat(); - } - }; - - System.prototype.handle_prodcast_message = function(msg){ - var command = new Command(msg.message); - if(!command.isCommand()){ - alert("Server sent brodcast and it was not a command \r\n"+msg.message); - return;//wee only care about command ;) - } - - switch(command.get()){ - case 'cookieOkay': - this.new_ajax_query({ - 'message' : '/getStatus', - 'channel' : 'Bot' //this is prodcast msg! - }); - break; - case 'config': - var data = command.get_param(); - var block = data[2].split(";"); - for(var i=0;i"; - } - }); - //vi sender nu en besked om at brugeren er inaktiv :) - this.get_object("message").bot_message(this.convert_lang_string('onInaktiv',{ - 'nick' : command.get_param()[2] - }),msg['id'],'red','onInaktiv',{ - 'nick' : command.get_param()[2] - }); - } - break; - case 'notInaktiv': - this.get_object("message").bot_message(this.convert_lang_string("onNInaktiv",{ - 'nick' : command.get_param()[2] - }),msg["id"],'green','onNInaktiv',{ - 'nick' : command.get_param()[2] - }); - this.getDom("user").run(function(){ - if(this.attr("uid") == msg['uid']){ - this.getObject().getElementsByClassName("u_nick")[0].innerHTML = command.get_param()[2]; - } - }); - break; - case 'maxFlood': - this.get_object("message").bot_message(this.convert_lang_string("flood",{}),msg['id'],'red','flood',{}); - break; - case 'commandDenaid': - this.get_object("message").bot_message(this.get_lang().WrongCommand,msg['id'],'red','WrongCommand',{}); - break; - case 'ignore': - this.get_object("message").bot_message(this.convert_lang_string("onIgnore",{ - 'nick' : command.get_param()[2] - }), msg['id'],'green','onIgnore',{ - 'nick' : command.get_param()[2] - }); - break; - case 'unIgnore': - this.get_object("message").bot_message(this.convert_lang_string("onUnIgnore",{ - 'nick' : command.get_param()[2] - }),msg['id'],'green','onUnIgnore',{ - 'nick' : command.get_param()[2] - }); - break; - case 'file': - this.addUploadedFile(command.get_param()[2],msg); - break; - default: - break; - } - }; - - System.prototype.addUploadedFile = function(url,msg){ - var part = url.split("."); - switch(part[(part.length-1)]){ - case 'png': - //its image :) - this.get_object("message").bot_message(this.convert_lang_string("uploadImage",{ - 'image' : '', - 'nick' : msg['nick'] - }),msg['id'],'black','uploadImage',{ - 'image' : '', - 'nick' : msg['nick'] - }); - break; - } - }; - - System.prototype.clickImage = function(obj){ - this.getDom("viewImages").setImage(obj.getElementsByTagName("img")[0].src); - this.getDom("viewImage").show(); - }; - - System.prototype.update_my_config = function(msg,command){ - var conf = /^\/updateConfig\s(.*?)\s(.*?)$/.exec(msg.message); - switch (conf[1]){ - case 'sound': - this.getDom("sound_botton").getObject().selected = (conf[2] === "true" ? true : false); - this.user_config[conf[1]] = (conf[2] == "true" ? true : false); - break; - case 'textColor': - this.getDom("textbox").css("color",conf[2]); - this.getDom("text_color").getOptions(function(value,text){ - if(value == conf[2]){ - this.getObject().slected=true; - } - }); - this.user_config[conf[1]] = conf[2]; - break; - case 'lang': - var secondLang = "English"; - - if(this.langName !== null){ - secondLang = this.langName; - } - - this.set_object("lang",this.setNewLang(conf[2],secondLang)); - this.getDom("lang_select").getOptions(function(value,text){ - if(value == system.langName){ - this.getObject().slected = true; - } - }); - this.user_config[conf[1]] = this.langName; - this.update_screen_lang(); - break; - case 'time': - this.user_config.time_format = conf[2]; - break; - } - }; - - System.prototype.join_in_channel = function(msg,command,is_cache){ - if(!this.is_num(msg['uid'])){ - return false; - } - var block = command.get_param(); - var channel = block === null ? this.trim(msg.channel) : this.trim(block[2]); - //control if block is null ;) - if(channel === this.null){ - alert("Channel is like nulll fuck"); - return; - }else if(is_cache){ - //Kun for at være sikker! - if(this.is_in_this_channel(msg.channel)){ - this.add_user_in_user_list(msg['img'],msg['nick'],msg['uid']); - this.get_object("message").bot_message(this.convert_lang_string("onJoin",{'nick' : msg['nick']}),msg['id'],"green",'onJoin',{'nick' : msg['nick']}); - } - }else if(this.get_object("cache").add_users(this.trim(msg['nick']),this.trim(msg['uid']),channel)){//channel er allerede trimmet - - var start_stat = { - 'is_in' : this.is_in_this_channel(msg['channel']), - 'is_i' : (msg['uid'] == this.get_my_stat().id) - }; - - if(start_stat.is_in){ - this.add_user_in_user_list(msg['img'],msg['nick'],msg['uid']); - if(msg.cid != 1){//1 er en global channel som alle vigtige informationer bliver skrevet ind i. derfor gøre vi intet med den når det gælder at informere brugeren om det :D - this.get_object("message").bot_message(this.convert_lang_string("onJoin",{'nick' : msg['nick']}),msg['id'],"green",'onJoin',{'nick' : msg['nick']}); - } - //alert("Yes"); - }else if(start_stat.is_i){ - this.add_channel_botton(msg['cid'],channel); - this.channelCount++;//ad one channel becuse wee is now in new channel :) - this.switch_channel(channel,msg['cid']); - this.new_ajax_query({ - 'message' : "/getOnline "+msg['channel'], - 'channel' : this.chat_name - },'server.php?userBlock=' + this.data.browserBlock+'&sort='+this.data.user.sort+"&li=" + this.get_last_id()); - } - }else{ - if(msg['uid'] == this.get_my_stat().id){ - //alert("Somting is broken!!!");//kan ikke helt finde ud af hvad der er galt :( - } - } - }; - - System.prototype.re_paint_channel_botton = function(on){ - var color = this.get_channel_botton_color(); - J(".chanenlContainer").run(function(){ - if(this.attr("cid") == on){ - this.css("backgroundColor",color.thisChannel); - }else{ - this.css("backgroundColor",color.notThisChannel); - } - }); - }; - - System.prototype.add_channel_botton = function(id,name){ - var botton = " " - + ""+this.trim(name)+" " - + " " - + " "; - - this.getDom("channel_list").append(botton); - }; - - System.prototype.on_closhe_channel_botton = function(id){ - this.getDom("channel_botton").run(function(){ - if(this.attr("cid") === id){ - //vi har nu fået fat i den rigtige channel ;) - var name = this.getObject().getElementsByClassName("channelNameContainer")[0].innerHTML; - system.leave_channel(name); - } - }) - }; - - System.prototype.leave_channel = function(name,send_leave,onKick){ - if(typeof send_leave === "undefined"){ - send_leave = true; - } - - if(typeof onKick === "undefined"){ - onKick = false; - } - - var is_botton_found = false; - var cid = 1;//1 is system brodcast channel. (channel all message some is not in normaly channel get into) - - //vi fjerner knappen fra oversigten ;) - this.getDom("channel_botton").run(function(){ - var bname = this.getObject().getElementsByClassName("channelNameContainer")[0].innerHTML; - if(name == system.trim(bname)){ - cid = this.attr("cid"); - is_botton_found = this.remove(); - } - }); - - if(!is_botton_found){ - alert("Channel not found"); - return; - } - - //vi tømmer cache - this.get_object("cache").empty_cache(name,cid); - this.channelCount--; - //wee got now one less channel wee are in :D - - if(this.is_in_this_channel(name)){ - //vi fjerner nu cache af bruger i denne channel - this.user_in_channel = []; - //vi tømmer først main ;) - this.getDom("main").empty(); - //tømmer bruger over sigten :) - this.getDom("option").run(function(){ - if(this.attr("what") == system.option_name.online){ - this.empty(); - } - }); - } - - if(send_leave){ - //jeg forstår det slet ikke hmm :( - this.new_ajax_query({ - 'message' : '/leave', - 'channel' : this.trim(name) - },'server.php?userBlock=' + this.data.browserBlock+'&sort='+this.data.user.sort+"&li=" + this.get_last_id()); - } - - //og vi finder en ny channel at være i :) - var has_found_new_channel = false; - var change_to_name = null; - var cid = 0; - this.getDom("channel_botton").run(function(){ - change_to_name = this.getObject().getElementsByClassName("channelNameContainer")[0].innerHTML; - cid = this.attr("cid"); - has_found_new_channel = true; - }); - - if(has_found_new_channel){ - this.switch_channel(change_to_name,cid); - }else{ - if(onKick){ - if(name == this.start_channel()){ - this.chat_name = null; - this.stop_chat(); - this.timer = null; - return false;//vi er nu igang med at joine en automatisk kick Hmmmm ikke en god ide :D - } - } - this.chat_name = null;//lige nu er vi jo ikke i en channel! - //this.send_ping('/join '+this.start_channel(),'Bot'); //this is a bad idé :( - } - - }; - - System.prototype.switch_channel = function(name,cid){ - //vi kontrollere at vi ikke allerede er i den (spild af kræfter) - if(this.is_in_this_channel(name)){ - return; - } - - this.chat_name = name; - this.u_num = 0; - - - this.getDom("main").empty(); - this.getDom("option").run(function(){ - if(this.attr("what") == system.option_name.online){ - this.empty(); - } - }); - - - this.re_paint_channel_botton(cid); - - this.user_in_channel = []; - - this.handle_in_message({ - 'message' : this.get_object("cache").get_message_in_channel(cid) - },true); - - return; - - }; - - System.prototype.show_user_menu = function(uid){ - this.getDom("user").run(function(){ - - if(this.getObject().getElementsByClassName("user_menu")[0].style.display == 'block'){ - J(this.getObject().getElementsByClassName("user_menu")[0]).hide(); - return; - } - - if(this.attr("uid") == uid){ - J(this.getObject().getElementsByClassName("user_menu")[0]).show(); - }else{ - J(this.getObject().getElementsByClassName("user_menu")[0]).hide(); - } - }); - }; - - System.prototype.add_user_in_user_list = function(img,nick,uid,inaktiv){ - this.user_in_channel.push(uid); - this.getDom("option").run(function(){ - if(this.attr("what") == system.option_name.online){ - system.u_num++; - var block = "
" - + "
" - + "" - + "
" - + "
" - + (inaktiv == system.data.yesNo.yes ? '[i]' : '')+nick+(inaktiv == system.data.yesNo.yes ? '' : '') - + "
" - + "
" - + "
" - + ""; - if(system.get_my_stat().id == uid){ - block += "" - + "" - + ""; - }else{ - block += "" - + "" - + "" - + "" - + "" - + ""; - } - block += "
" - + system.get_lang().noOption; - + "
"+system.get_lang().ignore+"
"+system.get_lang().unIgnore+"
" - + "
" - + "
"; - - this.append(block); - - return; - } - }); - }; - - System.prototype.sendMessage = function(msg,channel){ - if(typeof channel === "undefined"){ - channel = this.chat_name; - } - - this.new_ajax_query({ - 'message' : msg, - 'channel' : channel - },'server.php?userBlock=' + this.data.browserBlock+'&sort='+this.data.user.sort+"&li=" + this.get_last_id()); - } - - System.prototype.remove_user_from_online_list = function(nick){ - this.getDom("user").run(function(){ - if(system.is_num(nick)){ - if(nick == this.attr("uid")){ - this.remove(); - } - }else{ - var u_nick = this.getObject().getElementsByClassName("u_nick")[0].innerHTML; - if(u_nick == nick){ - this.remove(); - } - } - }); - }; - - System.prototype.is_num = function(string){ - return /^[0-9]*?$/.test(string); - }; - - System.prototype.prepare_start_socket = function () { - if (this.is_socket) { - this.new_ajax_query({ - 'message': '/cookie ' + this.data.cookie, - 'channel': 'Bot' - }); - this.ping_socket(); - } else { - this.is_socket = this.ajax[0].isOpen; - if (!this.is_socket) { - setTimeout(function () { - system.prepare_start_socket(); - }, this.data.timer); - } else { - this.prepare_start_socket(); - } - } - }; - - System.prototype.get_time = function () { - var date = new Date(); - if (typeof this.user_config.time_format === "undefined") { - this.user_config.time_format = "H:i"; - } - - var use = this.user_config.time_format; - - var w_zerro = function (int) { - if (int < 10) { - return "0" + int; - } else { - return int; - } - }; - - var day_of_year = function () { - var now = new Date(); - var start = new Date(now.getFullYear(), 0, 0); - var diff = now - start; - var oneDay = 1000 * 60 * 60 * 24; - var day = Math.floor(diff / oneDay); - return day; - }; - - var week_of_year = function () { - var d = new Date(+d); - d.setHours(0, 0, 0); - d.setDate(d.getDate() + 4 - (d.getDay() || 7)); - var yearStart = new Date(d.getFullYear(), 0, 1); - var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1) / 7); - return weekNo; - }; - - var h = date.getHours(); - - //Day - use = use.replace(/d/g, w_zerro(date.getDate())); - use = use.replace(/D/g, this.get_lang().day_short[date.getDay()]); - use = use.replace(/j/g, date.getDate()); - use = use.replace(/l/g, this.get_lang().day_long[date.getDay()]); - use = use.replace(/N/g, (date.getDay() + 1)); - //s not supportet - use = use.replace(/w/g, date.getDay()); - use = use.replace(/z/g, day_of_year()); - - //Week - use = use.replace(/W/g, week_of_year()); - - //Month - use = use.replace(/F/g, this.get_lang().month_long[date.getMonth()]); - use = use.replace(/m/g, w_zerro((date.getMonth() + 1))); - use = use.replace(/M/g, this.get_lang().months_short[date.getMonth()]); - use = use.replace(/n/g, (date.getMonth() + 1)); - use = use.replace(/t/g, date.getDate()); - - //Year - use = use.replace(/L/g, (((date.getFullYear() % 4 == 0) && (date.getFullYear() % 100 != 0)) || (date.getFullYear() % 400 == 0) ? 1 : 0)); - //o not supportet - use = use.replace(/Y/g, date.getFullYear()); - var fy = new String(date.getFullYear()); - use = use.replace(/y/g, fy.substring(2, 4)); - - //Time - use = use.replace(/a/g, (date.getHours() < 12 ? "am" : "pm")); - use = use.replace(/A/g, (date.getHours() < 12 ? "AM" : "PM")); - use = use.replace(/B/g, date.getMilliseconds()); - use = use.replace(/g/g, (h > 12 ? h - 12 : h)); - use = use.replace(/G/g, date.getHours()); - use = use.replace(/h/g, (h > 12 ? w_zerro((h - 12)) : w_zerro(h))); - use = use.replace(/H/g, w_zerro(date.getHours())); - use = use.replace(/i/g, w_zerro(date.getMinutes())); - use = use.replace(/s/g, w_zerro(date.getSeconds())); - use = use.replace(/u/g, date.getTime()); - - //TimeZone not supportet ;) - - return use; - }; - - System.prototype.setSmylie = function (smy_name, smy_tag, smy_url, smy_reg_tag) { - this.smylie[this.smylie.length] = { - 'smy_name' : smy_name, - 'smy_tag' : smy_tag, - 'smy_url' : smy_url, - 'smy_reg_tag' : smy_reg_tag - }; - }; - - System.prototype.return_smylie_dom = function(){ - var html = ""; - for(var i=0;i"+s[\r\n"; - } - - return html; - }; - - System.prototype.add_smylie_to_string = function(string){ - if(typeof string === "undefined"){ - return this.null; - } - - for(var i=0;i"); - } - return string; - }; - - System.prototype.jsoin_channel_by_click = function(name){ - this.new_ajax_query({ - 'message' : '/join '+name, - 'channel' : this.chat_name - },'server.php?userBlock=' + this.data.browserBlock+'&sort='+this.data.user.sort+"&li=" + this.get_last_id()); - }; - - System.prototype.add_default_item_to_message = function(string){ - - string = string.replace(/\[(img|image)=(.*?)\]/g,function(all,n,url){ - return ""; - }); - - - string = string.replace(/\[url=(.*?)\](.*?)\[\/url\]/g,function(all,url,text){ - return ""+text+""; - }); - - //finely :) - return string.replace(new RegExp("(#[a-z0-9][a-z0-9\-_]*)","ig"),function(find){ - return ""+find+""; - }); - }; - - System.prototype.smy_click = function(id){ - //vi skal du have fat i context i tekst box :) - var context = this.getDom("textbox").context(); - var object = this.getDom("textbox").getObject(); - var index = context.length; - if(object.selectionStart){ - index = object.selectionStart; - } - - var put = { - 'befor' : context.substring(0,index), - 'after' : context.substring(index,context.length) - }; - - this.getDom("textbox").context(put.befor+this.smylie[id]["smy_tag"]+put.after); - - //okay now wee need to focus the text fild :D - object.focus(); - var c = put.befor.length + this.smylie[id]["smy_tag"].length; - if(object.createTextRange){ - var r = object.createTextRange(); - r.move('character',c); - r.select(); - }else{ - object.selectionStart = c; - object.selectionEnd = c; - } - }; - - System.prototype.init_message = function () { - this.set_object("message", new Message(this)); - }; - - System.prototype.set_lang = function () { - this.set_object("lang", LibLang.English); - }; - - System.prototype.get_lang = function () { - return this.get_object("lang"); - }; - - System.prototype.new_status = function () { - this.set_object("status", new Status(this.get_lang())); - }; - - System.prototype.new_ajax = function () { - var id = 0; - if(this.ajax.length <= 50){ - id = this.ajax.length; - } - - this.get_object("status").call(); - - this.ajax[id] = new JAjax({ - 'action': 'server.php?userBlock=' + this.data.browserBlock+'&sort='+this.data.user.sort+"&li=" + this.get_last_id(), - 'method': 'get', - 'error': function (m) { - if(system.get_protokol() == "ajax"){ - system.get_object("message").bot_message(m,0,"red"); - }else{ - system.get_object("message").bot_message(system.get_lang().socket_open_fail, 0,"red","socket_open_fail",{}); - } - system.get_object("status").error(); - }, - 'success': function (json) { - system.handle_in_message(json,false); - if(system.changeStatus){ - system.get_object("status").okay(); - } - - system.changeStatus = true; - }, - 'protokol': this.get_protokol(), - 'host': this.data['socket']['server'], - 'port': this.data['socket']['port'], - 'file' : false, - 'noHeader' : false - }); - return id; - }; - - System.prototype.new_ajax_query = function (post, url) { - - if (this.get_protokol() == "socket") { - if (this.is_socket) { - this.ajax[0].send(post); - } else { - this.ajax[0].enable(); - } - - return; - }else{ - var id = this.new_ajax(); - } - - var block = ""; - - if (typeof post !== "undefined") { - this.ajax[id].changePost(post); - block = "&isPost=true"; - this.ajax[id].changeMethod("post"); - }else{ - this.ajax[id].changeMethod("get"); - } - - if (typeof url !== "undefined") { - this.ajax[id].changeUrl(url+block); - } - - - this.ajax[id].enable(); - }; - - System.prototype.get_protokol = function () { - if (this.data.protocol == 'socket') { - return 'socket'; - } - - return 'ajax'; - }; - - System.prototype.set_object = function (objName, objValue) { - this.object[objName] = objValue; - }; - - System.prototype.get_object = function (objName) { - if (typeof this.object[objName] === "undefined") { - return null; - } - - return this.object[objName]; - }; - - System.prototype.set_background = function (url) { - this.getDom("main").css("backgroundImage", "url('" + url + "')"); - }; - - System.prototype.selectOption = function(obj){ - this.show_option(obj.value); - }; - - System.prototype.show_option = function (w) { - this.getDom("option").run(function () { - if (this.attr("what") == w) { - this.show(); - } else { - this.hide(); - } - }); - }; - - System.prototype.unset_screen = function () { - this.getDom("main").empty(); - this.getDom("channel_botton").remove(); - this.show_option(this.option_name.online); - - }; - - System.prototype.getDom = function (domName) { - if (typeof this.dom[domName] === "undefined") { - return null; - } - - return this.dom[domName]; - }; - - System.prototype.setDom = function () { - this.dom = { - 'channel_list' : J("#channelList"), - 'main' : J("#channelMain"), - 'textbox' : J("#textbox"), - 'setting' : J("#rightContainer"), - 'channel_botton' : J(".chanenlContainer"), - 'option' : J(".option"), - 'sound_botton' : J("#sound"), - 'text_color' : J("#textColor"), - 'avatar' : J("#profilImage"), - 'lang_select' : J("#langSelect"), - 'title' : J("#chattitle"), - 'user' : J(".user"), - 'time' : J("#time"), - 'newInChanMessage' : J("#newInChanMessage"), - 'save' : J("#save"), - 'upload' : J("#upload"), - 'fileName' : J("#fileName"), - 'viewImages' : J("#viewImages"), - 'viewImage' : J("#viewImage") - }; - }; - - System.prototype.init_cache = function () { - this.set_object("cache", new Cache(this)); - }; - - System.prototype.update_config = function(){ - this.getDom("sound_botton").getObject().checked = (this.user_config['sound'] == "true" ? true : false); - - this.getDom("text_color").getOptions(function(value,text,obj){ - if(value == system.user_config['textColor']){ - obj.selected = true; - } - }); - - this.getDom("textbox").css("color",this.user_config['textColor']); - - var secondLang = "English"; - - if(this.langName !== null){ - secondLang = this.langName; - } - - this.set_object("lang",this.setNewLang(this.user_config['lang'],secondLang)); - this.get_object("status").updateSprog(this.get_object("lang")); - this.update_screen_lang(); - this.getDom("lang_select").getOptions(function(value,text,obj){ - if(value == system.langName){ - obj.selected = true; - } - }); - - this.getDom("time").context(this.user_config['time']); - - }; - - /** - * @param string [String] name of lang key - * @param data [Object] object whit data to convert from ;) - */ - System.prototype.convert_lang_string = function(string,data){ - var lang = this.get_lang(); - - if(typeof lang[string] === "undefined"){ - return "Unknown lang key: "+string; - } - - var use = lang[string]; - - for(var i in data){ - use = use.replace(new RegExp("%"+i),data[i]); - } - - return use; - }; - - System.prototype.update_screen_lang = function(){ - J("all").run(function(){ - if(typeof this.attr("langString") !== "undefined" && typeof this.attr("langData") !== "undefined"){ - var l_string = system.get_lang()[this.attr("langString")]; - var l_data = JSON.parse(this.attr("langData")); - - for(var i in l_data){ - l_string = l_string.replace(new RegExp("%"+i,"g"),l_data[i]); - } - - this.context(l_string); - }else if(typeof this.attr("langTitle") !== "undefined" && typeof this.attr("langData") !== "undefined"){ - var l_string = system.get_lang()[this.attr("langTitle")]; - var l_data = JSON.parse(this.attr("langData")); - - for(var i in l_data){ - l_string = l_string.replace(new RegExp("%"+i,"g"),l_data[i]); - } - - this.getObject().title = l_string; - } - }); - }; - - System.prototype.start_channel = function(){ - return this.data['startChannel']; - }; - - System.prototype.stop_chat = function(){ - if(this.get_protokol() != "ajax"){ - return false; - } - clearTimeout(this.timer); - }; - - System.prototype.start_chat = function(isStartChannel){ - if(typeof isStartChannel === "undefined"){ - isStartChannel = false; - } - - if(this.get_protokol() != "ajax"){ - return false; - } - - if(!isStartChannel && this.timer === null){ - this.new_ajax_query({ - 'message' : '/ping', - 'channel' : 'Bot' - }); - }else{ - this.stop_chat(); - } - - this.timer = setTimeout(function(){ - system.new_ajax_query(undefined,'server.php?userBlock=' + system.data.browserBlock+'&sort='+system.data.user.sort+"&li=" + system.get_last_id()) - },this.data.timer); - }; - - System.prototype.open_chat = function(){ - this.getDom("main").css("backgroundImage","none"); - - this.getDom("option").run(function(){ - if(this.attr("what") == system.option_name.smylie){ - this.context(system.return_smylie_dom()); - return; - } - }); - - if(this.get_protokol() == "ajax"){ - this.start_chat(true); - } - }; - - System.prototype.get_channel_botton_color = function(){ - return this.data.channelColor; - }; - - System.prototype.ping_socket = function(){ - setTimeout(function(){ - system.new_ajax_query({ - 'message' : '/ping', - 'channel' : 'Bot' - }); - - system.ping_socket(); - },500000); - }; - - System.prototype.is_in_this_channel = function(name){ - if(this.chat_name == name){ - return true; - } - - return false; - }; - - System.prototype.setNewLang = function(MainLang,SecondLang){ - var l = LibLang; - if(typeof l[MainLang] === "undefined"){ - return this.setNewLang(SecondLang,"English"); - } - - this.langName = MainLang; - return l[MainLang]; - } - - return System; - -})(); \ No newline at end of file diff --git a/lib/client.php b/lib/client.php deleted file mode 100644 index 3b3669c..0000000 --- a/lib/client.php +++ /dev/null @@ -1,111 +0,0 @@ - $value){ - $return[] = urlencode($key)."=".urlencode($value); - } - return implode(";",$return); - } - - return " - 'nick' : '".$userdata['nick']."', - 'id' : '".$userdata['user_id']."', - 'sort' : '".(int)$userdata['user_level']."', - 'mobil' : false, - 'lang' : '".str_replace("/",null,LOCALESET)."' - "; -} - -function jugoloChatClientReturnBotStat(){ - global $config; - - return " - 'name' : '".$config['botUserName']."', - 'color' : '".$config['botUserColor']."', - 'text' : '".$config['botTextColor']."' - "; -} - -function jugoloChatClientReturnBoxColorArray(){ - global $config; - - return "'".$config['bColorOne']."','".$config['bColorToo']."'"; -} - -function jugoloChatClientOnStart(){ - global $userdata; - - $sql = dbquery("SELECT `cid` FROM `".DB_CHATMEMBER."` WHERE `uid`='".(int)$userdata['user_id']."' AND `cid` <> '1'"); - while($row = dbarray($sql)){ - dbquery("INSERT INTO `".DB_CHATMESSAGE."` ( - `uid`, - `cid`, - `isBot`, - `time`, - `message`, - `messageColor`, - `isMsg`, - `msgTo` - ) VALUE ( - '".(int)$userdata['user_id']."', - '".(int)$row['cid']."', - '".No."', - NOW(), - '/exit', - 'red', - '".No."', - '0' - ) - "); - } - - dbquery("DELETE FROM `".DB_CHATMEMBER."` WHERE `uid`='".(int)$userdata['user_id']."' AND `cid`<>'1' AND `ban`='".No."'"); -} - -function jugoloChatCLientAddSmylie(){ - global $smiley_cache; - - $use = null; - for($i=0;$ihead = new mysqli($host,$user,$pass,$data); - if($this->head->connect_error){ - $this->saveError( - $this->head->connect_error, - $this->head->connect_errno - ); - return; - } - } - - function query($sql){ - $result = $this->head->query($sql); - if($this->strstwidth($sql,"SELECT")){ - if(!$result){ - $this->saveError( - $this->head->error, - $this->head->errno, - $sql - ); - } - } - - return new DatabaseResult($sql,$this->head,$result); - } - - function prepare($sql){ - return new DatabasePrepare($sql,$this); - } - - function clean($context){ - return $this->head->escape_string($context); - } - - function saveError($errStr,$errNo,$sql = 'null'){ - $this->isError = true; - $this->errorData[] = array( - 'string' => $errStr, - 'number' => $errNo, - 'sql' => $sql - ); - } - - function getError(){ - $return = "Error in Database:
"; - for($i=0;$ierrorData);$i++){ - $return .= "Error String: ".$this->errorData[$i]['string']."
- Error Number: ".$this->errorData[$i]['number']."
- Sql: ".$this->errorData[$i]['sql']; - } - - return $return; - } - - function strstwidth($tekst,$exp){ - return (strpos($tekst,$exp) === 0); - } - - function lastIndex(){ - return $this->head->insert_id; - } -} - -class DatabaseResult{ - private $sql = null; - private $main = null; - private $result = null; - - function DatabaseResult($sql,$main,$result){ - $this->main = $main; - $this->sql = $sql; - $this->result = $result; - } - - function get(){ - return @$this->result->fetch_assoc(); - } -} - -class DatabasePrepare{ - private $sql = null; - private $main = null; - - function DatabasePrepare($sql,DatabaseHandler $main){ - $this->sql = $sql; - $this->main = $main; - } - - function add($name,$context){ - $this->sql = str_replace( - "{".$name."}", - "'".$this->main->clean($context)."'", - $this->sql - ); - } - - function done(){ - return $this->main->query($this->sql); - } -} \ No newline at end of file diff --git a/lib/define.php b/lib/define.php deleted file mode 100644 index 4a648c4..0000000 --- a/lib/define.php +++ /dev/null @@ -1,3 +0,0 @@ -user = $array; - } - - function add_ignore($uid){ - $this->ignore[] = $uid; - $this->database->query("INSERT INTO `".DB_PREFIX."chat_ignore` - ( - `uid`, - `ignore` - ) VALUES( - '".$this->user['user_id']."', - '".$uid."' - )"); - } - - function remove_ignore($uid){ - if(($key = array_search($uid,$this->get_ignore())) !== false){ - unset($this->ignore[$key]); - $this->database->query("DELETE FROM `".DB_PREFIX."chat_ignore` WHERE `uid`='".(int)$this->user['user_id']."' AND `ignore`='".$uid."'"); - } - } - - function get_ignore($only_cahce = true){ - if(!$only_cahce || empty($this->ignore)){ - $datas = $this->database->query("SELECT `ignore` FROM `".DB_PREFIX."chat_ignore` WHERE `uid`='".(int)$this->user['user_id']."'"); - while($row = $datas->get()){ - $this->ignore[] = $row['ignore']; - } - } - - return $this->ignore; - } - - function Protokol(DatabaseHandler $mysql,Server $server){ - $this->database = $mysql; - $this->main = $server; - } - - function get_channel_list($onlye_cache = true){ - if(!$onlye_cache){ - $datas = $this->database->query("SELECT * FROM `".DB_PREFIX."chat_name`"); - while($row = $datas->get()){ - $data = $row; - unset($data['id']); - $this->channel[$row['id']] = $data; - } - } - - return $this->channel; - } - - function add_to_channel($cid){ - $this->database->query("INSERT INTO `".DB_PREFIX."chat_member` - (`uid`, - `cid`, - `lastActiv`, - `isInAktiv`, - `ban` - ) VALUE ( - '".(int)$this->user['user_id']."', - '".(int)$cid."', - NOW(), - '".No."', - '".No."' - )"); - - $id = $this->database->lastIndex(); - $this->my_channel[$id] = array( - 'uid' => $this->user['user_id'], - 'cid' => $cid, - 'lastActiv' => time(), - 'isInAktiv' => No, - 'ban' => No - ); - } - - function get_my_channel_list($only_cache = true){ - if($only_cache && !empty($this->my_channel)){ - return $this->my_channel; - } - - $this->my_channel = array();//unset all data :) - - $datas = $this->database->query("SELECT cm.*,cn.name - FROM `".DB_PREFIX."chat_member` AS cm - LEFT JOIN `".DB_PREFIX."chat_name` AS cn ON cn.id = cm.cid - WHERE cm.uid='".$this->user['user_id']."'"); - while($row = $datas->get()){ - $data = $row; - unset($data['id']); - $this->my_channel[$row['id']] = $data; - } - - return $this->my_channel; - } - - - function new_channel($name,$title = null,$isSystem = false){ - if($title === null){ - $title = $name; - } - - $data = $this->database->prepare("INSERT INTO `".DB_PREFIX."chat_name` - ( - `name`, - `isPriv`, - `uid`, - `title`, - `setTitle` - ) VALUE ( - {name}, - '".No."', - '0', - {title}, - '".$this->user['user_id']."' - )"); - - $data->add("name",$name); - $data->add("title",$title); - $data->done(); - - if($this->database->isError){ - exit($this->database->getError()); - } - - $id = $this->database->lastIndex(); - $this->channel[$id] = array( - 'name' => $name, - 'isPriv' => No, - 'uid' => 0, - 'title' => $title, - 'setTitle' => $this->user['user_id'], - ); - - $d = $this->channel[$id]; - $d['id'] = $id; - - return $d; - } - - function remove_ban($uid,$cid,$id,$r = true){ - $this->database->query("DELETE FROM `".DB_PREFIX."chat_member` - WHERE `uid`='".(int)$uid."' - AND `cid`='".(int)$cid."'"); - } - - function get_flood($cid){ - if(!$this->main->session("flood")){ - $flood = array(); - $_SESSION['flood'] = array(); - }else - $flood = $this->main->session("flood"); - - if(empty($flood[$cid])){ - return array(); - } - - return $flood[$cid]; - } - - function update_flood($flood,$cid){ - $_SESSION["flood"][$cid] = $flood; - } - - function update_nick($newNick){ - $this->user['nick'] = $newNick; - } - - function getBannetInChannel($cid){ - $data = $this->database->query("SELECT `uid` FROM `".DB_PREFIX."chat_member` WHERE `ban`='".Yes."' AND `cid`='".(int)$cid."'"); - $bannet = array(); - while($row = $data->get()){ - $bannet[] = $row['uid']; - } - - return $bannet; - } - - function banUser($cid,$uid,$banTo,$save = true){ - $this->database->query("UPDATE `".DB_PREFIX."chat_member` SET - `ban`='".Yes."', - `banTo`='".$banTo."' - WHERE `uid`='".$uid."' AND `cid`='".$cid."'"); - } - - function get_channel_by_id($id){ - if(!empty($this->channel[$id])){ - return $this->channel[$id]['name']; - } - - return "Bot"; - } - - function getUserInChannel($cid,$nick){ - $sql = $this->database->prepare("SELECT user.* - FROM `".DB_PREFIX."users` AS user - LEFT JOIN `".DB_PREFIX."chat_member` AS cm ON cm.uid = user.user_id - WHERE cm.cid='".(int)$cid."' - AND user.nick={nick}"); - - $sql->add("nick",$nick); - $user = $sql->done(); - - if($this->database->isError){ - exit($this->database->getError()); - } - - $user = $user->get(); - - if(empty($user)) - return false; - else - return $user; - } - - function getBanId($cid,$uid){ - $sql = $this->database->query("SELECT `id` - FROM `".DB_PREFIX."chat_member` - WHERE `cid`='".$cid."' - AND `uid`='".$uid."' - AND `ban`='".Yes."'"); - $data = $sql->get(); - - if(empty($data)) - return null; - else - return $data; - } - - function kick($cid,$uid){ - $this->database->query("DELETE FROM `".DB_PREFIX."chat_member` - WHERE `cid`='".$cid."' - AND `uid`='".$uid."'"); - } - - function updateConfig($key,$value){ - $sql = $this->database->prepare("UPDATE `".DB_PREFIX."chat_userConfig` SET `value`={value} WHERE `uid`={uid} AND `key`={key}"); - $sql->add("value",$value); - $sql->add("key",$key); - $sql->add("uid",$this->user['user_id']); - $sql->done(); - } - - function userConfig($key,$id = null){ - if($id === null) - $id = $this->user['user_id']; - - if(empty($this->userconfig[$id])) - $this->userconfig[$id] = $this->getUserConfig($id); - - if(empty($this->userconfig[$id][$key]) || !trim($this->userconfig[$id][$key])) - return null; - return $this->userconfig[$id][$key]; - - } - - private function getUserConfig($id){ - $sql = $this->database->query("SELECT * FROM `".DB_PREFIX."chat_userConfig` WHERE `uid`='".(int)$id."'"); - if($this->database->isError){ - exit($this->database->getError()); - } - $return = array(); - while($row = $sql->get()){ - $return[$row['key']] = $row['value']; - } - - return $return; - } - - function getConfig($key){}//not in use. only for websocket (yey); - function update(){}//not in use -} \ No newline at end of file diff --git a/lib/protokol/websocket.php b/lib/protokol/websocket.php deleted file mode 100644 index 57aa99f..0000000 --- a/lib/protokol/websocket.php +++ /dev/null @@ -1,247 +0,0 @@ -main = $server; - $this->mysql = $mysqli; - } - - function get_channel_by_id($id){ - foreach($this->channel AS $cid => $data){ - if($id == $cid){ - return $data['name']; - } - } - - return "Bot"; - } - - function get_ignore($uid = null){ - if($uid === null) - $uid = $this->user['user_id']; - return $this->client[$uid]->ignore; - } - - function add_ignore($uid){ - $this->client[$this->user['user_id']]->ignore[] = $uid; - } - - function remove_ignore($uid){ - if(($key = array_search($uid,$this->get_ignore())) !== false){ - unset($this->client[$this->user['user_id']]->ignore[$key]); - } - } - - function set_user_data($data,$client){ - $this->user = $data; - $this->client[$data['user_id']] = $client; - } - - function get_channel_list($e=false){ - return $this->channel; - } - - function get_my_channel_list(){ - if(empty($this->user['user_id'])){ - return array(); - } - - if(!empty($this->client[$this->user['user_id']]->channel)){ - return $this->client[$this->user['user_id']]->channel; - }else{ - return array(); - } - } - - function add_to_channel($cid){ - $id = count($this->client[$this->user['user_id']]->channel); - $this->client[$this->user['user_id']]->channel[$cid] = array( - 'id' => $id, - 'uid' => $this->user['user_id'], - 'cid' => $cid, - 'lastActiv' => time(), - 'isInAktiv' => No, - 'ban' => No, - 'name' => $this->channelNameCache[$cid] - ); - echo "\r\n".$this->channelNameCache[$cid]."\r\n\r\n"; - } - - function new_channel($name,$title = null,$isSystem = false){ - if($title === null) - $title = $name; - - $id = count($this->channel); - - if($id === 0 && !$isSystem){ - $this->new_channel("null","null channel",true); - $id = count($this->channel); - - } - if($id === 1 && !$isSystem){ - $this->new_channel("Bot","Global bot system",true); - $id = count($this->channel); - } - - $this->channelNameCache[$id] = $name; - - $this->channel[$id] = array( - 'id' => $id, - 'name' => $name, - 'isPriv' => No, - 'uid' => 0, - 'title' => $title, - 'setTitle' => 0, - 'isPm' => No, - ); - - $this->bannet[$id] = array(); - - return $this->channel[$id]; - } - - function turn($uid){ - if(in_array($uid,array_keys($this->client))){ - $this->user = $this->client[$uid]->user; - } - } - - function get_flood($cid){ - if(empty($this->flood[$this->user['user_id']])){ - $this->flood[$this->user['user_id']] = array(); - } - if(empty($this->flood[$this->user['user_id']][$cid])){ - $this->flood[$this->user['user_id']][$cid] = array(); - } - - return $this->flood[$this->user['user_id']][$cid]; - } - - function update_flood($flood,$cid){ - $this->flood[$this->user['user_id']][$cid] = $flood; - } - - function update_nick($newNick){ - $this->client[$this->user['user_id']]->user['nick'] = $newNick; - $this->user['nick'] = $newNick; - } - - function getUserInChannel($cid,$nick){ - foreach($this->client AS $object){ - if(strtolower($object->user['nick']) == strtolower($nick)){ - foreach($object->channel AS $channelID => $data){ - if($channelID == $cid){ - return $object->user; - } - } - } - } - - return false; - } - - function getBannetInChannel($cid){ - if(empty($this->bannet[$cid])) - return array(); - return $this->bannet[$cid]; - } - - function banUser($cid,$uid,$banTo,$save =true){ - $this->bannet[$cid][] = $uid; - $this->client[$uid]->channel[$cid]['ban'] = Yes; - $this->client[$uid]->channel[$cid]['banTo'] = $banTo; - if($save){ - $this->mysql->query("INSERT INTO `".DB_PREFIX."chat_member` ( - `uid`, - `cid`, - `lastActiv`, - `isInAktiv`, - `ban`, - `banTo` - ) VALUES ( - '".(int)$uid."', - '".(int)$cid."', - NOW(), - '".No."', - '".Yes."', - '".$banTo."' - )"); - } - } - - function remove_ban($uid,$cid,$id,$remove = true){ - unset($this->client[$uid]->channel[$cid]); - $i = array_search($uid,$this->bannet[$cid]); - unset($this->bannet[$cid][$i]); - if($remove){ - $this->mysql->query("DELETE FROM `".DB_PREFIX."chat_member` - WHERE `uid`='".$uid."' - AND `cid`='".$cid."'"); - } - } - - function getBanId($c,$u){return null;}//this protokol dosent need this :) - - function kick($cid,$uid){ - if(empty($this->client[$uid]->channel[$cid])){ - return false; - } - - unset($this->client[$uid]->channel[$cid]); - unset($this->client[$uid]->aktiv[$cid]); - return true; - } - - function updateConfig($key,$value){ - $this->client[$this->user['user_id']]->update_user_config($key,$value); - } - - function getConfig($key){ - $config = $this->client[$this->user['user_id']]->user_config; - if(empty($config[$key])) - return null; - else - return $config[$key]; - } - - function update(){ - foreach($this->bannet as $cid => $data){ - for($i=0;$iremove_ban($data[$i],$cid,0,false); - } - } - - $this->bannet = array();//protect against fail. - $sql = $this->mysql->query("SELECT * FROM `".DB_PREFIX."chat_member` WHERE `id`<>'1' AND `ban`='".Yes."'"); - while($row = $sql->get()){ - $this->banUser( - $row['cid'], - $row['uid'], - $row['banTo'], - false - ); - } - } - - function userConfig($key,$id = null){ - $sql = $this->database->query("SELECT * FROM `".DB_PREFIX."chat_userconfig` WHERE `uid`='".(int)$id."'"); - $return = array(); - while($row = $sql->get()){ - $return[$row['key']] = $row['value']; - } - - return $return; - } -} \ No newline at end of file diff --git a/lib/tmp/allow_file.php b/lib/tmp/allow_file.php deleted file mode 100644 index 1c2f338..0000000 --- a/lib/tmp/allow_file.php +++ /dev/null @@ -1,5 +0,0 @@ - $value){ - $return .= "'".$key."' : "; - if(is_array($value)){ - $return .= PHPArrayToJavaScriptObject($value,false).((count($data)-1) == $i ? null : ','); - }else{ - $return .= "'".addslashes($value)."'".((count($data)-1) == $i ? null : ','); - } - $i++; - } - - return $return."}"; -} - -$dir = opendir("./"); -$l = array(); - -while($file = readdir($dir)){ - if(is_dir($file) && ($file != "." && $file != "..")){ - $l[$file] = getLang($file); - } -} - -$cache = "var LibLang = ".PHPArrayToJavaScriptObject($l).";"; - -$obj = fopen("../lib/tmp/lang_js_cache.php","w"); -fwrite($obj,"//this is cache\r\n".$cache); -fclose($obj); - -echo $cache; \ No newline at end of file diff --git a/multi_include.php b/multi_include.php new file mode 100644 index 0000000..e355c87 --- /dev/null +++ b/multi_include.php @@ -0,0 +1,25 @@ +"); -add_to_head(""); -add_to_head(""); -add_to_head(""); -add_to_head(""); -add_to_head(""); -add_to_head(""); -add_to_head(""); -add_to_head(""); - -add_to_head(""); - -function convert_socket_server($server){ - if (!filter_var($server, FILTER_VALIDATE_IP)) { - return gethostbyname($server); - } - - return $server; -} - -//vi laver nu en start på systemet :) -add_to_head(""); - -//vi har brug for at kunne afspille en lyd ;) -echo ""; - -$t = explode(",",$config['textColor']); -$textColor = array(); -for($i=0;$i".$reg[2].""; - } -} - -opentable("Jugolo chat"); -echo "
-
-
-
-
-
- -
-
- -
-
-
-
- -
-
- -
- -
- -
- -
- - - - - - - - - - - - - - - - - - -
- -
- -
- -
-
- -
- - - - - - - - -
- -
-
- -
-
- - -
- -
- - -
-
-
-
-"; \ No newline at end of file diff --git a/page/index.php b/page/index.php deleted file mode 100644 index 5bebbb9..0000000 --- a/page/index.php +++ /dev/null @@ -1 +0,0 @@ -Access deniad \ No newline at end of file diff --git a/pm.php b/pm.php deleted file mode 100644 index 2b790be..0000000 --- a/pm.php +++ /dev/null @@ -1,8 +0,0 @@ -websocket = $websocket; - - $this->loadPages(); - $this->init_db(); - $this->init_system_setting(); - $this->init_lang(); - $this->loadVariabel(); - $this->loadDatabaseConfig(); - $this->init_protokol(); - if($this->protokol->use_session){ - $this->sessionInit(); - } - - $this->channel = $this->protokol->get_channel_list(false); - - if(!$this->websocket){ - $this->userInit(); - } - - if($this->websocket){ - $this->init_websocket(); - }else{ - if("socket" == $this->getConfig("protokol")){ - exit("This is not ajax webserver but WebSocket server!"); - } - } - - //ajax only ;) if it is not ajax it will not work! - if($this->getVariabel("isPost")){ - $this->handlePost(); - }else{ - $this->showMessage(); - } - - if($this->database->isError){ - exit($this->database->getError()); - } - - if(empty($this->json['message'])){ - $this->json['message'] = array(); - } - - exit(json_encode($this->json)); - } - - private function init_websocket(){ - - if(!function_exists("socket_create")){ - exit("Missing socket create!"); - } - - if(($master = socket_create(AF_INET,SOCK_STREAM,SOL_TCP)) === false){ - exit("Denaid to create socket!"); - } - - if(socket_set_option($master,SOL_SOCKET,SO_REUSEADDR,1) === false){ - exit("Deinad to create socket"); - } - - if (!filter_var($this->getConfig("socketServer"), FILTER_VALIDATE_IP)) { - $this->config['socketServer'] = gethostbyname($this->getConfig("socketServer")); - } - - if(@socket_bind( - $master, - $this->getConfig("socketServer"), - $this->getConfig("socketPort") - ) === false){ - exit("Failt to bind socket"); - } - - if(socket_listen($master,20) === false){ - exit("Fail to listen socket"); - } - - $this->add_socket_client($master); - - while($this->websocket){ - $read = $this->client; - $write = $ex = null; - - @socket_select($read,$write,$ex,null); - - foreach($read AS $socket){ - if($socket == $master){ - $client = socket_accept($socket); - if($client < 0){ - echo "Error to accept socket!"; - continue; - }else{ - $this->handle_new_connect($client); - } - continue; - } - - $konto = $this->get_client($socket); - - if(!$konto->my_turn()){ - $this->remove_client($socket); - continue; - } - - $recv = @socket_recv($socket,$buf,1024,0); - if($recv === false || $recv == 0){ - $this->remove_client($socket); - continue; - } - - $message = $konto->unmask($buf); - if(!$message || $message == "undefined"){ - continue; - } - - $this->postData = @json_decode($message,true); - if(@json_last_error() != JSON_ERROR_NONE){ - $this->remove_client($socket); - continue; - } - - - $this->variabel['client'] = $konto; - if($konto->isLogin){ - $this->protokol->turn($konto->user['user_id']); - $this->setLang($this->protokol->getConfig("lang")); - } - $this->re_cache_channel_id($this->postData['channel']); - $this->handlePost(); - - } - } - } - - private function handle_new_connect($new){ - $user = $this->add_socket_client($new); - - $head = array(); - //handshake :) - $lines = explode("\r\n",$user->read()); - for($i=0;$iremove_client($new); - echo "Missing Sec-WebSocket-Key\r\n"; - print_r($head); - return false; - } - - $key = $head['Sec-WebSocket-Key']; - $hkey = base64_encode(sha1($key.'258EAFA5-E914-47DA-95CA-C5AB0DC85B11', true)); - - $uhead = array(); - - $uhead[] = "HTTP/1.1 101 Web Socket Protocol Handshake"; - $uhead[] = "Upgrade: websocket"; - $uhead[] = "Connection: Upgrade"; - $uhead[] = "Sec-WebSocket-Accept: ".$hkey; - - $handshake = implode("\r\n",$uhead)."\r\n\r\n"; - //exit($handshake); - - if(socket_write($new,$handshake,strlen($handshake))===false){ - exit("Handshake fail"); - } - echo "New client connected to server\r\n"; - return null; - } - - private function remove_client($socket){ - $i = array_search($socket,$this->client); - if(empty($i)){ - return false; - } - $this->clientObj[$i]->disconnect(); - $this->clientObj = $this->reset_array_sort($this->clientObj,$i); - $this->client = $this->reset_array_sort($this->client,$i); - echo "Client disconetet\r\n"; - - return true; - } - - private function reset_array_sort($array,$removeId = null){ - $cache = $array; - $array = array(); - for($i=0;$iclient[] = $client; - $this->clientObj[] = $obj = new socket_user_client($client,$this->database); - return $obj; - } - - private function get_client($socket){ - foreach($this->clientObj as $c){ - if($c->socket == $socket){ - return $c; - } - } - - return false; - } - - private function init_lang(){ - $this->setLang($this->get_system_config("locale")); - } - - function setLang($name){ - if(!empty($this->langCache[$name]) && is_array($this->langCache[$name])){ - $this->lang = $this->langCache[$name]; - return;//super :) - } - $locale = array(); - - if($this->websocket) - $langUse = $this->get_base_part()."locale\\".$name."\\server.php"; - else - $langUse = "./locale/".$name."/server.php"; - - - if(file_exists($langUse)){ - include $langUse; - $this->lang = $this->langCache[$name] = $locale; - }else{ - if(!empty($this->langCache['English']) && is_array($this->langCache['English'])){ - $this->lang = $this->langCache['English']; - return; - } - if($this->websocket) - $url = $this->get_base_part()."locale\\English\\server.php"; - else - $url = "./locale/English/server.php"; - include $url; - $this->lang = $this->langCache['English'] = $locale; - } - } - - - private function getLangList(){ - $return = array(); - if($this->websocket) - $dir = $this->get_base_part()."locale\\"; - else - $dir = "locale/"; - - $dirObj = opendir($dir); - while($file = readdir($dirObj)){ - if($file != "." && $file != ".." && is_dir($dir.$file)){ - $return[] = $file; - } - } - - return $return; - } - - //inaktiv sektion - private function handle_inaktiv($row){ - if($row['isInAktiv'] == Yes){ - $this->do_leave($row); - }else{ - $this->do_inaktiv($row); - } - } - - private function do_leave($row){ - $this->sendBotMessage( - $row['cid'], - '/leave', - false, - $row['uid'] - ); - $this->database->query("DELETE FROM `".DB_PREFIX."chat_member` WHERE `id`='".(int)$row['id']."'"); - if($this->database->isError){ - exit($this->database->getError()); - } - $this->sendBotPrivMessage( - 1, - "/leave ".$row['name'], - "red", - $row['uid'] - ); - } - - private function do_inaktiv($row){ - $this->database->query("UPDATE `".DB_PREFIX."chat_member` SET `isInAktiv`='".Yes."' WHERE `id`='".$row['id']."'"); - if($this->database->isError){ - exit($this->database->getError()); - } - - $this->sendBotMessage( - $row['cid'], - "/inaktiv ".$row['nick'],false,$row['uid'] - ); - } - - //message sektion - private function showMessage(){ - //vi sletter nu pong beskeder som er mere end 1 min gammel :) - $this->database->query("DELETE FROM `".DB_PREFIX."chat_message` WHERE `cid`='1' AND `message`='/pong' AND DATE_SUB(time, INTERVAL 1 MINUTE) > NOW()"); - if($this->database->isError){ - exit($this->database->getError()); - } - - //big sql :D - $data = $this->database->query("SELECT tm.id AS id, tm.message AS message, tm.isMsg AS isMsg, tm.msgTo AS msgTo, tm.messageColor AS messageColor, tm.isBot AS isBot, user.nick AS nick, tm.time AS time, tn.id AS cid, tn.name AS channel, cm.id AS cmid, user.user_id AS uid, user.user_avatar AS img, tn.isPriv AS isPriv, tn.uid AS privUid - FROM ".DB_PREFIX."chat_message AS tm - LEFT JOIN ".DB_PREFIX."chat_member AS cm ON tm.cid = cm.cid - LEFT JOIN ".DB_PREFIX."users AS user ON user.user_id = tm.uid - LEFT JOIN ".DB_PREFIX."chat_name AS tn ON tn.id = cm.cid - WHERE cm.uid = '".(int)$this->protokol->user['user_id']."' - AND tm.id > '".(int)$this->getVariabel("last_id")."' - AND cm.ban <> '".Yes."' - ORDER BY tm.id ASC "); - - if($this->database->isError){ - exit($this->database->getError()); - } - - $message = array(); - while($row = $data->get()){ - if($row['message'] == null){ - continue; - } - - if($this->may_show_may_show_message($row)){ - $row['time'] = date("H:i",strtotime($row['time'])); - $message[] = $this->messageMakeSafe($row); - } - } - - - $this->json['message'] = $message; - - $data = $this->database->query("SELECT cm.isInAktiv, cm.id, cm.uid , us.nick, cm.cid, cn.name - FROM `".DB_PREFIX."chat_member` AS cm - LEFT JOIN `".DB_PREFIX."users` AS us ON us.user_id = cm.uid - LEFT JOIN `".DB_PREFIX."chat_name` AS cn ON cn.id=cm.cid - WHERE cm.cid != '1' - AND cm.ban = '".No."' - AND cm.lastActiv < DATE_SUB( now( ) , INTERVAL ".(int)$this->config['inaktiv']." MINUTE ) - AND cm.isInAktiv = '".No."' - OR cm.cid != '1' - AND cm.ban = '".No."' - AND cm.lastActiv < DATE_SUB( now( ) , INTERVAL ".(int)$this->config['leave']." MINUTE ) - AND cm.isInAktiv = '".Yes."'" - ); - - while($row = $data->get()) - $this->handle_inaktiv($row); - } - - private function may_show_may_show_message($data){ - if(in_array($data['uid'],$this->protokol->get_ignore()) && $data['isBot'] == No){ - return false; - } - - if($data['isMsg'] == Yes){ - if( - $data['uid'] != $this->protokol->user['user_id'] - && $data['msgTo'] != $this->protokol->user['user_id'] - ){ - return false; - } - } - - return true; - } - - private function messageMakeSafe($row){ - $row['message'] = $this->remove_bad_words(htmlentities($row['message'])); - $row['time'] = htmlentities($row['time']); - $row['nick'] = htmlentities($row['nick']); - if(empty($row['img'])){ - $row['img'] = "noavatar150.png"; - } - $row['img'] = "../../images/avatars/".$row['img']; - return $row; - } - - private function remove_bad_words($word){ - if($this->sConfig['bad_words_enabled'] != '1'){ - return $word; - } - - $block = explode("\r\n",$this->sConfig["bad_words"]); - for($i=0;$isConfig['bad_word_replace'], $word); - } - - return $word; - } - - private function getUserIdFromNick($nick){ - $sql = $this->database->prepare("SELECT `user_id` FROM `".DB_PREFIX."users` WHERE BINARY `nick`={nick}"); - $sql->add("nick",$nick); - $data = $sql->done(); - if($this->database->isError) - exit("Database error"); - $row = $data->get(); - return (empty($row['user_id']) ? 0 : $row['user_id']); - } - - //channel sektion - - protected function re_cache_channel_id($name){ - $myChannels = $this->protokol->get_my_channel_list(); - $channel = $this->protokol->get_channel_list(); - - //og vi får resultatet hurtigt da MySQL ikke er indblandet :D - - foreach($channel as $cid => $data){ - if($data['name'] == $name){ - //vi har fundet den. nu er spøgsmålet bare om brugeren er medlem i den :) - $this->variabel['cid'] = $this->cid = empty($myChannels[$cid]) ? 1 : $cid; - return $this->cid; - } - } - - $this->variabel['cid'] = $this->cid = 1; - - return $this->cid; - } - - protected function getCidFromChannel($name){ - - foreach($this->protokol->get_my_channel_list(false) as $data){ - if(!empty($data['name']) && $data['name'] == $name){ - $this->variabel['cid'] = $this->cid = $data['cid']; - return $data['cid']; - } - } - - $this->variabel['cid'] = $this->cid = 1; - return 1; - } - - //post sektion - - private function init_get_data(){ - if($this->websocket){ - if(!is_array($this->postData)){ - return $this->remove_client($this->getVariabel("client")->socket); - } - return array_merge($this->postData,array( - 'li' => 0, - )); - }else{ - return array( - 'message' => $this->post("message"), - 'channel' => $this->post("channel"), - 'li' => $this->get("li"), - ); - } - } - - private function handlePost(){ - - $input = $this->init_get_data(); - - //WebSocket has a problem. bannet user can write in the channel soo wee control it now :) - if($this->getVariabel("cid") != 1 && in_array($this->protokol->user['user_id'],$this->protokol->getBannetInChannel($this->getVariabel("cid")))){ - return; - } - - if(preg_match("/^\//", $input['message'])){ - $this->handleCommand(); - if($this->getVariabel("last_id")){ - $this->showMessage(); - } - }else{ - if($this->is_flood($this->getVariabel("cid"))){ - if($input['message']){ - $this->handleMessage($input); - } - - if($input['channel']){ - $this->updateActivInChannel($input['channel']); - } - }else{ - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - "/maxFlood", - 'red' - ); - } - - if($this->getVariabel("last_id")){ - $this->showMessage(); - }else{ - $this->json['message'] = array(); - } - } - } - - private function is_flood($cid){ - $flood = $this->protokol->get_flood($cid); - - - $count = 0; - $new_flood = array(); - for($i=0;$isConfig["flood_interval"]){ - $new_flood[] = time(); - - $this->protokol->update_flood($new_flood,$cid); - return true; - }else{ - return false; - } - } - - private function updateActivInChannel(){ - $data = $this->database->query("SELECT * - FROM `".DB_PREFIX."chat_member` - WHERE `uid`='".(int)$this->protokol->user['user_id']."' - AND `cid`='".(int)$this->getVariabel("cid")."'"); - - if($this->database->isError){ - exit($this->database->getError()); - } - - $row = $data->get(); - - if($row['isInAktiv'] == Yes){ - $this->sendBotMessage($row['cid'], "/notInaktiv ".$this->protokol->user['nick'], 'green'); - } - - $this->database->query("UPDATE `".DB_PREFIX."chat_member` SET `lastActiv`= NOW(), `isInAktiv`='".No."' WHERE `cid`='".(int)$row['cid']."' AND `uid`='".$this->protokol->user['user_id']."'"); - - if($this->database->isError){ - exit($this->database->getError()); - } - } - - private function handleMessage($data){ - if($this->getVariabel("cid") == 1){ - //exit("Can not send to server 1!"); Fail from my side :( user can not send join command if user is not allow to write to bot channel :) - return; - } - - if($this->websocket){ - $this->send_message_to_users($data['message']); - return;//websocket sender direkte til brugerenerne så vi har ikke brug for denne del :) - } - - $datas = $this->database->prepare("INSERT INTO `".DB_PREFIX."chat_message` - ( - `uid`, - `cid`, - `isBot`, - `time`, - `message`, - `messageColor`, - `isMsg`, - `msgTo` - ) VALUE ( - '".(int)$this->protokol->user['user_id']."', - '".(int)$this->getVariabel("cid")."', - '".No."', - NOW(), - {message}, - {tx}, - '".No."', - '0' - )"); - - $datas->add("message",$data['message']); - $datas->add("tx",(string)$this->protokol->userConfig("textColor")); - $datas->done(); - - if($this->database->isError){ - exit($this->database->getError()); - } - } - - private function get_user_id_from_nick($nick){ - $data = $this->database->prepare("SELECT `user_id` FROM `".DB_PREFIX."users` WHERE `nick`={nick}"); - $data->add("nick",$nick); - $result = $data->done(); - if($this->database->isError){ - exit("Database error"); - } - - $row = $result->get(); - - if(!empty($row['user_id'])) - return $row['user_id']; - else - return false; - } - - private function returnCommandName(){ - $data = $this->init_get_data(); - $ex = explode(" ",$data['message']); - return preg_replace("/^\//",null,$ex[0]); - } - - private function handleCommand(){ - switch($this->returnCommandName()){ - case 'cookie': - if(!$this->websocket){ - exit("ERROR"); - } - $input = $this->init_get_data(); - - if(!$this->getVariabel("client")->login(str_replace("/cookie ",null,$input['message']))){ - $this->remove_client($this->getVariabel("client")->socket); - }else{ - $this->getVariabel("client")->user['user_avatar'] = $this->convert_image( - $this->getVariabel("client")->user['user_avatar'] - ); - $this->sendBotPrivMessage(1,"/cookieOkay","green"); - $this->protokol->set_user_data($this->getVariabel("client")->user,$this->getVariabel("client")); - } - break; - case "getStatus": - $this->answer_getStatus(); - break; - case "join": - $this->answer_join(); - break; - case "nick": - $this->answer_nick(); - break; - case 'msg': - $this->answer_msg(); - break; - case "config": - $this->answer_config(); - break; - case 'getOnline': - $this->do_getOnline(); - break; - case 'title': - $this->doTitle(); - break; - case 'exit': - $this->doExit(); - break; - case 'getLang': - $this->answer_getLang(); - break; - case 'leave': - $this->answer_leave(); - break; - case 'kick': - $this->answer_kick(); - break; - case 'bot': - $this->answer_bot(); - break; - case 'ban': - $this->answer_ban(); - break; - case 'unban': - $this->answer_unban(); - break; - case 'ignore': - $this->answer_ignore(); - break; - case 'unIgnore': - $this->answer_uningore(); - break; - case 'ping': - $this->sendBotPrivMessage(1,"/pong","green"); - break; - case 'update': - $this->answer_update(); - break; - case 'getConfig': - $this->sendBotPrivMessage(1,"/config ".$this->getUserConfig()); - break; - case 'clear': - $this->answer_clear(); - break; - case 'file': - $this->answer_file(); - break; - default: - $this->sendBotPrivMessage($this->getCidFromChannel($this->post("channel")), "/commandDenaid"); - break; - } - } - - private function answer_file(){ - //findes filen? - $input = $this->init_get_data(); - if(preg_match("/^\/file\s([0-9]*?)$/",$input['message'],$reg)){ - $sql = $this->database->query("SELECT * FROM `".DB_PREFIX."chat_file` WHERE `id`='".(int)$reg[1]."'"); - $row = $sql->get(); - if(empty($row)){ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/noFile"); - }else{ - $this->sendBotMessage( - $this->getVariabel("cid"), - '/file '.$row['url'] - ); - } - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"), "/commandDenaid"); - } - } - - private function answer_clear(){ - if(!$this->iADMIN() && !$this->iSUPERADMIN()){ - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - "/error ".sprintf($this->lang['accessDenaidKommando'],"/clear") - ); - return; - } - - $this->database->query("DELETE FROM ".DB_PREFIX."chat_message");//on this method wee dont reseat id to 0 but only delete all items - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - $this->lang['clearDone'], - 'green' - ); - } - - private function answer_update(){ - if(!$this->iADMIN() && !$this->iSUPERADMIN()){ - //has nothing to do here idiot :() - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error ".sprintf($this->lang['accessDenaidKommando'],"/update")); - return; - } - - //system config :) - $this->sConfig = array(); - $this->init_system_setting(); - - //database config :) - $this->config = array(); - $this->loadDatabaseConfig(); - - $this->protokol->update(); - - if($this->getConfig("protokol") != "socket" && $this->websocket){ - exit("Server gooing down!"); - } - - //okay now wee can tell user this system is now updatet :) - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - $this->lang['systemUpdatet'], - "green" - ); - } - - private function answer_uningore(){ - $input = $this->init_get_data(); - if(preg_match("/^\/unIgnore\s([a-zA-Z]*?)$/",$input['message'],$reg)){ - if(($uid = $this->get_user_id_from_nick($reg[1])) !== false){ - if(!in_array($uid,$this->protokol->get_ignore())){ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".$this->lang['isNotIgnore']); - return; - } - $this->protokol->remove_ignore($uid); - $this->sendBotPrivMessage($this->getVariabel("cid"),"/unIgnore ".$reg[1],"green"); - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".$this->lang['userNotFound']); - } - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".sprintf($this->lang['invalidCommand'],"unIgnore")); - } - } - - private function answer_ignore(){ - $input = $this->init_get_data(); - if(preg_match("/^\/ignore\s([a-zA-Z]*?)$/",$input['message'],$reg)){ - if(($uid = $this->get_user_id_from_nick($reg[1])) !== false){ - if(in_array($uid,$this->protokol->get_ignore())){ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".$this->lang['isIgnore'],"red"); - return; - } - $this->sendBotPrivMessage($this->getVariabel("cid"),"/ignore ".$reg[1]); - $this->protokol->add_ignore($uid); - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".$this->lang['userNotFound']); - } - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".sprintf($this->lang['invalidCommand'],"ignore")); - } - } - - private function answer_unban(){ - - $input = $this->init_get_data(); - - if(!$this->iADMIN() && !$this->iSUPERADMIN()){ - //has nothing to do here idiot :() - $this->sendBotPrivMessage($this->getCidFromChannel($input['channel']), "/error ".sprintf($this->lang['accessDenaidKommando'],"/unban")); - return; - } - - if(preg_match("/^\/unban\s([a-zA-Z]*?)$/",$input['message'],$reg)){ - $userData = $this->protokol->getUserInChannel($this->getVariabel("cid"),$reg[1]); - if($userData === false){ - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - "/error ".$this->lang['userNotFound'] - ); - return; - } - - if(in_array($userData['user_id'],$this->protokol->getBannetInChannel($this->getVariabel("cid")))){ - $this->protokol->remove_ban( - $userData['user_id'], - $this->getVariabel("cid"), - $this->protokol->getBanId($userData['user_id'],$this->getVariabel("cid")) - ); - $this->sendBotMessage( - $this->getVariabel("cid"), - $input['message'], - "green" - ); - }else{ - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - "/error ".sprintf($this->lang['notBan'],$reg[1]) - ); - } - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".$this->lang['unbanBroken']); - } - } - - private function answer_ban(){ - if(!$this->iADMIN() && !$this->iSUPERADMIN()){ - //has nothing to do here idiot :() - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error ".sprintf($this->lang['accessDenaidKommando'],"/ban")); - return; - } - - $input = $this->init_get_data(); - - if(preg_match("/^\/ban\s([a-zA-Z]*?)\s([0-9]*?)$/",$input['message'],$reg)){ - //vi sætter nu tiden frem til den tidspunkt brugeren ikke længere er bannet ;) - $to = strtotime("+".(int)$reg[2]." minutes",time()); - - $userData = $this->protokol->getUserInChannel( - $this->getVariabel("cid"), - trim($reg[1]) - ); - - if($userData !== false && is_array($userData)){ - //you can not ban you self :) - if($userData['user_id'] === $this->protokol->user['user_id']){ - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - '/error '.$this->lang['banSelf'] - ); - return; - } - - $this->ban( - $input['channel'], - $userData['user_id'], - $to, - trim($reg[1]) - ); - }else{ - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - "/error ".sprintf($this->lang['nickNotFound'],$reg[1]) - ); - } - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".$this->lang['banBroken']); - } - } - - private function answer_bot(){ - - $input = $this->init_get_data(); - - if(!$this->iADMIN() && !$this->iSUPERADMIN()){ - //has nothing to do here idiot :() - $this->sendBotPrivMessage($this->getCidFromChannel($input['channel']), "/error ".sprintf($this->lang['accessDenaidKommando'],"/bot")); - return; - } - - if(preg_match("/^\/bot\s(.*?)$/",$input["message"],$reg)){ - $this->sendBotMessage($this->getVariabel("cid"),$reg[1],($this->websocket ? $this->getVariabel("client")->user_config['textColor'] : $this->userConfig['textColor'])); - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".$this->lang['botBroken']); - } - } - - private function answer_leave(){ - if($this->getVariabel("cid") == 1){ - return; - } - - $this->database->query("DELETE FROM `".DB_PREFIX."chat_member` WHERE `cid`='".(int)$this->getVariabel("cid")."' AND `uid`='".($this->websocket ? $this->getVariabel("client")->user['user_id'] : $this->user['user_id'])."'"); - if($this->database->isError){ - exit($this->database->getError()); - } - //vi skriver til channel at brugeren har forladt channel ;) - $input = $this->init_get_data(); - - if($this->websocket){ - unset($this->getVariabel("client")->channel[$this->getVariabel("cid")]); - unset($this->getVariabel("client")->aktiv[$this->getVariabel("cid")]); - } - - $this->sendBotMessage( - $this->getVariabel("cid"), - "/leave ".$input['channel'], - "red", - $this->protokol->user['user_id'] - ); - } - - private function answer_kick(){ - if(!$this->iADMIN() && !$this->iSUPERADMIN()){ - //has nothing to do here idiot :() - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error ".sprintf($this->lang['accessDenaidKommando'],"/kick")); - return; - } - - $input = $this->init_get_data(); - - if(preg_match("/^\/kick\s([a-zA-Z]*?)\s(.*?)$/",trim($input['message']),$reg)){ - //vi har nu en kick med message - if(($uid = $this->getUserIdFromNick($reg[1])) != 0){ - $this->kick($input['channel'],$reg[2],$uid); - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error ".$this->lang['kickBroken']); - } - }elseif(preg_match("/^\/kick\s([a-zA-Z\s]*?)$/", trim($input['message']),$reg)){ - if(($uid = $this->getUserIdFromNick($reg[1])) != 0){ - $this->kick($input['channel'],null,$uid); - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error ".sprintf($this->lang['nickNotFound'],$reg[1])); - } - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error ".$this->lang['kickBroken']); - } - } - - private function answer_getLang(){ - $this->sendBotPrivMessage(1,"/langList ".implode(",",$this->getLangList())); - } - - private function doExit(){ - - foreach($this->protokol->get_my_channel_list() AS $cid => $data){ - $this->sendBotMessage( - $cid, - "/exit" - ); - } - - if($this->websocket){ - $this->remove_client($this->getVariabel("client")->socket); - }else{ - $this->database->query("DELETE FROM `".DB_PREFIX."chat_member` - WHERE `uid`='".$this->protokol->user['user_id']."' AND `cid`!='1'"); - } - } - - private function doTitle(){ - - if(!$this->iADMIN() && !$this->iSUPERADMIN()){ - //has nothing to do here idiot :() - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error ".sprintf($this->lang['accessDenaidKommando'],"/title")); - return; - } - - $input = $this->init_get_data(); - - if(preg_match("/^\/title\s(.*?)$/",$input['message'],$reg)){ - $sql = $this->database->prepare("UPDATE `".DB_PREFIX."chat_name` - SET `title`={title}, - `setTitle`='".($this->websocket ? (int)$this->getVariabel("client")->user['user_id'] : (int)$this->user['user_id'])."' - WHERE `id`='".(int)$this->getVariabel("cid")."'"); - - $sql->add("title",$reg[1]); - $sql->done(); - - $this->sendBotMessage($this->getVariabel("cid"), $reg[0],"green"); - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error ".$this->lang['titleBroken']); - } - } - - private function do_getOnline(){ - $input = $this->init_get_data(); - if(preg_match("/^\/getOnline\s(.*?)$/", $input["message"],$reg)){ - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - "/online ".implode(" ", $this->getOnline($this->getCidFromChannel($reg[1],true),true)) - ); - }else{ - exit($input['message']); - } - } - - //config - private function answer_config(){ - $input = $this->init_get_data(); - if(preg_match("/^\/config\s\[(.*?)\]\[(.*?)\]$/", $input['message'],$reg)){ - switch(trim($reg[1])){ - case 'time': - case 'sound': - case 'textColor': - case 'lang': - - $this->protokol->updateConfig($reg[1],$reg[2]); - if(trim($reg[1]) == "lang"){ - //this is lang and it is importen wee update it so fast :D - $this->setLang($reg[2]); - } - - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - $this->lang['configUpdatet'], - "green" - ); - - $this->sendBotPrivMessage( - 1, - "/updateConfig ".$reg[1]." ".$reg[2], - 'black' - ); - break; - default: - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error Wrong key: ".$reg[1],"red"); - break; - } - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error ".$this->lang['brokenConfigCommand'], "red"); - } - } - - //msg - private function answer_msg(){ - $cid = $this->getVariabel("cid"); - $input = $this->init_get_data(); - //vi deler stringen op ;) - if(preg_match("/^\/msg\s(.*?)\s(.*?)$/", $input['message'],$reg)){ - //vi ser om vi kan finde en bruger med det nick ;) - $data = $this->database->prepare("SELECT user_id AS id,`nick` FROM `".DB_PREFIX."users` WHERE `nick`={nick}"); - $data->add("nick",$reg[1]); - $row = $data->done()->get(); - if(!empty($row['id'])){ - - if($this->websocket){ - for($i=0;$iclientObj);$i++){ - if($this->clientObj[$i]->isLogin && $this->clientObj[$i]->user['user_id'] == $row['id']){ - $this->clientObj[$i]->msg(array( - 'cid' => $cid, - 'message' => "/msg ".$this->getVariabel("client")->user['nick']." -> ".$this->clientObj[$i]->user['nick'].": ".$reg[2], - 'nick' => $this->getVariabel("client")->user['nick'], - 'channel' => $input['channel'], - 'uid' => $this->getVariabel("client")->user['user_id'], - 'img' => $this->getVariabel("client")->user['user_avatar'] - )); - //vi skal også sende det til afsenderen :) - $this->getVariabel("client")->msg(array( - 'cid' => $cid, - 'message' => "/msg ".$this->getVariabel("client")->user['nick']." -> ".$this->clientObj[$i]->user['nick'].": ".$reg[2], - 'nick' => $this->getVariabel("client")->user['nick'], - 'channel' => $input['channel'], - 'uid' => $this->getVariabel("client")->user['user_id'], - 'img' => $this->getVariabel("client")->user['user_avatar'] - )); - return; - } - } - - $this->sendBotPrivMessage($cid, "/error ".sprintf($this->lang['noNick'], $reg[1]),"red"); - return; - } - - $data = $this->database->prepare("INSERT INTO `".DB_PREFIX."chat_message` - ( - `uid`, - `cid`, - `isBot`, - `time`, - `message`, - `messageColor`, - `isMsg`, - `msgTo` - ) VALUE ( - '".(int)$this->user['user_id']."', - '".(int)$cid."', - '".No."', - NOW(), - {message}, - 'yellow', - '".Yes."', - '".(int)$row['id']."' - )"); - - $data->add("message","/msg ".$this->protokol->user['nick']." -> ".$row['nick'].": ".$reg[2]); - $data->done(); - }else{ - $this->sendBotPrivMessage($cid, "/error ".sprintf($this->lang['noNick'], $reg[1]),"red"); - } - }else{ - $this->sendBotPrivMessage($cid, "/error broken /msg","red"); - } - } - - //nick - private function answer_nick(){ - $input = $this->init_get_data(); - if(preg_match("/\/nick\s([a-zA-Z0-9]*?)$/", $input['message'],$reg)){ - if(!$this->nickKontrol($reg[1])){ - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error ".$this->lang['nickTaken'], "red"); - return; - } - - if(($code = $this->is_length_okay($reg[1],1,$this->getConfig("maxNickLengt"))) !== true){ - if($code == self::text_min){ - - }elseif($code == self::text_max){ - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - '/error '.$this->lang['maxNick'], - 'red' - ); - } - }else{ - //wee control if user try to change nick to his nick o.O - if($this->protokol->user['nick'] == $reg[1]){ - $this->sendBotPrivMessage( - $this->getVariabel("cid"), - '/error '.sprintf($this->lang['nickIsYour'],$this->protokol->user['nick']), - 'red' - ); - return; - } - $oldNick = $this->protokol->user['nick']; - $data = $this->database->prepare("UPDATE `".DB_PREFIX."users` SET `nick`={nick} WHERE `user_id`='".$this->protokol->user['user_id']."'"); - $data->add("nick",$reg[1]); - $data->done(); - $this->protokol->update_nick($reg[1]); - if($this->websocket){ - foreach($this->getVariabel("client")->channel as $id => $name){ - $this->sendBotMessage( - $id, - '/nick '.$oldNick, - 'green' - ); - } - }else{ - $data = $this->database->query("SELECT `cid` FROM `".DB_PREFIX."chat_member` WHERE `uid`='".$this->protokol->user['user_id']."' AND `cid`<>'1'"); - while($row = $data->get()){ - $this->sendBotMessage($row['cid'], "/nick ".$oldNick,"green"); - } - } - } - }else{ - $this->json['isOkay'] = "false"; - $this->sendBotPrivMessage($this->getVariabel("cid"), "/error ".$this->lang['nickBroken'], "red"); - } - } - - //join - - private function isMemberOfChannel($name){ - foreach($this->protokol->get_my_channel_list(false) as $data){ - if(!empty($data['name']) && $data['name'] == $name){ - return true; - } - } - - return false; - } - - private function isChannelExists($name){ - foreach($this->protokol->get_channel_list() as $cid => $data){ - if($data['name'] == $name){ - return array_merge($data,array('id' => $cid)); - } - } - - return false; - } - - private function getCannelIDFromChannelName($name){ - foreach($this->protokol->get_channel_list() as $cid => $data){ - if($data['name'] == $name){ - return $cid; - } - } - - return 1; - } - - private function answer_join(){ - $input = $this->init_get_data(); - if(preg_match("/^\/join #([a-zA-Z0-9]*?)$/", $input['message'], $reg)){ - if(!$this->parseJoinChannelName($reg[1])){ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".$this->lang['invalidJoin']); - return; - } - $channelName = "#".$reg[1]; - - if($this->isMemberOfChannel($channelName)){ - //vi skal nu se om vi er bannet :) - if(!in_array($this->protokol->user['user_id'],$this->protokol->getBannetInChannel($this->getCannelIDFromChannelName($channelName)))){ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".sprintf($this->lang['isMember'],$channelName)); - return; - }else{ - //brugeren er bannet :) - if(!$this->allowJoinInBannetChannel($this->getCannelIDFromChannelName($channelName))){ - $this->sendBotMessage( - 1, - "/bannet ".$channelName, - "red" - ); - return; - } - } - } - - if($data = $this->isChannelExists($channelName)){ - $this->join_user_in_channel($data); - }else{ - $data = $this->joinUserInNewChannel($channelName); - } - - $this->sendBotPrivMessage((int)$data['id'], "/title ".$data['title'],"green",null,0); - - }else{ - $this->sendBotPrivMessage($this->getVariabel("cid"),"/error ".$this->lang['invalidJoin']); - } - } - - private function allowJoinInBannetChannel($cid){ - $sql = $this->database->query("SELECT * FROM `".DB_PREFIX."chat_member` WHERE `cid`='".(int)$cid."' AND `uid`='".$this->protokol->user['user_id']."'"); - - if($this->database->isError){ - exit($this->database->getError()); - } - - $result = $sql->get(); - - if(time() > $result['banTo']){ - $this->protokol->remove_ban( - $result['uid'], - $result['cid'], - 0 - ); - return true; - } - - return false; - } - - private function join_user_in_channel($data){ - $this->protokol->add_to_channel($data['id']); - $this->sendBotMessage($data['id'],"/join","green"); - $this->sendBotPrivMessage(1,"/join ".$data['name']); - return $data; - } - - private function parseJoinChannelName($name){ - - if($this->sConfig['bad_words_enabled'] != '1'){ - return true; - } - - //is ther any bad word?? - $sp = explode("\r\n",$this->sConfig['bad_words']); - for($i=0;$iprotokol->new_channel($channel); - $this->channel = $this->protokol->get_channel_list(); - $this->protokol->add_to_channel($data['id']); - - $this->sendBotMessage($data['id'],"/join","green"); - $this->sendBotPrivMessage(1,"/join ".$channel); - - //join user ;) - return $data; - } - - private function getOnline($id,$isCommand = false){ - $name = array(); - if($this->websocket){ - for($i=0;$iclientObj);$i++){ - $client = $this->clientObj[$i]; - if($client->isLogin && !empty($client->channel[$id])){ - if($isCommand){ - $name[] = $client->user['user_id']."|".$client->user['nick']."|".$client->user['user_avatar']."|".No; - }else{ - $name[] = array( - $client->user['user_id'], - $client->user['nick'], - $this->convert_image($client->user['user_avatar']), - No - ); - } - } - } - }else{ - $data = $this->database->query("SELECT user.nick AS nick, user.user_id AS id, user.user_avatar AS img, cm.isInAktiv AS isInAktiv - FROM ".DB_PREFIX."users AS user - LEFT JOIN ".DB_PREFIX."chat_member AS cm ON user.user_id = cm.uid - WHERE cm.cid='".(int)$id."' AND cm.ban <> '".Yes."'"); - - while($row = $data->get()){ - if($isCommand){ - $name[] = $row['id']."|".$row['nick']."|".$this->convert_image($row['img'])."|".$row['isInAktiv']; - }else{ - $name[] = array($row['id'],$row['nick'],$this->convert_image($row['img']),$row['isInAktiv']); - } - } - } - return $name; - } - - //getStatus - private function answer_getStatus(){ - $this->sendBotPrivMessage(1,"/getStatus you are user"); - $this->sendBotPrivMessage($this->getVariabel("cid"),"/profilImage ".$this->convert_image( - $this->protokol->user['user_avatar'] - )); - } - - //nick control - - private function nickKontrol($nick){ - $data = $this->database->prepare("SELECT `user_id` FROM `".DB_PREFIX."users` WHERE `user_name`={nick} AND `user_id`!='".$this->protokol->user['user_id']."' OR `nick`={nick} AND `user_id`!='".$this->protokol->user['user_id']."'"); - $data->add("nick",$nick); - $row = $data->done()->get(); - return (empty($row['user_id']) ? true : false); - } - - //user config - private function getUserConfig(){ - $return = array(); - - $data = $this->database->query("SELECT * - FROM `".DB_PREFIX."chat_userConfig` - WHERE `uid`='".$this->protokol->user['user_id']."'"); - - while($row = $data->get()){ - $return[] = $row['key']."=".$row['value']; - } - - return implode(";",$return); - } - - //load sektion - - private function get_base_part($numBack = 0){ - if($this->basepart !== null){ - return $this->basepart; - } - - $file = __FILE__; - //remove server.php ;) - $file = preg_replace("/server\.php$/",null,$file); - - if($numBack !== 0){ - $block = explode("\\",$file); - - for($i=0;$i<$numBack;$i++){ - unset($block[count($block)-1]); - } - - $file = implode("\\",$block)."\\"; - } - - return $file; - } - - private function init_protokol(){ - if($this->getConfig("protokol") == "socket"){ - include $this->get_base_part()."lib\\protokol\\websocket.php"; - }else{ - include ("lib/protokol/ajax.php"); - } - $this->protokol = new Protokol($this->database,$this); - } - - private function init_system_setting(){ - $data = $this->database->query("SELECT * FROM `".DB_PREFIX."settings"."`"); - while($row = $data->get()){ - $this->sConfig[$row['settings_name']] = $row['settings_value']; - } - } - - private function get_system_config($name){ - if(empty($this->sConfig[$name])){ - return null; - } - - return $this->sConfig[$name]; - } - - private function init_db(){ - $this->database = new DatabaseHandler( - $this->getVariabel("db_host"), - $this->getVariabel("db_user"), - $this->getVariabel("db_pass"), - $this->getVariabel("db_data") - ); - - if($this->database->isError){ - exit($this->database->getError()); - } - - unset($this->variabel['db_host']); - unset($this->variabel['db_user']); - unset($this->variabel['db_pass']); - unset($this->variabel['db_data']); - } - - private function loadPages(){ - if($this->websocket){ - $load = array( - $this->get_base_part()."lib\\define.php", - $this->get_base_part()."lib\\db.php", - $this->get_base_part()."lib\\protokol\\Protokol.php", - $this->get_base_part()."lib\\db\\mysqli.php" - ); - }else{ - $load = array( - 'lib/define.php', - 'lib/db.php', - 'lib/protokol/Protokol.php', - 'lib/db/mysqli.php' - ); - } - - for($i=0;$iwebsocket) - include($this->get_base_part(3)."config.php"); - else - include("../../config.php"); - $this->variabel['db_host'] = $db_host; - $this->variabel['db_user'] = $db_user; - $this->variabel['db_pass'] = $db_pass; - $this->variabel['db_data'] = $db_name; - } - - //user sektion - private function userInit(){ - $this->initUser(); - $this->loadUserConfig(); - $this->setLang($this->userConfig['lang']); - $this->variabel["cid"] = $this->post("channel") ? $this->getCidFromChannel($this->post("channel")) : 1; - } - - private function convert_image($img){ - if(empty($img) || !trim($img)){ - $img = "../../images/avatars/noavatar100.png"; - }else{ - $img = "../../images/avatars/".$img; - } - - return $img; - } - - private function initUser(){ - if($this->login()){ - //do nothing :) - }else{ - $this->json['location'] = "../../index.php?error=sessiong"; - exit(json_encode($this->json)); - } - } - - private function get_nick_from_user_id($uid){ - if($this->websocket){ - foreach($this->clientObj AS $clientOBJ){ - if($clientOBJ->isLogin && $clientOBJ->user['user_id'] == $uid){ - return $clientOBJ->user['nick']; - } - } - - return null; - } - return null; - } - - private function loadUserConfig(){ - $sql = $this->database->query("SELECT * FROM `".DB_PREFIX."chat_userConfig` WHERE `uid`='".($this->websocket ? $this->getVariabel("client")->user['id'] : $this->user['user_id'])."'"); - while($row = $sql->get()){ - $this->userConfig[$row['key']] = $row['value']; - } - } - - //variabel sektion - - private function getVariabel($key){ - if(empty($this->variabel[$key])){ - return null; - }else{ - if(is_object($this->variabel[$key])){ - return $this->variabel[$key]; - } - if(!is_array($this->variabel[$key]) && !trim($this->variabel[$key])){ - return null; - } - - } - - return $this->variabel[$key]; - } - - private function loadVariabel(){ - $this->variabel['isPost'] = $this->get("isPost") ? true : false; - $this->variabel['last_id'] = $this->get('li') ? (int)$this->get('li') : 0; - } - - private function loadDatabaseConfig(){ - $data = $this->database->query("SELECT * FROM `".DB_PREFIX."settings_inf` WHERE `settings_inf`='chat'"); - while($row = $data->get()){ - $this->config[$row['settings_name']] = $row['settings_value']; - } - } - - private function getConfig($key){ - if(empty($this->config[$key])){ - return null; - } - - return $this->config[$key]; - } - - //session sektion - private function sessionInit(){ - - //wee kontrol if header is sendt :) - if(headers_sent()){ - exit("Header is allray sendt!"); - } - - if(!$this->isSessionStarted()){ - $this->startSession(); - } - } - - private function ip(){ - return $_SERVER['REMOTE_ADDR']; - } - - private function login(){ - - if(empty($_COOKIE[COOKIE_PREFIX."user"])){ - return false; - } - - $ucd = explode(".",$_COOKIE[COOKIE_PREFIX."user"]); - - $row = $this->database->query("SELECT * FROM `".DB_PREFIX."users` WHERE - `user_id`='".(empty($ucd[0]) ? '0' : (int)$ucd[0])."' - AND `user_status`='0' - AND `user_actiontime`='0'")->get(); - if($this->database->isError){ - exit("Database error"); - } - - if(empty($row)){ - return false; - } - - if($row['user_ip'] != $this->ip()){ - return false; - } - - $this->protokol->set_user_data($row,null); - $this->user = $row; - return true; - } - - private function startSession(){ - session_start(); - } - - private function isSessionStarted(){ - return (session_id() != ''); - } - - private function getSessionId(){ - return session_id(); - } - - //header sektion (post get session) - - private function get($key){ - if(empty($_GET[$key]) || !trim($_GET[$key])){ - return null; - } - - return $_GET[$key]; - } - - private function post($key){ - if(empty($_POST[$key]) || !trim($_POST[$key])){ - return null; - } - - return $_POST[$key]; - } - - public function session($name){ - if(empty($_SESSION[$name]) || !is_array($_SESSION[$name]) && !trim($_SESSION[$name])){ - return null; - } - - return $_SESSION[$name]; - } - - //send message - - private function send_message_to_users($message){ - if($this->websocket){ - - $input = $this->init_get_data(); - - $this->display( - $input['channel'], - $this->getVariabel('client')->user['nick'], - $message - ); - - for($i=0;$iclientObj);$i++){ - $client = $this->clientObj[$i]; - if(!$client->isLogin){ - continue; - } - - if(!empty($client->channel[$this->getVariabel("cid")]) && !in_array($this->protokol->user['user_id'],$this->protokol->get_ignore($client->user['user_id']))){ - $client->message(array( - 'cid' => $this->getVariabel("cid"), - 'message' => $this->remove_bad_words($message), - 'color' => $this->getVariabel("client")->user_config['textColor'], - 'uid' => $this->getVariabel("client")->user['user_id'], - 'nick' => $this->getVariabel("client")->user['nick'], - 'channel' => $this->protokol->get_channel_by_id($this->getVariabel("cid")), - 'img' => $this->getVariabel("client")->user['user_avatar'] - )); - } - } - } - } - - private function sendBotMessage($cid,$message,$color = false, $uid = false){ - if($this->websocket){ - $input = $this->init_get_data(); - $this->display( - $input['channel'], - 'Bot', - $message - ); - for($i=0;$iclientObj);$i++){ - $client = $this->clientObj[$i]; - if(!$client->isLogin){ - continue; - } - if(!empty($client->channel[$cid])){ - $client->bot_message(array( - 'cid' => $cid, - 'message' => $message, - 'color' => ($color === false ? $this->getConfig("botTextColor") : $color), - 'uid' => $uid !== false ? $uid : $this->getVariabel("client")->user['user_id'], - 'nick' => $uid !== false ? $this->get_nick_from_user_id($uid) : $this->getVariabel("client")->user['nick'], - 'channel' => $this->protokol->get_channel_by_id($cid), - 'img' => $this->getVariabel("client")->user['user_avatar'] - )); - } - } - return; - } - - if(!$uid){ - $uid = $this->user['user_id']; - } - - if($color === false){ - $color = $this->getConfig("botTextColor"); - } - - $data = $this->database->prepare("INSERT INTO `".DB_PREFIX."chat_message` - ( - `uid`, - `cid`, - `isBot`, - `time`, - `message`, - `messageColor`, - `isMsg`, - `msgTo` - ) VALUE ( - '".(int)$uid."', - '".(int)$cid."', - '".Yes."', - NOW(), - {message}, - {color}, - '".No."', - '0' - )"); - - $data->add("message",$message); - $data->add("color",$color); - $data->done(); - } - - private function sendBotPrivMessage($cid,$message,$color = false,$uid=null,$my=null){ - - if($this->websocket){ - $this->display( - ($cid === 1 ? 'Globel' : $this->protokol->get_channel_by_id($cid)), - 'Bot', - $message - ); - for($i=0;$iclientObj);$i++){ - $client = $this->clientObj[$i]; - if(!$client->isLogin){ - continue; - } - $m = ($uid === null ? $this->getVariabel("client")->user['user_id'] : $uid); - if(!empty($client->channel[$cid]) || $cid == 1){ - if($m==$client->user['user_id']){ - $client->bot_message(array( - 'cid' => $cid, - 'message' => $message, - 'color' => ($color ? $color : 'yellow'), - 'uid' => ($my === null ? $this->getVariabel("client")->user['user_id'] : $my), - 'nick' => $this->getVariabel("client")->user['nick'], - 'channel' => $this->protokol->get_channel_by_id($cid), - 'img' => $this->getVariabel("client")->user['user_avatar'], - )); - } - } - } - return; - } - - $data = $this->database->prepare("INSERT INTO `".DB_PREFIX."chat_message` - ( - `uid`, - `cid`, - `isBot`, - `time`, - `message`, - `messageColor`, - `isMsg`, - `msgTo` - ) VALUE ( - '".(int)($my === null ? $this->user['user_id'] : $my)."', - '".(int)$cid."', - '".Yes."', - NOW(), - {message}, - {color}, - '".Yes."', - '".(int)($uid === null ? $this->user['user_id'] : $uid)."' - )"); - - $data->add("message",$message); - $data->add("color",($color ? $color : 'yellow')); - $data->done(); - - if($this->database->isError) - exit($this->database->getError()); - } - - private function ban($channel,$uid,$to,$nick){ - $cid = $this->getCidFromChannel($channel,false); - $this->sendBotPrivMessage(1,"/ban ".$channel,"red",$uid,0); - - //Both Ajax and WebSocket need this (Websocket when admin write /update) - $this->database->query("UPDATE `".DB_PREFIX."chat_member` SET `ban`='".Yes."', `banTo`='".(int)$to."' WHERE `uid`='".(int)$uid."' AND `cid`='".(int)$cid."'"); - - - $this->protokol->banUser($cid,$uid,$to); - $this->sendBotMessage($cid,"/ban ".$nick,"red"); - } - - //Yes my dear :D - private function kick($channel,$message = null,$uid = 0, $sendMessage = true){ - if($uid === 0){ - $uid = $this->protokol->user['user_id']; - } - - if(!is_numeric($channel)){ - $cid = $this->getCidFromChannel($channel,false); - }else{ - $cid = (int)$channel; - } - - if($cid == 1){ - return; - } - - if($sendMessage){ - $this->sendBotPrivMessage( - 1, - "/kick ".$channel.($message !== null ? ' '.$message : null), - "red", - $uid, - $uid//kun for denne bruger :D - ); - } - - $this->protokol->kick( - $cid, - $uid - ); - - if($sendMessage){ - $this->sendBotMessage($cid, "/kick".($message !== null ? " ".$message : null),"red",$uid); - } - } - - private function iADMIN(){ - if($this->protokol->user['user_level'] >= 102) - return true; - else - return false; - } - - private function iSUPERADMIN(){ - if($this->protokol->user['user_level'] == 103) - return true; - else - return false; - } - - private function display($channel,$nick,$msg){ - echo "[".$channel."] ".date("H:i")." ".$nick." ".$msg; - - echo "\r\n"; - } - - private function is_length_okay($text, $min=0,$max=1000){ - if(strlen($text) < $min){ - return self::text_min; - } - - if(strlen($text) > $max){ - return self::text_max; - } - - return true; - } - } - -$server = new Server((empty($socket) ? false : true)); \ No newline at end of file diff --git a/socket.php b/socket.php deleted file mode 100644 index 94a4543..0000000 --- a/socket.php +++ /dev/null @@ -1,304 +0,0 @@ - 0); - public $user_config = array(); - public $channel = array('1' => array( - 'id' => 1, - 'uid' => 0, - 'cid' => 1, - 'lastActiv' => 0, - 'isInAktiv' => No, - 'ban' => No, - 'banTo' => 0, - )); - private $data = array(); - public $ip = null; - public $leave_chan = null; - public $isLogin = false; - private $cookie = false; - public $aktiv = array(); - public $ignore = array(); - private $mysql = array(); - - function kick($cid,$isBan = false){ - if(!empty($this->channel[$cid])){ - if(!$isBan) - unset($this->channel[$cid]); - } - } - - function ban($cid){ - $this->kick($cid,true); - } - - function socket_user_client($socket, DatabaseHandler $mysql){ - $this->socket = $socket; - $this->mysql = $mysql; - } - - function update_my_nick($newNick){ - $this->user['nick'] = $newNick; - } - - function my_turn(){ - - if(!$this->isLogin){ - return true; - } - - if($this->user['user_ip'] != $this->ip()){ - return false; - } - - return true; - } - - function login($cookie){ - $this->cookie = $this->parseCookie($cookie); - - if(!$this->cookie(COOKIE_PREFIX."user")){ - return false; - } - - $user_ip = $this->ip(); - $user_cookie = $this->cookie(COOKIE_PREFIX."user"); - //vi spliter den ad ;) - $user_cookie_data = explode(".",$user_cookie); - - $sql = $this->mysql->query("SELECT * FROM `".DB_PREFIX."users` WHERE - `user_id`='".(empty($user_cookie_data[0]) ? '0' : (int)$user_cookie_data[0])."' - AND `user_status`='0' - AND `user_actiontime`='0'"); - $row = $sql->get(); - - if(empty($row)){ - echo "empty row"; - return false; - } - - if($row['user_ip'] != $user_ip){ - echo "Fandt bruger men ip passer ikke\r\nIp var '".$user_ip."'\r\n"; - return false; - } - - echo "User is now login: ".$row['nick']."\r\n"; - $this->isLogin = true; - $this->user = $row; - - $this->channel[1]['uid'] = $this->user['user_id']; - - $this->get_user_config(); - - return true; - } - - function read($length = 1024){ - return socket_read($this->socket, $length); - } - - function write($msg,$ishandshake = false,$mask = true){ - if(!$this->isLogin && !$ishandshake){ - echo "Prøvede at skrive til en som ikke er logget ind "; - return false; - } - - //vi kontrollere nu at brugeren ikke er bannet i denne channel :) - if(empty($this->channel[$msg['message'][0]['cid']]) || $this->channel[$msg['message'][0]['cid']]['ban'] == Yes) - return false; - - $msg['message'][0]['message'] = htmlentities($msg['message'][0]['message']); - $msg = json_encode($msg); - - if($mask){ - $msg = $this->mask($msg); - } - - socket_write($this->socket,$msg,strlen($msg)); - return true; - } - - function ip(){ - if(!empty($this->data['ip'])){ - return $this->data['ip']; - } - - socket_getpeername($this->socket,$ip); - $this->data['ip'] = $ip; - return $this->data['ip']; - } - - function disconnect(){ - socket_close($this->socket); - } - - function get(){ - $respons = socket_recv($this->socket, $buf, 1024, 0); - - if($respons >= 1){ - return false; - } - - return $this->unmask($buf); - } - - function message($data){ - Server::$message_id++; - $this->write(array( - 'message' => array( - array( - 'id' => Server::$message_id, - 'message' => $data['message'], - 'isMsg' => No, - 'msgTo' => 0, - 'messageColor' => $data['color'], - 'isBot' => No, - 'nick' => $data['nick'], - 'time' => time(), - 'cid' => $data['cid'], - 'channel' => $data['channel'], - 'cmid' => 0, - 'uid' => $data['uid'], - 'img' => $data['img'], - 'isPriv' => No, - 'privUid' => 0 - ), - ), - )); - } - - function msg($data){ - Server::$message_id++; - if(!$this->isLogin){ - echo "User is not login !\r\n"; - return; - } - $this->write(array( - 'message' => array( - array( - 'id' => Server::$message_id, - 'message' => $data['message'], - 'isMsg' => Yes, - 'msgTo' => $this->user['user_id'], - 'messageColor' => 'yellow', - 'isBot' => No, - 'nick' => $data['nick'], - 'time' => time(), - 'cid' => $data['cid'], - 'channel' => $data['channel'], - 'cmid' => 0, - 'uid' => $data['uid'], - 'img' => $data['img'], - 'isPriv' => No, - 'privUid' => 0 - ) - ) - )); - //message is now sendt ;) - } - - function bot_message($data){ - Server::$message_id++; - $this->write(array( - 'message' => array( - array( - 'id' => Server::$message_id, - 'message' => $data['message'], - 'isMsg' => No, - 'msgTo' => 0, - 'messageColor' => $data['color'], - 'isBot' => Yes, - 'nick' => $data['nick'], - 'time' => time(), - 'cid' => $data['cid'], - 'channel' => $data['channel'], - 'cmid' => 0, - 'uid' => $data['uid'], - 'img' => $data['img'], - 'isPriv' => No, - 'privUid' => 0, - ), - ), - )); - } - - function unmask($text) { - $length = ord($text[1]) & 127; - if($length == 126) { - $masks = substr($text, 4, 4); - $data = substr($text, 8); - }elseif($length == 127) { - $masks = substr($text, 10, 4); - $data = substr($text, 14); - }else { - $masks = substr($text, 2, 4); - $data = substr($text, 6); - } - $text = ""; - for ($i = 0; $i < strlen($data); ++$i) { - $text .= $data[$i] ^ $masks[$i%4]; - } - return $text; - } - - function update_user_config($key,$value){ - $this->user_config[$key] = $value; - } - - private function get_user_config(){ - $sql = $this->mysql->query("SELECT * FROM `".DB_PREFIX."chat_userConfig` WHERE `uid`='".$this->user['user_id']."'"); - while($row = $sql->get()){ - $this->user_config[$row['key']] = $row['value']; - } - - return $this->user_config; - } - - private function cookie($name){ - if(empty($this->cookie[$name]) || !trim($this->cookie[$name])){ - return null; - } - - return $this->cookie[$name]; - } - - private function parseCookie($string){ - $block = explode(";",$string); - $return = array(); - for($i=0;$i> 8; - $frame[3] = $data_length & 0xFF; - } - - for($i=0;$i false, + 'host' => null, + 'port' => null, + 'config' => [ + 'startChannel' => '#start' + ] +); + +if(file_exists("include/websocket.txt")){ + $data = unserialize(file_get_contents("include/websocket.txt")); + $json = [ + 'isWebSocket' => true, + 'host' => $data['host'], + 'port' => $data['port'], + 'config' => $json["config"] + ]; +} + +init_ajax(); +exit(json_encode($json)); \ No newline at end of file diff --git a/upload.php b/upload.php deleted file mode 100644 index e3f06b4..0000000 --- a/upload.php +++ /dev/null @@ -1,52 +0,0 @@ -