From 157ecdbf2ad4c58635f860c61369225b1ff294ff Mon Sep 17 00:00:00 2001 From: hide_d Date: Sat, 24 Mar 2018 22:03:54 +0900 Subject: [PATCH] =?UTF-8?q?=EB=A7=8E=EC=9D=80=20=EC=9C=A0=ED=8B=B8?= =?UTF-8?q?=EB=A6=AC=ED=8B=B0=20=ED=95=A8=EC=88=98=EB=A5=BC=20Util,=20File?= =?UTF-8?q?Util,=20WebUtil=EB=A1=9C=20=EC=9D=B4=EB=8F=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- f_func/func.php | 179 +--------------------------- f_install/j_create_admin.php | 2 +- f_install/j_setup_db.php | 2 +- oauth_kakao/j_change_pw.php | 6 +- oauth_kakao/j_join_process.php | 2 +- src/sammo/FileUtil.php | 51 ++++++++ src/sammo/Json.php | 11 +- src/sammo/Util.php | 169 ++++++++++++++++++++++++++ src/sammo/WebUtil.php | 71 +++++++++++ tmp_msg/add_msg_dummy.php | 2 +- tmp_msg/json_result.php | 4 +- tmp_msg/prompt_dummy.php | 2 +- twe/func.php | 5 +- twe/func_diplomacy.php | 2 +- twe/func_file.php | 24 ---- twe/func_map.php | 20 ++-- twe/func_message.php | 2 +- twe/j_adjust_icon.php | 2 + twe/j_basic_info.php | 2 + twe/j_build_conf.php | 60 +--------- twe/j_drop_settings.php | 6 +- twe/j_get_new_msg.php | 6 +- twe/j_get_scenario_map.php | 4 +- twe/j_init_scenario.php | 2 + twe/j_init_settings.php | 2 + twe/j_map.php | 6 +- twe/j_msg_contact_list.php | 2 + twe/j_msg_decide_opt.php | 6 +- twe/j_msgsubmit.php | 2 +- twe/j_server_basic_info.php | 2 + twe/j_turn.php | 2 + twe/join_post.php | 6 +- twe/lib.php | 209 +-------------------------------- twe/login_process.php | 2 +- twe/old/j_old_install.php | 2 +- twe/reset.php | 4 +- 36 files changed, 364 insertions(+), 517 deletions(-) create mode 100644 src/sammo/FileUtil.php create mode 100644 src/sammo/WebUtil.php delete mode 100644 twe/func_file.php diff --git a/f_func/func.php b/f_func/func.php index a5b4debc..0b9cebe9 100644 --- a/f_func/func.php +++ b/f_func/func.php @@ -3,23 +3,9 @@ namespace sammo; require(__dir__.'/../vendor/autoload.php'); -function SetHeaderNoCache(){ - if(!headers_sent()) { - header('Expires: Wed, 01 Jan 2014 00:00:00 GMT'); - header('Cache-Control: no-store, no-cache, must-revalidate'); - header('Cache-Control: post-check=0, pre-check=0', FALSE); - header('Pragma: no-cache'); - } -} - function CustomHeader() { //xxx: CustomHeader를 제거하기 전까진 유지 - SetHeaderNoCache(); -} - -function getmicrotime() { - $microtimestmp = explode(' ', microtime()); - return $microtimestmp[0] + $microtimestmp[1]; + WebUtil::setHeaderNoCache(); } function logErrorByCustomHandler(int $errno, string $errstr, string $errfile, int $errline, array $errcontext){ @@ -31,171 +17,14 @@ function logErrorByCustomHandler(int $errno, string $errstr, string $errfile, in $date = date("Ymd_His"); - file_put_contents(__DIR__.'/../d_log/err_log.txt',"$date, $errno, $errstr, $errfile, $errline\n"); + file_put_contents(__DIR__.'/../d_log/err_log.txt',"$date, $errno, $errstr, $errfile, $errline\n", FILE_APPEND); /* Don't execute PHP internal error handler */ - return true; + //return true; } set_error_handler("\sammo\logErrorByCustomHandler"); function Error($msg) { - AppendToFile(ROOT.'/d_log/err.txt', $msg."\n"); + file_put_contents(ROOT.'/d_log/err.txt', $msg."\n", FILE_APPEND); exit(1); } - -function ErrorToScreen($msg) { - AppendToFile(ROOT.'/d_log/err.txt', $msg."\n"); - echo $msg; - exit(1); -} - -function WriteToFile($filename, $content) { - $fp = @fopen($filename, 'w'); - @fwrite($fp, $content); - @fclose($fp); -} - -function AppendToFile($filename, $content) { - $fp = @fopen($filename, 'a'); - @fwrite($fp, $content); - @fclose($fp); -} - -function ReadToFile($filename) { - $fp = @fopen($filename, 'r'); - $content = @fread($fp, filesize($filename)); - @fclose($fp); - return $content; -} - -function ReadToFileForward($filename, $size) { - $fp = @fopen($filename, 'r'); - $content = @fread($fp, $size); - @fclose($fp); - return $content; -} - -function ReadToFileBackward($filename, $size) { - $fp = @fopen($filename, 'r'); - @fseek($fp, -$size, SEEK_END); - $content = @fread($fp, $size); - @fclose($fp); - return $content; -} - -function delInDir($dir) { - $handle = opendir($dir); - while(false !== ($FolderOrFile = readdir($handle))) { - if($FolderOrFile != "." && $FolderOrFile != "..") { - if(is_dir("$dir/$FolderOrFile")) { - delInDir("$dir/$FolderOrFile"); - } // recursive - else { - unlink("$dir/$FolderOrFile"); - } - } - } - closedir($handle); - return $success; -} - -function delExpiredInDir($dir, $t) { - $handle = opendir($dir); - while(false !== ($FolderOrFile = readdir($handle))) { - if($FolderOrFile != "." && $FolderOrFile != "..") { - if(is_dir("$dir/$FolderOrFile")) { - delExpiredInDir("$dir/$FolderOrFile", $t); - } // recursive - else { - $mt = filemtime("$dir/$FolderOrFile"); - if($mt < $t) { - unlink("$dir/$FolderOrFile"); - } - } - } - } - closedir($handle); - return $success; -} - -function hashPassword($salt, $password){ - return hash('sha512', $salt.$password.$salt); -} - -/** - * 변환할 내용이 _tK_$key_ 형태로 작성된 단순한 템플릿 파일을 이용하여 결과물을 생성해주는 함수. - */ -function generateFileUsingSimpleTemplate(string $srcFilePath, string $destFilePath, array $params, bool $canOverwrite=false){ - if($destFilePath === $srcFilePath){ - return 'invalid destFilePath'; - } - if(!file_exists($srcFilePath)){ - return 'srcFilePath is not exists'; - } - if(file_exists($destFilePath) && !$canOverwrite){ - return 'destFilePath is already exists'; - } - if(!is_writable(dirname($destFilePath))){ - return 'destFilePath is not writable'; - } - - $text = file_get_contents($srcFilePath); - foreach($params as $key => $value){ - $text = str_replace("_tK_{$key}_", $value, $text); - } - file_put_contents($destFilePath, $text); - - return true; -} - -/** - * '비교적' 안전한 int 변환 - * null -> null - * int -> int - * float -> int - * numeric(int, float) 포함 -> int - * 기타 -> 예외처리 - * - * @return int|null - */ -function toInt($val, $force=false){ - if($val === null){ - return null; - } - if(is_int($val)){ - return $val; - } - if(is_numeric($val)){ - return intval($val);// - } - if(strtolower($val) === 'null'){ - return null; - } - - if($force){ - return intval($val); - } - throw new InvalidArgumentException('올바르지 않은 타입형 :'.$val); -} - -/** - * 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 - * @return string - */ -function random_str($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') -{ - $str = ''; - $max = mb_strlen($keyspace, '8bit') - 1; - for ($i = 0; $i < $length; ++$i) { - $str .= $keyspace[random_int(0, $max)]; - } - return $str; -} diff --git a/f_install/j_create_admin.php b/f_install/j_create_admin.php index 57204020..96cac77d 100644 --- a/f_install/j_create_admin.php +++ b/f_install/j_create_admin.php @@ -50,7 +50,7 @@ if($memberCnt > 0){ } $userSalt = bin2hex(random_bytes(8)); -$finalPassword = hashPassword($userSalt, $password); +$finalPassword = Util::hashPassword($userSalt, $password); $nowDate = TimeUtil::DatetimeNow(); $rootDB->insert('member',[ diff --git a/f_install/j_setup_db.php b/f_install/j_setup_db.php index a7b994be..af16ffae 100644 --- a/f_install/j_setup_db.php +++ b/f_install/j_setup_db.php @@ -141,7 +141,7 @@ $rootDB->insert('system', array( $globalSalt = bin2hex(random_bytes(16)); -$result = generateFileUsingSimpleTemplate( +$result = Util::generateFileUsingSimpleTemplate( ROOT.'/d_setting/conf.orig.php', ROOT.'/d_setting/conf.php',[ 'host'=>$host, diff --git a/oauth_kakao/j_change_pw.php b/oauth_kakao/j_change_pw.php index cc6d26a3..e459ad1c 100644 --- a/oauth_kakao/j_change_pw.php +++ b/oauth_kakao/j_change_pw.php @@ -71,10 +71,10 @@ if(!$isUser){ ]); } -$newPassword = random_str(6); -$tmpPassword = hashPassword(getGlobalSalt(), $newPassword); +$newPassword = Util::randomStr(6); +$tmpPassword = Util::hashPassword(getGlobalSalt(), $newPassword); $newSalt = bin2hex(random_bytes(8)); -$newFinalPassword = hashPassword($newSalt, $tmpPassword); +$newFinalPassword = Util::hashPassword($newSalt, $tmpPassword); $sendResult = $restAPI->talk_to_me_default([ "object_type"=> "text", diff --git a/oauth_kakao/j_join_process.php b/oauth_kakao/j_join_process.php index 3834f82e..5a7769d3 100644 --- a/oauth_kakao/j_join_process.php +++ b/oauth_kakao/j_join_process.php @@ -80,7 +80,7 @@ if($nicknameChk !== true){ } $userSalt = bin2hex(random_bytes(8)); -$finalPassword = hashPassword($userSalt, $password); +$finalPassword = Util::hashPassword($userSalt, $password); //클라이언트 단에서 보내준 데이터 준비가 끝났다. $restAPI = new Kakao_REST_API_Helper($access_token); diff --git a/src/sammo/FileUtil.php b/src/sammo/FileUtil.php new file mode 100644 index 00000000..44cb3424 --- /dev/null +++ b/src/sammo/FileUtil.php @@ -0,0 +1,51 @@ + $value){ + $text = str_replace("_tK_{$key}_", $value, $text); + } + file_put_contents($destFilePath, $text); + + return true; + } + + /** + * '비교적' 안전한 int 변환 + * null -> null + * int -> int + * float -> int + * numeric(int, float) 포함 -> int + * 기타 -> 예외처리 + * + * @return int|null + */ + public static function toInt($val, $force=false){ + if($val === null){ + return null; + } + if(is_int($val)){ + return $val; + } + if(is_numeric($val)){ + return intval($val);// + } + if(strtolower($val) === 'null'){ + return null; + } + + if($force){ + return intval($val); + } + throw new InvalidArgumentException('올바르지 않은 타입형 :'.$val); + } + + /** + * 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 + * @return string + */ + public static function randomStr($length, $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') + { + $str = ''; + $max = mb_strlen($keyspace, '8bit') - 1; + for ($i = 0; $i < $length; ++$i) { + $str .= $keyspace[random_int(0, $max)]; + } + return $str; + } + + public static function mapWithDict($callback, $dict){ + $result = []; + foreach(array_keys($dict) as $key){ + $result[$key] = ($callback)($dict[$key]); + } + return $result; + } + + public static function convertArrayToDict($arr, $keyName){ + $result = []; + + foreach($arr as $obj){ + $key = $obj[$keyName]; + $result[$key] = $obj; + } + + return $result; + } + + public static function convertDictToArray($dict, $keys){ + $result = []; + + foreach($keys as $key){ + $result[] = Util::array_get($dict[$key], null); + } + return $result; + } + + public static function isDict(&$array){ + if(!is_array($array)){ + //배열이 아니면 dictionary 조차 아님. + return false; + } + $idx = 0; + $jmp = 0; + foreach ($arr as $key=>&$value) { + if(is_string($key)){ + return true; + } + $jmp = $key - $idx - 1; + $idx = $key; + } + + if ($jmp * 5 >= count($array)){ + //빈칸이 많으면 dictionary인걸로. + return true; + } + else{ + return false; + } + } + + public static function eraseNullValue($dict, $depth=512){ + //TODO:Test 추가 + if($dict === null){ + return null; + } + + if(is_array($dict) && empty($dict)){ + return null; + } + + if($depth <= 0){ + return $dict; + } + + foreach ($arr as $key=>$value) { + if($value === null){ + unset($dict[$key]); + } + else if(Util::isDict($value)){ + $newValue = Util::eraseNullValue($value, $depth - 1); + if($newValue === null){ + unset($dict[$key]); + } + else{ + $dict[$key] = $newValue; + } + + } + } + + return $dict; + } + + + }; \ No newline at end of file diff --git a/src/sammo/WebUtil.php b/src/sammo/WebUtil.php new file mode 100644 index 00000000..8253fd29 --- /dev/null +++ b/src/sammo/WebUtil.php @@ -0,0 +1,71 @@ +true, diff --git a/tmp_msg/json_result.php b/tmp_msg/json_result.php index e48385b2..60016ba8 100644 --- a/tmp_msg/json_result.php +++ b/tmp_msg/json_result.php @@ -26,9 +26,9 @@ function relayJson($filepath, $noCache = true, $die = true){ } } -$jsonPost = parseJsonPost(); +$jsonPost = WebUtil::parseJsonPost(); -$reqSequence = toInt(Util::array_get($jsonPost['sequence'], 0), true); +$reqSequence = Util::toInt(Util::array_get($jsonPost['sequence'], 0), true); if($reqSequence === null){ $reqSequence = 0; diff --git a/tmp_msg/prompt_dummy.php b/tmp_msg/prompt_dummy.php index b352b94d..6a0ebcdc 100644 --- a/tmp_msg/prompt_dummy.php +++ b/tmp_msg/prompt_dummy.php @@ -2,7 +2,7 @@ require('../twe/lib.php'); -$jsonPost = parseJsonPost(); +$jsonPost = WebUtil::parseJsonPost(); echo json_encode([ 'result'=>true, diff --git a/twe/func.php b/twe/func.php index 800e9bc1..4c72565d 100644 --- a/twe/func.php +++ b/twe/func.php @@ -15,7 +15,6 @@ require_once 'func_auction.php'; require_once 'func_string.php'; require_once 'func_history.php'; require_once 'func_legacy.php'; -require_once 'func_file.php'; require_once 'func_converter.php'; require_once 'func_time_event.php'; require_once('func_template.php'); @@ -148,7 +147,7 @@ function getNationStaticInfo($nationID, $forceRefresh=false) if($nationList === null){ $nationAll = getDB()->query("select nation, name, color, type, level, capital from nation"); - $nationList = ArrayToDict($nationAll, "nation"); + $nationList = Util::convertArrayToDict($nationAll, "nation"); $nationList[-1] = $nationAll; } @@ -1463,7 +1462,7 @@ function onlinegen($connect) { $onlinegen = ""; $generalID = getGeneralID(); $nationID = getDB()->queryFirstField('select `nation` from `general` where `no` = %i', $generalID); - if($nationID !== null || toInt($nationID) === 0) { + if($nationID !== null || Util::toInt($nationID) === 0) { $query = "select onlinegen from game where no='1'"; $result = MYDB_query($query, $connect) or Error(__LINE__.MYDB_error($connect),""); $game = MYDB_fetch_array($result); diff --git a/twe/func_diplomacy.php b/twe/func_diplomacy.php index 99103b47..71b2d110 100644 --- a/twe/func_diplomacy.php +++ b/twe/func_diplomacy.php @@ -40,7 +40,7 @@ function acceptScout($messageInfo, $general, $msgResponse){ $me = $general; $you = getDB()->queryFirstRow('SELECT `no`, `name`, `nation` FROM `general` WHERE `no` = %i', $messageInfo['src']['id']); - list($startyear, $year, $month, $killturn) = dictToArray(getDB()->queryFirstRow('SELECT `startyear`, `year`, `month`, `killturn` FROM `game` LIMIT 1'), ['startyear', 'year', 'month', `killturn`]); + list($startyear, $year, $month, $killturn) = Util::convertDictToArray(getDB()->queryFirstRow('SELECT `startyear`, `year`, `month`, `killturn` FROM `game` LIMIT 1'), ['startyear', 'year', 'month', `killturn`]); list($avaliableScout, $reason) = checkScoutAvailable($messageInfo, $general, $you, $startyear, $year); diff --git a/twe/func_file.php b/twe/func_file.php deleted file mode 100644 index 958e1402..00000000 --- a/twe/func_file.php +++ /dev/null @@ -1,24 +0,0 @@ -queryFirstRow('select `startyear`, `year`, `month` from `game` where `no` = 1'); - $startYear = toInt($game['startyear']); - $year = toInt($game['year']); - $month = toInt($game['month']); + $startYear = Util::toInt($game['startyear']); + $year = Util::toInt($game['year']); + $month = Util::toInt($game['month']); if($generalID && ($req->showMe || $req->neutralView)){ $city = $db->queryFirstRow( 'select `city`, `nation` from `general` where `no`=%i', $generalID); - $myCity = toInt($city['city']); - $myNation = toInt($city['nation']); + $myCity = Util::toInt($city['city']); + $myNation = Util::toInt($city['nation']); if(!$req->showMe){ $myCity = null; @@ -82,7 +82,7 @@ function getWorldMap($req){ if($myNation){ $spyList = $db->queryFirstField('select `spy` from `nation` where `nation`=%i', $myNation); - $spyList = array_map('toInt', explode("|", $spyList)); + $spyList = array_map('Util::toInt', explode("|", $spyList)); } else{ $spyList = []; @@ -91,17 +91,17 @@ function getWorldMap($req){ $nationList = []; foreach($db->query('select `nation`, `name`, `color`, `capital` from `nation`') as $row){ $nationList[] = [ - toInt($row['nation']), + Util::toInt($row['nation']), $row['name'], $row['color'], - toInt($row['capital']) + Util::toInt($row['capital']) ]; } if($myNation){ //굳이 타국 도시에 있는 아국 장수 리스트를 뽑을 이유가 없음. 일단 다 뽑자. $shownByGeneralList = - array_map('toInt', + array_map('Util::toInt', $db->queryFirstColumn('select distinct `city` from `general` where `nation` = %i', $myNation)); } @@ -112,7 +112,7 @@ function getWorldMap($req){ $cityList = []; foreach($db->query('select `city`, `level`, `state`, `nation`, `region`, `supply` from `city`') as $r){ $cityList[] = - array_map('toInt', [$r['city'], $r['level'], $r['state'], $r['nation'], $r['region'], $r['supply']]); + array_map('Util::toInt', [$r['city'], $r['level'], $r['state'], $r['nation'], $r['region'], $r['supply']]); } return [ diff --git a/twe/func_message.php b/twe/func_message.php index 5ce8745e..2cf6ab64 100644 --- a/twe/func_message.php +++ b/twe/func_message.php @@ -141,7 +141,7 @@ function sendRawMessage($msgType, $isSender, $mailbox, $src, $dest, $msg, $date, 'dest' => $dest['id'], 'time' => $date, 'valid_until' => $validUntil, - 'message' => json_encode(eraseNullValue([ + 'message' => json_encode(Util::eraseNullValue([ 'src' => $src, 'dest' =>$dest, 'text' => $msg, diff --git a/twe/j_adjust_icon.php b/twe/j_adjust_icon.php index bb64b66e..1b4c342e 100644 --- a/twe/j_adjust_icon.php +++ b/twe/j_adjust_icon.php @@ -1,4 +1,6 @@ false, diff --git a/twe/j_drop_settings.php b/twe/j_drop_settings.php index 3da1af66..b26a3666 100644 --- a/twe/j_drop_settings.php +++ b/twe/j_drop_settings.php @@ -1,4 +1,6 @@ query("DROP TABLE IF EXISTS history"); // 삭제 unlink(__DIR__."/d_setting/conf.php"); -delInDir("logs"); -delInDir("data/session"); +FileUtil::delInDir("logs"); +FileUtil::delInDir("data/session"); @unlink("data/connected.php"); diff --git a/twe/j_get_new_msg.php b/twe/j_get_new_msg.php index b272b06a..4989b6a0 100644 --- a/twe/j_get_new_msg.php +++ b/twe/j_get_new_msg.php @@ -1,4 +1,6 @@ queryFirstField( diff --git a/twe/j_get_scenario_map.php b/twe/j_get_scenario_map.php index b009aa32..ec3034ee 100644 --- a/twe/j_get_scenario_map.php +++ b/twe/j_get_scenario_map.php @@ -1,4 +1,6 @@ userGrade < 5){ ]); } -$scenarioIdx = toInt(Util::array_get($_GET['scenarioIdx'])); +$scenarioIdx = Util::toInt(Util::array_get($_GET['scenarioIdx'])); if($scenarioIdx === null){ Json::die([ diff --git a/twe/j_init_scenario.php b/twe/j_init_scenario.php index 10cfa58d..7c21455e 100644 --- a/twe/j_init_scenario.php +++ b/twe/j_init_scenario.php @@ -1,4 +1,6 @@ false, 'showMe' => true ]; -$post = array_merge($defaultPost, parseJsonPost()); +$post = array_merge($defaultPost, WebUtil::parseJsonPost()); if($post['year']){ @@ -29,8 +29,8 @@ if($post['year']){ ]); } - $post['year'] = toInt($post['year']); - $post['month'] = toInt($post['month']); + $post['year'] = Util::toInt($post['year']); + $post['month'] = Util::toInt($post['month']); } else{ $post['year'] = null; diff --git a/twe/j_msg_contact_list.php b/twe/j_msg_contact_list.php index 3f17e8c1..52761512 100644 --- a/twe/j_msg_contact_list.php +++ b/twe/j_msg_contact_list.php @@ -1,4 +1,6 @@ queryFirstField("select count(city) from city where level>=5 and level<=6 and nation=0")); + $citycount = Util::toInt($db->queryFirstField("select count(city) from city where level>=5 and level<=6 and nation=0")); // 공백지에서만 태어나게 if($citycount > 0) { - $city = toInt($db->queryFirstField("select city from city where level>=5 and level<=6 and nation=0 order by rand() limit 0,1")); + $city = Util::toInt($db->queryFirstField("select city from city where level>=5 and level<=6 and nation=0 order by rand() limit 0,1")); } else { - $city = toInt($db->queryFirstField("select city from city where level>=5 and level<=6 order by rand() limit 0,1")); + $city = Util::toInt($db->queryFirstField("select city from city where level>=5 and level<=6 order by rand() limit 0,1")); } $total = rand() % 6; diff --git a/twe/lib.php b/twe/lib.php index b0cd8e5d..5e0f3021 100644 --- a/twe/lib.php +++ b/twe/lib.php @@ -44,7 +44,7 @@ require_once(__dir__.'/d_setting/conf.php'); // 각종 변수 define('STEP_LOG', true); define('PROCESS_LOG', true); -$_startTime = getMicroTime(); +$_startTime = microtime(true); $_ver = "서비스중"; $x_version = "삼국지 모의전투 PHP HideD v0.1"; $x_banner = "KOEI의 이미지를 사용, 응용하였습니다 / 제작 : 유기체(jwh1807@gmail.com), HideD(hided62@gmail.com)"; @@ -153,15 +153,6 @@ function Error($message, $url="") { exit; } -function SetHeaderNoCache(){ - if(!headers_sent()) { - header('Expires: Wed, 01 Jan 2014 00:00:00 GMT'); - header('Cache-Control: no-store, no-cache, must-revalidate'); - header('Cache-Control: post-check=0, pre-check=0', FALSE); - header('Pragma: no-cache'); - } -} - // 게시판의 생성유무 검사 function isTable($connect, $str, $dbname='') { if(!$dbname) { @@ -181,67 +172,16 @@ function isTable($connect, $str, $dbname='') { return 0; } -// 빈문자열 경우 1을 리턴 -function isblank($str) { - //FIXME: 리턴 값은 boolean이 더 적절하다. - $temp=str_replace(" ","",$str); - $temp=str_replace("\n","",$temp); - $temp=strip_tags($temp); - $temp=str_replace(" ","",$temp); - $temp=str_replace(" ","",$temp); - if(preg_match("/[^[:space:]]/i",$temp)) return 0; - return 1; -} - -function Debug($str) { - echo ""; -} - function MessageBox($str) { echo ""; } -function getmicrotime() { - $microtimestmp = explode(' ', microtime()); - return $microtimestmp[0] + $microtimestmp[1]; -} - function PrintElapsedTime() { global $_startTime; - $_endTime = round(getMicroTime() - $_startTime, 3); + $_endTime = round(microtime(true) - $_startTime, 3); echo "
경과시간 : {$_endTime}초
"; } -/** - * '비교적' 안전한 int 변환 - * null -> null - * int -> int - * float -> int - * numeric(int, float) 포함 -> int - * 기타 -> 예외처리 - * - * @return int|null - */ -function toInt($val, $force=false){ - if($val === null){ - return null; - } - if(is_int($val)){ - return $val; - } - if(is_numeric($val)){ - return intval($val);// - } - if($val === 'null' || $val === 'null'){ - return null; - } - - if($force){ - return intval($val); - } - throw new InvalidArgumentException('올바르지 않은 타입형 :'.$val); -} - function LogText($prefix, $variable){ $fp = fopen('logs/dbg_logs.txt', 'a+'); if($fp == false){ @@ -255,151 +195,6 @@ function LogText($prefix, $variable){ fclose($fp); } -function dict_map($callback, $dict){ - $result = []; - foreach(array_keys($dict) as $key){ - $result[$key] = ($callback)($dict[$key]); - } - return $result; -} - -function ArrayToDict($arr, $keyName){ - $result = []; - - foreach($arr as $obj){ - $key = $obj[$keyName]; - $result[$key] = $obj; - } - - return $result; -} - -function dictToArray($dict, $keys){ - $result = []; - - foreach($keys as $key){ - $result[] = Util::array_get($dict[$key], null); - } - return $result; -} - -function isDict(&$array){ - if(!is_array($array)){ - //배열이 아니면 dictionary 조차 아님. - return false; - } - $idx = 0; - $jmp = 0; - foreach ($arr as $key=>&$value) { - if(is_string($key)){ - return true; - } - $jmp = $key - $idx - 1; - $idx = $key; - } - - if ($jmp * 5 >= count($array)){ - //빈칸이 많으면 dictionary인걸로. - return true; - } - else{ - return false; - } - -} - -function eraseNullValue($dict, $depth=512){ - //TODO:Test 추가 - if($dict === null){ - return null; - } - - if(is_array($dict) && empty($dict)){ - return null; - } - - if($depth <= 0){ - return $dict; - } - - foreach ($arr as $key=>$value) { - if($value === null){ - unset($dict[$key]); - } - else if(isDict($value)){ - $newValue = eraseNullKey($value, $depth - 1); - if($newValue === null){ - unset($dict[$key]); - } - else{ - $dict[$key] = $newValue; - } - - } - } - - - - return $dict; -} - -function parseJsonPost(){ - // http://thisinterestsme.com/receiving-json-post-data-via-php/ - // http://thisinterestsme.com/php-json-error-handling/ - if(strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0){ - throw new Exception('Request method must be POST!'); - } - - //Make sure that the content type of the POST request has been set to application/json - $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : ''; - if(strcasecmp($contentType, 'application/json') != 0){ - throw new Exception('Content type must be: application/json'); - } - - //Receive the RAW post data. - $content = trim(file_get_contents("php://input")); - - //Attempt to decode the incoming RAW post data from JSON. - $decoded = json_decode($content, true); - - - $jsonError = json_last_error(); - - //In some cases, this will happen. - if(is_null($decoded) && $jsonError == JSON_ERROR_NONE){ - throw new Exception('Could not decode JSON!'); - } - - //If an error exists. - if($jsonError != JSON_ERROR_NONE){ - $error = 'Could not decode JSON! '; - - //Use a switch statement to figure out the exact error. - switch($jsonError){ - case JSON_ERROR_DEPTH: - $error .= 'Maximum depth exceeded!'; - break; - case JSON_ERROR_STATE_MISMATCH: - $error .= 'Underflow or the modes mismatch!'; - break; - case JSON_ERROR_CTRL_CHAR: - $error .= 'Unexpected control character found'; - break; - case JSON_ERROR_SYNTAX: - $error .= 'Malformed JSON'; - break; - case JSON_ERROR_UTF8: - $error .= 'Malformed UTF-8 characters found!'; - break; - default: - $error .= 'Unknown error!'; - break; - } - throw new Exception($error); - } - - return $decoded; -} if(isset($_POST) && count($_POST) > 0){ LogText($_SERVER['REQUEST_URI'], $_POST); diff --git a/twe/login_process.php b/twe/login_process.php index ec5f2d36..baa0471b 100644 --- a/twe/login_process.php +++ b/twe/login_process.php @@ -37,7 +37,7 @@ case 3: MessageBox("절대 1계정만 사용하십시오! {$me['killturn']}시간 후 재등록 가능합니다."); break; } -$_SESSION[getServPrefix().'p_no'] = toInt($me['no']); +$_SESSION[getServPrefix().'p_no'] = Util::toInt($me['no']); $_SESSION[getServPrefix().'p_name'] = $me['name']; $_SESSION['p_time'] = time(); diff --git a/twe/old/j_old_install.php b/twe/old/j_old_install.php index 82c6b4cc..4cd2a5b2 100644 --- a/twe/old/j_old_install.php +++ b/twe/old/j_old_install.php @@ -27,7 +27,7 @@ $connect = MYDB_connect($hostname,$user_id,$password) or Error("MySQL-DB Connect if(MYDB_error($connect)) Error(__LINE__.MYDB_error($connect),""); MYDB_select_db($dbname, $connect) or Error("MySQL-DB Select
Error!!!",""); -delInDir("logs"); +FileUtil::delInDir("logs"); @unlink("data/connected.php"); // 관리자 테이블 삭제 diff --git a/twe/reset.php b/twe/reset.php index 8546ae3e..241a71d3 100644 --- a/twe/reset.php +++ b/twe/reset.php @@ -23,8 +23,8 @@ $connect = @MYDB_connect($hostname,$user_id,$password) or Error("MySQL-DB Connec if(MYDB_error($connect)) Error(__LINE__.MYDB_error($connect),""); MYDB_select_db($dbname, $connect ) or Error("MySQL-DB Select
Error!!!",""); -delInDir("logs"); -delInDir("data/session"); +FileUtil::delInDir("logs"); +FileUtil::delInDir("data/session"); @unlink("data/connected.php");