From 2bce82c73e894e3f2fb52c2b0e21ae56ddee5c91 Mon Sep 17 00:00:00 2001 From: hide_d Date: Fri, 6 Apr 2018 19:03:35 +0900 Subject: [PATCH] =?UTF-8?q?PSR=EC=97=90=20=EB=A7=9E=EA=B2=8C=20=EC=88=98?= =?UTF-8?q?=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- d_setting/RootDB.orig.php | 1 + hwe/d_setting/DB.orig.php | 1 + hwe/func_gamerule.php | 4 +- index.php | 9 +- src/kakao/Kakao_REST_API_Helper.php | 334 +++++++++++++------------ src/sammo/AppConf.php | 30 ++- src/sammo/FileTail.php | 6 +- src/sammo/FileUtil.php | 19 +- src/sammo/Json.php | 24 +- src/sammo/Lock.php | 67 +++-- src/sammo/Session.php | 160 ++++++------ src/sammo/Setting.php | 71 +++--- src/sammo/StringUtil.php | 125 +++++---- src/sammo/TimeUtil.php | 38 +-- src/sammo/Util.php | 129 +++++----- src/sammo/Validator.php | 12 +- src/sammo/WebUtil.php | 33 +-- src/sammo/templates/block_htaccess.php | 2 +- 18 files changed, 584 insertions(+), 481 deletions(-) diff --git a/d_setting/RootDB.orig.php b/d_setting/RootDB.orig.php index 9c2a43c9..e4775ad8 100644 --- a/d_setting/RootDB.orig.php +++ b/d_setting/RootDB.orig.php @@ -23,6 +23,7 @@ class RootDB{ * DB 객체 생성 * * @return \MeekroDB + * @suppress PhanTypeMismatchProperty */ public static function db(){ if(self::$uDB === null){ diff --git a/hwe/d_setting/DB.orig.php b/hwe/d_setting/DB.orig.php index 8ad0333b..5ebb9046 100644 --- a/hwe/d_setting/DB.orig.php +++ b/hwe/d_setting/DB.orig.php @@ -21,6 +21,7 @@ class DB{ * DB 객체 생성 * * @return \MeekroDB + * @suppress PhanTypeMismatchProperty */ public static function db(){ if(self::$uDB === null){ diff --git a/hwe/func_gamerule.php b/hwe/func_gamerule.php index a221fa4f..53a9c1ad 100644 --- a/hwe/func_gamerule.php +++ b/hwe/func_gamerule.php @@ -92,7 +92,7 @@ function getSpecial($leader, $power, $intel) { $type = array(20, 31); $special = $type[array_rand($type)]; // 귀모는 50% * 5% = 2.5% - if($special == 31 && randBool(0.95)) { + if($special == 31 && Util::randBool(0.95)) { $special = 20; } //무장 @@ -100,7 +100,7 @@ function getSpecial($leader, $power, $intel) { $type = array(10, 11, 12, 31); $special = $type[array_rand($type)]; // 귀모는 그중에 25% * 10% = 2.5% - if($special == 31 && randBool(0.9)) { + if($special == 31 && Util::randBool(0.9)) { $type = array(10, 11, 12); $special = $type[array_rand($type)]; } diff --git a/index.php b/index.php index 1be59d9e..ae2fcabb 100644 --- a/index.php +++ b/index.php @@ -3,8 +3,8 @@ namespace sammo; require(__dir__.'/vendor/autoload.php'); -if(!class_exists('\\sammo\\RootDB')){ - header ('Location:install.php'); +if (!class_exists('\\sammo\\RootDB')) { + header('Location:install.php'); die(); } @@ -13,9 +13,8 @@ $session = Session::getInstance(); use \kakao\KakaoKey as KakaoKey; - -if($session->isLoggedIn()){ - header ('Location:i_entrance/entrance.php'); +if ($session->isLoggedIn()) { + header('Location:i_entrance/entrance.php'); die(); } diff --git a/src/kakao/Kakao_REST_API_Helper.php b/src/kakao/Kakao_REST_API_Helper.php index b50a0350..3cf41360 100644 --- a/src/kakao/Kakao_REST_API_Helper.php +++ b/src/kakao/Kakao_REST_API_Helper.php @@ -2,11 +2,12 @@ namespace kakao; if (class_exists('\\kakao\\KakaoKey') === false) { - class KakaoKey{ - const REST_KEY = ''; - const ADMIN_KEY = ''; - const REDIRECT_URI = ''; - } + class KakaoKey + { + const REST_KEY = ''; + const ADMIN_KEY = ''; + const REDIRECT_URI = ''; + } } //https://devtalk.kakao.com/t/php-rest-api/14602/3 //header('Content-Type: application/json; charset=utf-8'); @@ -19,241 +20,252 @@ if (class_exists('\\kakao\\KakaoKey') === false) { class User_Management_Path { - public static $TOKEN = "/oauth/token"; - public static $SIGNUP = "/v1/user/signup"; - public static $UNLINK = "/v1/user/unlink"; - public static $LOGOUT = "/v1/user/logout"; - public static $ME = "/v1/user/me"; - public static $UPDATE_PROFILE = "/v1/user/update_profile"; - public static $USER_IDS = "/v1/user/ids"; + public static $TOKEN = "/oauth/token"; + public static $SIGNUP = "/v1/user/signup"; + public static $UNLINK = "/v1/user/unlink"; + public static $LOGOUT = "/v1/user/logout"; + public static $ME = "/v1/user/me"; + public static $UPDATE_PROFILE = "/v1/user/update_profile"; + public static $USER_IDS = "/v1/user/ids"; } class Story_Path { - public static $PROFILE = "/v1/api/story/profile"; - public static $ISSTORYUSER = "/v1/api/story/isstoryuser"; - public static $MYSTORIES = "/v1/api/story/mystories"; - public static $MYSTORY = "/v1/api/story/mystory"; - public static $DELETE_MYSTORY = "/v1/api/story/delete/mystory"; - public static $POST_NOTE = "/v1/api/story/post/note"; - public static $UPLOAD_MULTI = "/v1/api/story/upload/multi"; - public static $POST_PHOTO = "/v1/api/story/post/photo"; - public static $LINKINFO = "/v1/api/story/linkinfo"; - public static $POST_LINK = "/v1/api/story/post/link"; + public static $PROFILE = "/v1/api/story/profile"; + public static $ISSTORYUSER = "/v1/api/story/isstoryuser"; + public static $MYSTORIES = "/v1/api/story/mystories"; + public static $MYSTORY = "/v1/api/story/mystory"; + public static $DELETE_MYSTORY = "/v1/api/story/delete/mystory"; + public static $POST_NOTE = "/v1/api/story/post/note"; + public static $UPLOAD_MULTI = "/v1/api/story/upload/multi"; + public static $POST_PHOTO = "/v1/api/story/post/photo"; + public static $LINKINFO = "/v1/api/story/linkinfo"; + public static $POST_LINK = "/v1/api/story/post/link"; } class Talk_Path { - public static $TALK_PROFILE= "/v1/api/talk/profile"; - public static $TALK_TO_ME = "/v2/api/talk/memo/send"; - public static $TALK_TO_ME_DEFAULT = "/v2/api/talk/memo/default/send"; + public static $TALK_PROFILE= "/v1/api/talk/profile"; + public static $TALK_TO_ME = "/v2/api/talk/memo/send"; + public static $TALK_TO_ME_DEFAULT = "/v2/api/talk/memo/default/send"; } class Push_Notification_Path { - public static $REGISTER = "/v1/push/register"; - public static $TOKENS = "/v1/push/tokens"; - public static $DEREGISTER = "/v1/push/deregister"; - public static $SEND = "/v1/push/send"; + public static $REGISTER = "/v1/push/register"; + public static $TOKENS = "/v1/push/tokens"; + public static $DEREGISTER = "/v1/push/deregister"; + public static $SEND = "/v1/push/send"; } class Kakao_REST_API_Helper { - public static $OAUTH_HOST = "https://kauth.kakao.com"; - public static $API_HOST = "https://kapi.kakao.com"; + public static $OAUTH_HOST = "https://kauth.kakao.com"; + public static $API_HOST = "https://kapi.kakao.com"; - private static $admin_apis; + private static $admin_apis; - private $access_token; - private $admin_key; + private $access_token; + private $admin_key; - public function __construct($access_token = '') { + public function __construct($access_token = '') + { + if ($access_token) { + $this->access_token = $access_token; + } - if ($access_token) { - $this->access_token = $access_token; - } - - self::$admin_apis = array( + self::$admin_apis = array( User_Management_Path::$USER_IDS, Push_Notification_Path::$REGISTER, Push_Notification_Path::$TOKENS, Push_Notification_Path::$DEREGISTER, Push_Notification_Path::$SEND ); - } - - public function request($api_path, $params = '', $http_method = 'GET') - { - if ($api_path != Story_Path::$UPLOAD_MULTI && is_array($params)) { // except for uploading - $params = http_build_query($params); } - $requestUrl = ($api_path == '/oauth/token' ? self::$OAUTH_HOST : self::$API_HOST) . $api_path; + public function request($api_path, $params = '', $http_method = 'GET') + { + if ($api_path != Story_Path::$UPLOAD_MULTI && is_array($params)) { // except for uploading + $params = http_build_query($params); + } - if (($http_method == 'GET' || $http_method == 'DELETE') && !empty($params)) { - $requestUrl .= '?'.$params; - } + $requestUrl = ($api_path == '/oauth/token' ? self::$OAUTH_HOST : self::$API_HOST) . $api_path; - $opts = array( + if (($http_method == 'GET' || $http_method == 'DELETE') && !empty($params)) { + $requestUrl .= '?'.$params; + } + + $opts = array( CURLOPT_URL => $requestUrl, CURLOPT_RETURNTRANSFER => true, CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSLVERSION => 1, ); - if ($api_path != '/oauth/token') + if ($api_path != '/oauth/token') { + if (in_array($api_path, self::$admin_apis)) { + if (!$this->admin_key) { + throw new Exception('admin key should not be null or empty.'); + } + $headers = array('Authorization: KakaoAK ' . $this->admin_key); + } else { + if (!$this->access_token) { + throw new Exception('access token should not be null or empty.'); + } + $headers = array('Authorization: Bearer ' . $this->access_token); + } + + $opts[CURLOPT_HEADER] = false; + $opts[CURLOPT_HTTPHEADER] = $headers; + } + + if ($http_method == 'POST') { + $opts[CURLOPT_POST] = true; + if ($params) { + $opts[CURLOPT_POSTFIELDS] = $params; + } + } elseif ($http_method == 'DELETE') { + $opts[CURLOPT_CUSTOMREQUEST] = 'DELETE'; + } + + $curl_session = curl_init(); + curl_setopt_array($curl_session, $opts); + $return_data = curl_exec($curl_session); + + if (curl_errno($curl_session)) { + throw new Exception(curl_error($curl_session)); + } else { + // 디버깅 시에 주석을 풀고 응답 내용 확인할 때 + //print_r(curl_getinfo($curl_session)); + curl_close($curl_session); + return json_decode($return_data, true); + } + } + + public function set_access_token($access_token) { - if (in_array($api_path, self::$admin_apis)) { - - if (!$this->admin_key) { - throw new Exception('admin key should not be null or empty.'); - } - $headers = array('Authorization: KakaoAK ' . $this->admin_key); - - } else { - - if (!$this->access_token) { - throw new Exception('access token should not be null or empty.'); - } - $headers = array('Authorization: Bearer ' . $this->access_token); - } - - $opts[CURLOPT_HEADER] = false; - $opts[CURLOPT_HTTPHEADER] = $headers; + $this->access_token = $access_token; } - if ($http_method == 'POST') { - $opts[CURLOPT_POST] = true; - if ($params) { - $opts[CURLOPT_POSTFIELDS] = $params; - } - } else if ($http_method == 'DELETE') { - $opts[CURLOPT_CUSTOMREQUEST] = 'DELETE'; + public function set_admin_key($admin_key) + { + $this->admin_key = $admin_key; } - $curl_session = curl_init(); - curl_setopt_array($curl_session, $opts); - $return_data = curl_exec($curl_session); + /////////////////////////////////////////////////////////////// + // User Management + /////////////////////////////////////////////////////////////// - if (curl_errno($curl_session)) { - throw new Exception(curl_error($curl_session)); - } else { - // 디버깅 시에 주석을 풀고 응답 내용 확인할 때 - //print_r(curl_getinfo($curl_session)); - curl_close($curl_session); - return json_decode($return_data, true); + private function _create_or_refresh_access_token($params) + { + return $this->request(User_Management_Path::$TOKEN, $params, 'POST'); } - } - public function set_access_token($access_token) { - $this->access_token = $access_token; - } - - public function set_admin_key($admin_key) { - $this->admin_key = $admin_key; - } - - /////////////////////////////////////////////////////////////// - // User Management - /////////////////////////////////////////////////////////////// - - private function _create_or_refresh_access_token($params) { - return $this->request(User_Management_Path::$TOKEN, $params, 'POST'); - } - - public function create_access_token($authorization_code){ - $this->AUTHORIZATION_CODE = $authorization_code; - $params = [ + public function create_access_token($authorization_code) + { + $this->AUTHORIZATION_CODE = $authorization_code; + $params = [ 'grant_type'=>'authorization_code', 'client_id'=>$this->REST_KEY, 'redirect_uri'=>$this->REDIRECT_URI, 'code'=>$this->AUTHORIZATION_CODE ]; - $result = $this->_create_or_refresh_access_token($params); + $result = $this->_create_or_refresh_access_token($params); - return $result; - } + return $result; + } - public function refresh_access_token($refresh_token){ - $params = [ + public function refresh_access_token($refresh_token) + { + $params = [ 'grant_type'=>'refresh_token', 'client_id'=>$this->REST_KEY, 'redirect_uri'=>$this->REDIRECT_URI, 'code'=>$refresh_token ]; - $result = $this->_create_or_refresh_access_token($params); + $result = $this->_create_or_refresh_access_token($params); - return $result; - } + return $result; + } - public function signup() { - return $this->request(User_Management_Path::$SIGNUP); - } + public function signup() + { + return $this->request(User_Management_Path::$SIGNUP); + } - public function unlink() { - return $this->request(User_Management_Path::$UNLINK); - } + public function unlink() + { + return $this->request(User_Management_Path::$UNLINK); + } - public function logout() { - return $this->request(User_Management_Path::$UNLINK); - } + public function logout() + { + return $this->request(User_Management_Path::$UNLINK); + } - public function me() { - return $this->request(User_Management_Path::$ME); - } + public function me() + { + return $this->request(User_Management_Path::$ME); + } - public function meWithEmail(){ - $params = [ + public function meWithEmail() + { + $params = [ 'propertyKeys'=>'["id","kaacount_email","kaccount_email_verified"]' ]; - return $this->request(User_Management_Path::$ME); - } + return $this->request(User_Management_Path::$ME); + } - public function update_profile($params) { - return $this->request(User_Management_Path::$UPDATE_PROFILE, $params, 'POST'); - } + public function update_profile($params) + { + return $this->request(User_Management_Path::$UPDATE_PROFILE, $params, 'POST'); + } - public function user_ids() { - return $this->request(User_Management_Path::$USER_IDS); - } + public function user_ids() + { + return $this->request(User_Management_Path::$USER_IDS); + } - /////////////////////////////////////////////////////////////// - // Kakao Story - /////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////// + // Kakao Story + /////////////////////////////////////////////////////////////// - public function isstoryuser() { - return $this->request(Story_Path::$ISSTORYUSER); - } + public function isstoryuser() + { + return $this->request(Story_Path::$ISSTORYUSER); + } - public function story_profile() { - return $this->request(Story_Path::$PROFILE); - } + public function story_profile() + { + return $this->request(Story_Path::$PROFILE); + } - /////////////////////////////////////////////////////////////// - // Kakao Talk - /////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////// + // Kakao Talk + /////////////////////////////////////////////////////////////// - public function talk_profile() { - return $this->request(Talk_Path::$TALK_PROFILE); - } + public function talk_profile() + { + return $this->request(Talk_Path::$TALK_PROFILE); + } - public function talk_to_me_default($req){ - - $params = [ + public function talk_to_me_default($req) + { + $params = [ 'template_object' => json_encode($req) ]; - return $this->request(Talk_Path::$TALK_TO_ME_DEFAULT, $params, 'POST'); - } + return $this->request(Talk_Path::$TALK_TO_ME_DEFAULT, $params, 'POST'); + } - /////////////////////////////////////////////////////////////// - // API Test - /////////////////////////////////////////////////////////////// + /////////////////////////////////////////////////////////////// + // API Test + /////////////////////////////////////////////////////////////// - private $REST_KEY = KakaoKey::REST_KEY; // 디벨로퍼스의 앱 설정에서 확인할 수 있습니다. + private $REST_KEY = KakaoKey::REST_KEY; // 디벨로퍼스의 앱 설정에서 확인할 수 있습니다. private $REDIRECT_URI = KakaoKey::REDIRECT_URI; // 설정에 등록한 사이트 도메인 + redirect uri private $AUTHORIZATION_CODE = ''; // 동의를 한 후 발급되는 code private $REFRESH_TOKEN = ''; -} \ No newline at end of file +} diff --git a/src/sammo/AppConf.php b/src/sammo/AppConf.php index aaa04435..25ff29f3 100644 --- a/src/sammo/AppConf.php +++ b/src/sammo/AppConf.php @@ -1,16 +1,18 @@ new Setting(ROOT.'/che', '체', 'white'), 'kwe'=>new Setting(ROOT.'/kwe', '퀘', 'yellow'), @@ -24,11 +26,12 @@ class AppConf{ /** * DB 객체 생성 - * - * @return \MeekroDB + * + * @return \MeekroDB */ - public static function requireRootDB(){ - if(!class_exists('\\sammo\\RootDB')){ + public static function requireRootDB() + { + if (!class_exists('\\sammo\\RootDB')) { trigger_error('RootDB.php가 설정되지 않았습니다.', E_USER_ERROR); die(); } @@ -37,14 +40,15 @@ class AppConf{ /** * DB 객체 생성 - * - * @return \MeekroDB + * + * @return \MeekroDB */ - public static function requireDB(){ - if(!class_exists('\\sammo\\DB')){ + public static function requireDB() + { + if (!class_exists('\\sammo\\DB')) { trigger_error('DB.php가 설정되지 않았습니다.', E_USER_ERROR); die(); } return DB::db(); } -} \ No newline at end of file +} diff --git a/src/sammo/FileTail.php b/src/sammo/FileTail.php index 2e8f481d..f77328c6 100644 --- a/src/sammo/FileTail.php +++ b/src/sammo/FileTail.php @@ -1,6 +1,6 @@ true, - 'time'=>true, - 'userID'=>true, - 'userName'=>true, - 'userGrade'=>true, + 'time'=>true, + 'userID'=>true, + 'userName'=>true, + 'userGrade'=>true, 'writeClosed'=>true, 'generalID'=>true, 'generalName'=>true @@ -31,15 +31,17 @@ class Session { private $writeClosed = false; private $sessionID = null; - public static function getInstance(): Session{ + public static function getInstance(): Session + { static $inst = null; - if($inst === null){ + if ($inst === null) { $inst = new Session(); } return $inst; } - public function restart(): Session{ + public function restart(): Session + { //NOTE: logout 프로세스는 아예 세션을 날려버리기도 하므로, 항상 안전하게 session_restart가 가능함을 보장하지 않음. ini_set('session.use_only_cookies', false); ini_set('session.use_cookies', false); @@ -50,8 +52,9 @@ class Session { return $this; } - private static function die($result){ - if(is_string($result)){ + private static function die($result) + { + if (is_string($result)) { header('Location:'.$result); die(); } @@ -61,90 +64,98 @@ class Session { 'reason'=>'로그인이 필요합니다.' ]; - if(is_array($result)){ + if (is_array($result)) { $jsonResult = array_merge($result, $jsonResult); } Json::die($jsonResult); } - public static function requireLogin($result = '..'): Session{ + public static function requireLogin($result = '..'): Session + { $session = Session::getInstance(); - if($session->isLoggedIn()){ + if ($session->isLoggedIn()) { return $session; } static::die($result); } - public static function requireGameLogin($result = '..'): Session{ + public static function requireGameLogin($result = '..'): Session + { $session = Session::requireLogin($result)->loginGame(); - if($session->generalID){ + if ($session->generalID) { return $session; } static::die($result); } - public function __construct() { + public function __construct() + { //session_cache_limiter('nocache, must_revalidate'); // 세션 변수의 등록 - if (session_id() == ""){ + if (session_id() == "") { session_start(); $this->sessionID = session_id(); } //첫 등장 - if(!$this->get('ip')) { + if (!$this->get('ip')) { $this->set('ip', Util::get_client_ip(true)); $this->set('time', time()); } } - public function setReadOnly(): Session{ - if(!$this->writeClosed){ + public function setReadOnly(): Session + { + if (!$this->writeClosed) { session_write_close(); $this->writeClosed = true; - } + } return $this; } - public function __set(string $name, $value){ - if(key_exists($name, $this->PROTECED_NAMES)){ + public function __set(string $name, $value) + { + if (key_exists($name, $this->PROTECED_NAMES)) { trigger_error("{$name}은 외부에서 쓰기 금지된 Session 변수입니다.", E_USER_NOTICE); return; } - $this->set($name, $value); + $this->set($name, $value); } - private function set(string $name, $value){ - if($value === null){ + private function set(string $name, $value) + { + if ($value === null) { unset($_SESSION[$name]); - } - else{ + } else { $_SESSION[$name] = $value; } } - public function __get(string $name){ - if($name == 'generalID'){ + public function __get(string $name) + { + if ($name == 'generalID') { return $this->get(UniqueConst::$serverID.static::GAME_KEY_GENERAL_ID); } - if($name == 'generalName'){ + if ($name == 'generalName') { return $this->get(UniqueConst::$serverID.static::GAME_KEY_GENERAL_NAME); } return $this->get($name); } - private function get(string $name){ + private function get(string $name) + { return Util::array_get($_SESSION[$name]); } - public function login(int $userID, string $userName, int $grade): Session { + public function login(int $userID, string $userName, int $grade): Session + { $this->set('userID', $userID); $this->set('userName', $userName); $this->set('ip', Util::get_client_ip(true)); @@ -155,11 +166,12 @@ class Session { } - public function logout(): Session { - if($this->writeClosed){ + public function logout(): Session + { + if ($this->writeClosed) { $this->restart(); } - if(class_exists('\\sammo\\UniqueConst')){ + if (class_exists('\\sammo\\UniqueConst')) { $this->logoutGame(); } @@ -170,17 +182,18 @@ class Session { return $this; } - public function loginGame(&$result = null): Session{ + public function loginGame(&$result = null): Session + { $userID = $this->userID; - if(!$userID){ - if($result !== null){ + if (!$userID) { + if ($result !== null) { $result = false; } return $this; } - if(!class_exists('\\sammo\\DB') || !class_exists('\\sammo\\UniqueConst')){ - if($result !== null){ + if (!class_exists('\\sammo\\DB') || !class_exists('\\sammo\\UniqueConst')) { + if ($result !== null) { $result = false; } return $this; @@ -194,29 +207,29 @@ class Session { $deadTime = $this->get($serverID.static::GAME_KEY_EXPECTED_DEADTIME); $now = time(); - if( + if ( $generalID && $generalName && $loginDate && $deadTime && $loginDate + 1800 > $now && $deadTime > $now - ){ + ) { //로그인 정보는 30분간 유지한다. - if($result !== null){ + if ($result !== null) { $result = true; } return $this; } - if($generalID || $generalName || $loginDate || $deadTime){ + if ($generalID || $generalName || $loginDate || $deadTime) { $this->logoutGame(); } $db = DB::db(); $general = $db->queryFirstRow( - 'SELECT `no`, `name`, `killturn`, `turntime` from general where `owner` = %i', + 'SELECT `no`, `name`, `killturn`, `turntime` from general where `owner` = %i', $userID ); - if(!$general){ - if($result !== null){ + if (!$general) { + if ($result !== null) { $result = false; } return $this; @@ -232,15 +245,14 @@ class Session { $nextTurn = $nextTurn->getTimestamp(); $deadTime = $nextTurn + $general['killturn'] * $turnterm; - if($deadTime < $now && !$isUnited){ + if ($deadTime < $now && !$isUnited) { $locked = $db->queryFirstField('SELECT plock FROM plock LIMIT 1'); - if(!$locked){ - if($result !== null){ + if (!$locked) { + if ($result !== null) { $result = false; } return $this; } - } $db->update('general', [ @@ -256,8 +268,9 @@ class Session { return $this; } - public function logoutGame(): Session{ - if($this->writeClosed){ + public function logoutGame(): Session + { + if ($this->writeClosed) { $this->restart(); } $serverID = UniqueConst::$serverID; @@ -273,44 +286,43 @@ class Session { * 로그인 유저의 전역 grade를 받아옴 * @return int|null */ - public static function getUserGrade(bool $requireLogin = false, string $exitPath = '..'){ - if($requireLogin){ + public static function getUserGrade(bool $requireLogin = false, string $exitPath = '..') + { + if ($requireLogin) { $obj = self::requireLogin($exitPath); - } - else{ + } else { $obj = self::getInstance(); } return $obj->userGrade; } - /** - * 로그인한 유저의 전역 id(숫자)를 받아옴 + /** + * 로그인한 유저의 전역 id(숫자)를 받아옴 * - * @return int|null + * @return int|null */ - public static function getUserID(bool $requireLogin = false, string $exitPath = '..'){ - if($requireLogin){ + public static function getUserID(bool $requireLogin = false, string $exitPath = '..') + { + if ($requireLogin) { $obj = self::requireLogin($exitPath); - } - else{ + } else { $obj = self::getInstance(); } return $obj->userID; } - public function isLoggedIn() { - if($this->userID){ + public function isLoggedIn() + { + if ($this->userID) { return true; - } - else{ + } else { return false; } } - public function __destruct() { + public function __destruct() + { } } - - diff --git a/src/sammo/Setting.php b/src/sammo/Setting.php index ec59ff7a..c5c51903 100644 --- a/src/sammo/Setting.php +++ b/src/sammo/Setting.php @@ -1,7 +1,8 @@ basepath = $basepath; $this->settingFile = realpath($basepath.'/d_setting/DB.php'); $this->htaccessFile = realpath($basepath.'/.htaccess'); @@ -22,56 +24,63 @@ class Setting { $this->korName = $korName; $this->color = $color; - if($name){ + if ($name) { $this->shortName = $name; - } - else{ + } else { $this->shortName = basename($this->basepath); } - if(file_exists($this->settingFile)) { + if (file_exists($this->settingFile)) { $this->exist = true; - if(!file_exists($this->htaccessFile)){ + if (!file_exists($this->htaccessFile)) { $this->running = true; } } } - public function isRunning(){ + public function isRunning() + { return $this->running; } - public function isExists() { + public function isExists() + { return $this->exist; } - public function getShortName(){ + public function getShortName() + { return $this->shortName; } - public function getColor(){ + public function getColor() + { return $this->color; } - public function getKorName(){ + public function getKorName() + { return $this->korName; } - public function getBasePath(){ + public function getBasePath() + { return $this->basepath; } - public function getSettingFile() { + public function getSettingFile() + { return $this->settingFile; } - public function getVersion(){ - if($this->version !== null){ + public function getVersion() + { + if ($this->version !== null) { return $this->version; } - if(!file_exists($this->versionFile)){ + if (!file_exists($this->versionFile)) { $this->version = 'noVersionFile'; return $this->version; } @@ -79,7 +88,7 @@ class Setting { $tail = new FileTail($this->versionFile); $version = 'noVersionJson'; foreach ($tail->smart(5, 100, true) as $line) { - if(Util::starts_with($line, '//{')){ + if (Util::starts_with($line, '//{')) { $version = Json::decode(substr($line, 2)); $version = Util::array_get($version['version'], 'noVersionValue'); break; @@ -87,40 +96,40 @@ class Setting { } $this->version = $version; return $version; - } - public function closeServer(){ - if(!file_exists($this->basepath) || !is_dir($this->basepath)){ + public function closeServer() + { + if (!file_exists($this->basepath) || !is_dir($this->basepath)) { return false; } $templates = new \League\Plates\Engine(__dir__.'/templates'); //TODO: .htaccess가 서버 오픈에도 사용될 수 있으니 별도의 방법이 필요함 $allow_ip = Util::get_client_ip(false); - if(Util::starts_with($allow_ip, '192.168.') || - Util::starts_with($allow_ip, '10.')) - { + if (Util::starts_with($allow_ip, '192.168.') || + Util::starts_with($allow_ip, '10.')) { //172.16~172.31은 코딩하기 귀찮으니까 안할거다 $allow_ip = Util::get_client_ip(true); } $xforward_allow_ip = WebUtil::escapeIPv4($allow_ip); - $htaccess = $templates->render('block_htaccess', - ['allow_ip' => $allow_ip, 'xforward_allow_ip' => $xforward_allow_ip]); + $htaccess = $templates->render( + 'block_htaccess', + ['allow_ip' => $allow_ip, 'xforward_allow_ip' => $xforward_allow_ip] + ); file_put_contents($this->basepath.'/.htaccess', $htaccess); return true; } - public function openServer(){ - if(!file_exists($this->basepath) || !is_dir($this->basepath)){ + public function openServer() + { + if (!file_exists($this->basepath) || !is_dir($this->basepath)) { return false; } - if(file_exists($this->basepath.'/.htaccess')){ + if (file_exists($this->basepath.'/.htaccess')) { @unlink($this->basepath.'/.htaccess'); } return true; } } - - diff --git a/src/sammo/StringUtil.php b/src/sammo/StringUtil.php index 2c4e74de..10a3d2c0 100644 --- a/src/sammo/StringUtil.php +++ b/src/sammo/StringUtil.php @@ -1,20 +1,22 @@ = 0xf0) { + if ($code >= 0xf0) { $len++; $i += 4; - } elseif($code >= 0xe0) { + } elseif ($code >= 0xe0) { $len++; $i += 3; - } elseif($code >= 0xc2) { + } elseif ($code >= 0xc2) { $len++; $i += 2; } else { @@ -25,29 +27,32 @@ class StringUtil { return $len; } - public static function SubStr($str, $s, $l=1000) { + public static function SubStr($str, $s, $l=1000) + { $count = strlen($str); - $startByte = 0; $isSet = 0; + $startByte = 0; + $isSet = 0; $endByte = $count; $len = 0; - for($i=0; $i < $count; ) { + for ($i=0; $i < $count;) { $code = ord($str[$i]); - if($isSet == 0 && $len >= $s) { - $startByte = $i; $isSet = 1; + if ($isSet == 0 && $len >= $s) { + $startByte = $i; + $isSet = 1; } - if($isSet == 1 && $len-$s >= $l) { + if ($isSet == 1 && $len-$s >= $l) { $endByte = $i; break; } - if($code >= 0xf0) { + if ($code >= 0xf0) { $len++; $i += 4; - } elseif($code >= 0xe0) { + } elseif ($code >= 0xe0) { $len++; $i += 3; - } elseif($code >= 0xc2) { + } elseif ($code >= 0xc2) { $len++; $i += 2; } else { @@ -59,39 +64,43 @@ class StringUtil { return $str; } - public static function SubStrForWidth($str, $s, $w) { + public static function SubStrForWidth($str, $s, $w) + { $count = strlen($str); - $startByte = 0; $isSet = 0; - $endByte = $count; $last = 0; + $startByte = 0; + $isSet = 0; + $endByte = $count; + $last = 0; $len = 0; $width = 0; - for($i=0; $i < $count; ) { + for ($i=0; $i < $count;) { $code = ord($str[$i]); - if($isSet == 0 && $len >= $s) { - $startByte = $i; $isSet = 1; + if ($isSet == 0 && $len >= $s) { + $startByte = $i; + $isSet = 1; $width = 0; } - if($isSet == 1 && $width == $w) { + if ($isSet == 1 && $width == $w) { $endByte = $i; break; } - if($isSet == 1 && $width > $w) { + if ($isSet == 1 && $width > $w) { $endByte = $i - $last; break; } - if($code >= 0xf0) { + if ($code >= 0xf0) { $len++; $width += 2; $last = 4; $i += 4; - } elseif($code >= 0xe0) { + } elseif ($code >= 0xe0) { $len++; $width += 2; $last = 3; $i += 3; - } elseif($code >= 0xc2) { + } elseif ($code >= 0xc2) { $len++; $width += 2; $last = 2; @@ -107,37 +116,41 @@ class StringUtil { return $str; } - public static function CutStrForWidth($str, $s, $w, $ch='..') { + public static function CutStrForWidth($str, $s, $w, $ch='..') + { $isCut = 0; $count = strlen($str); - $startByte = 0; $isSet = 0; - $endByte = $count; $last = 0; + $startByte = 0; + $isSet = 0; + $endByte = $count; + $last = 0; $len = 0; $width = 0; - for($i=0; $i < $count; ) { + for ($i=0; $i < $count;) { $code = ord($str[$i]); - if($isSet == 0 && $len >= $s) { - $startByte = $i; $isSet = 1; + if ($isSet == 0 && $len >= $s) { + $startByte = $i; + $isSet = 1; $width = 0; } - if($isSet == 1 && $width >= $w) { + if ($isSet == 1 && $width >= $w) { $endByte = $i - $last; $isCut = 1; break; } - if($code >= 0xf0) { + if ($code >= 0xf0) { $len++; $width += 2; $last = 4; $i += 4; - } elseif($code >= 0xe0) { + } elseif ($code >= 0xe0) { $len++; $width += 2; $last = 3; $i += 3; - } elseif($code >= 0xc2) { + } elseif ($code >= 0xc2) { $len++; $width += 2; $last = 2; @@ -149,15 +162,16 @@ class StringUtil { $i += 1; } } - if($isCut != 0) { + if ($isCut != 0) { $str = substr($str, $startByte, $endByte-$startByte) . $ch; } return $str; } //중간정렬 - public static function staticFill($str, $maxsize, $ch) { - if(!$str){ + public static function staticFill($str, $maxsize, $ch) + { + if (!$str) { $str = ''; } $size = strlen($str); @@ -165,18 +179,19 @@ class StringUtil { $count = ($maxsize - $size) / 2; $string = ''; - for($i=0; $i < $count; $i++) { + for ($i=0; $i < $count; $i++) { $string = $string.$ch; } $string = $string.$str; - for($i=0; $i < $count; $i++) { + for ($i=0; $i < $count; $i++) { $string = $string.$ch; } return $string; } - public static function Fill($str, $maxsize, $ch) { - if(!$str){ + public static function Fill($str, $maxsize, $ch) + { + if (!$str) { $str = ''; } $size = strlen($str); @@ -184,26 +199,27 @@ class StringUtil { $count = ($maxsize - $size) / 2; $string = ''; - for($i=0; $i < $count; $i++) { + for ($i=0; $i < $count; $i++) { $string = $string.$ch; } $string = $string.$str; - for($i=0; $i < $count; $i++) { + for ($i=0; $i < $count; $i++) { $string = $string.$ch; } return $string; } //우측정렬 - public static function Fill2($str, $maxsize, $ch='0') { - if(!$str){ + public static function Fill2($str, $maxsize, $ch='0') + { + if (!$str) { $str = ''; } $size = strlen($str); $count = ($maxsize - $size); $string = ''; - for($i=0; $i < $count; $i++) { + for ($i=0; $i < $count; $i++) { $string = $string.$ch; } $string = $string.$str; @@ -211,7 +227,8 @@ class StringUtil { return $string; } - public static function EscapeTag($str) { + public static function EscapeTag($str) + { $str = htmlspecialchars($str); $str = str_replace(["\r\n", "\r", "\n"], '
', $str); // return nl2br(htmlspecialchars($str)); @@ -219,13 +236,13 @@ class StringUtil { return $str; } - public static function removeSpecialCharacter($str) { + public static function removeSpecialCharacter($str) + { return str_replace([ - ' ', '"', '\'', 'ⓝ', 'ⓜ', 'ⓖ', '\\', '/', '`', - '-', '=', '[', ']', ';', ',', '.', '~', '!', '@', - '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', + ' ', '"', '\'', 'ⓝ', 'ⓜ', 'ⓖ', '\\', '/', '`', + '-', '=', '[', ']', ';', ',', '.', '~', '!', '@', + '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '|', '{', '}', ':', '', '<', '>', '?', ' ' ], '', $str); } - } diff --git a/src/sammo/TimeUtil.php b/src/sammo/TimeUtil.php index b0e3b96f..84572bcb 100644 --- a/src/sammo/TimeUtil.php +++ b/src/sammo/TimeUtil.php @@ -1,46 +1,57 @@ $value){ + foreach ($params as $key => $value) { $text = str_replace("_tK_{$key}_", $value, $text); } file_put_contents($destFilePath, $text); @@ -39,28 +42,29 @@ class Util extends \utilphp\util{ * float -> int * numeric(int, float) 포함 -> int * 기타 -> 예외처리 - * + * * @return int|null */ - public static function toInt($val, $silent=false){ - if(!isset($val)){ + public static function toInt($val, $silent=false) + { + if (!isset($val)) { return null; } - if($val === null){ + if ($val === null) { return null; } - if(is_int($val)){ + if (is_int($val)) { return $val; } - if(is_numeric($val)){ + if (is_numeric($val)) { return intval($val);// } - if(strtolower($val) === 'null'){ + if (strtolower($val) === 'null') { return null; } - if($silent){ - if($val == null){ + if ($silent) { + if ($val == null) { return null; } return intval($val); @@ -69,12 +73,12 @@ class Util extends \utilphp\util{ } /** - * Generate a random string, using a cryptographically secure + * Generate a random string, using a cryptographically secure * pseudorandom number generator (random_int) - * + * * For PHP 7, random_int is a PHP core function * For PHP 5.x, depends on https://github.com/paragonie/random_compat - * + * * @param int $length How many characters do we want? * @param string $keyspace A string of all possible characters * to select from @@ -90,18 +94,20 @@ class Util extends \utilphp\util{ return $str; } - public static function mapWithDict($callback, $dict){ + public static function mapWithDict($callback, $dict) + { $result = []; - foreach(array_keys($dict) as $key){ + foreach (array_keys($dict) as $key) { $result[$key] = ($callback)($dict[$key]); } return $result; } - public static function convertArrayToDict($arr, $keyName){ + public static function convertArrayToDict($arr, $keyName) + { $result = []; - foreach($arr as $obj){ + foreach ($arr as $obj) { $key = $obj[$keyName]; $result[$key] = $obj; } @@ -109,66 +115,65 @@ class Util extends \utilphp\util{ return $result; } - public static function convertDictToArray($dict, $keys){ + public static function convertDictToArray($dict, $keys) + { $result = []; - foreach($keys as $key){ + foreach ($keys as $key) { $result[] = Util::array_get($dict[$key], null); } return $result; } - public static function isDict(&$array){ - if(!is_array($array)){ + public static function isDict(&$array) + { + if (!is_array($array)) { //배열이 아니면 dictionary 조차 아님. return false; } $idx = 0; $jmp = 0; foreach ($array as $key=>&$value) { - if(is_string($key)){ + if (is_string($key)) { return true; } $jmp = $key - $idx - 1; $idx = $key; } - if ($jmp * 5 >= count($array)){ + if ($jmp * 5 >= count($array)) { //빈칸이 많으면 dictionary인걸로. return true; - } - else{ + } else { return false; } } - public static function eraseNullValue($dict, $depth=512){ + public static function eraseNullValue($dict, $depth=512) + { //TODO:Test 추가 - if($dict === null){ + if ($dict === null) { return null; } - if(is_array($dict) && empty($dict)){ + if (is_array($dict) && empty($dict)) { return null; } - if($depth <= 0){ + if ($depth <= 0) { return $dict; } foreach ($dict as $key=>$value) { - if($value === null){ + if ($value === null) { unset($dict[$key]); - } - else if(Util::isDict($value)){ + } elseif (Util::isDict($value)) { $newValue = Util::eraseNullValue($value, $depth - 1); - if($newValue === null){ + if ($newValue === null) { unset($dict[$key]); - } - else{ + } else { $dict[$key] = $newValue; } - } } @@ -176,11 +181,12 @@ class Util extends \utilphp\util{ } - /** + /** * 0.0~1.0 사이의 랜덤 float * @return float */ - public static function randF(){ + public static function randF() + { return mt_rand() / mt_getrandmax(); } @@ -188,7 +194,8 @@ class Util extends \utilphp\util{ * $prob의 확률로 true를 반환 * @return boolean */ - public static function randBool($prob = 0.5){ + public static function randBool($prob = 0.5) + { return self::randF() < $prob; } @@ -196,11 +203,12 @@ class Util extends \utilphp\util{ /** * $min과 $max 사이의 값으로 교정 */ - public static function valueFit($value, $min, $max){ - if($value < $min){ + public static function valueFit($value, $min, $max) + { + if ($value < $min) { return $min; } - if($value > $max){ + if ($value > $max) { return $max; } return $value; @@ -208,20 +216,21 @@ class Util extends \utilphp\util{ /** * 각 값의 비중에 따라 랜덤한 값을 선택 - * + * * @param array $items 각 수치의 비중 - * + * * @return int|string 선택된 랜덤 값의 key값. 단순 배열인 경우에는 index */ - public static function choiceRandomUsingWeight(array $items){ + public static function choiceRandomUsingWeight(array $items) + { $sum = 0; - foreach($items as $value){ + foreach ($items as $value) { $sum += $value; } $rd = self::randF()*$sum; - foreach($items as $key=>$value){ - if($rd <= $value){ + foreach ($items as $key=>$value) { + if ($rd <= $value) { return $key; } $rd -= $value; @@ -234,13 +243,13 @@ class Util extends \utilphp\util{ /** * 배열의 아무거나 고름. Python의 random.choice() - * + * * @param array $items 선택하고자 하는 배열 - * + * * @return object 선택된 value값. */ - public static function choiceRandom(array $items){ + public static function choiceRandom(array $items) + { return $items[array_rand($items)]; } - -}; \ No newline at end of file +}; diff --git a/src/sammo/Validator.php b/src/sammo/Validator.php index ab3b346a..977cb3bc 100644 --- a/src/sammo/Validator.php +++ b/src/sammo/Validator.php @@ -1,13 +1,17 @@ errors()); - $errors = array_map(function($value){return join(', ', $value);}, $errors); + $errors = array_map(function ($value) { + return join(', ', $value); + }, $errors); $errors = join(', ', $errors); return $errors; } -} \ No newline at end of file +} diff --git a/src/sammo/WebUtil.php b/src/sammo/WebUtil.php index 236354ce..5595c064 100644 --- a/src/sammo/WebUtil.php +++ b/src/sammo/WebUtil.php @@ -1,35 +1,38 @@ Deny from all - + SetEnvIf X-Forwarded-For ^ env_allow_1 Allow from env=env_allow_1 Allow from