많은 유틸리티 함수를 Util, FileUtil, WebUtil로 이동

This commit is contained in:
2018-03-24 22:03:54 +09:00
parent b5cba27df9
commit 157ecdbf2a
36 changed files with 364 additions and 517 deletions
+4 -175
View File
@@ -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;
}
+1 -1
View File
@@ -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',[
+1 -1
View File
@@ -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,
+3 -3
View File
@@ -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",
+1 -1
View File
@@ -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);
+51
View File
@@ -0,0 +1,51 @@
<?php
namespace sammo;
class FileUtil{
public static function delInDir(string $dir) {
$handle = opendir($dir);
if($handle !== false){
while(false !== ($FolderOrFile = readdir($handle))) {
if ($FolderOrFile == "." || $FolderOrFile == "..") {
continue;
}
$filepath = sprintf('%s/%s', $dir, $FolderOrFile);
if (is_dir($filepath)) {
FileUtil::delInDir($filepath);
} // recursive
else {
@unlink($filepath);
}
}
closedir($handle);
}
return true;
}
function delExpiredInDir($dir, $t) {
$handle = opendir($dir);
if ($handle !== false) {
while (false !== ($FolderOrFile = readdir($handle))) {
if ($FolderOrFile == "." || $FolderOrFile == "..") {
continue;
}
$filepath = sprintf('%s/%s', $dir, $FolderOrFile);
if (is_dir($filepath)) {
delExpiredInDir($filepath, $t);
} // recursive
else {
$mt = filemtime($filepath);
if ($mt < $t) {
@unlink($filepath);
}
}
}
closedir($handle);
}
return $success;
}
}
+1 -10
View File
@@ -2,15 +2,6 @@
namespace sammo;
class Json{
private static 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');
}
}
public static function encode($value, $pretty = false){
if($pretty){
$flag = JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT;
@@ -27,7 +18,7 @@ class Json{
public static function die($value, $noCache = true, $pretty = false, $die = true){
if($noCache){
self::setHeaderNoCache();
WebUtil::setHeaderNoCache();
}
header('Content-Type: application/json');
+169
View File
@@ -2,4 +2,173 @@
namespace sammo;
class Util extends \utilphp\util{
public static function hashPassword($salt, $password){
return hash('sha512', $salt.$password.$salt);
}
/**
* 변환할 내용이 _tK_$key_ 형태로 작성된 단순한 템플릿 파일을 이용하여 결과물을 생성해주는 함수.
*/
public static 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
*/
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;
}
};
+71
View File
@@ -0,0 +1,71 @@
<?php
namespace sammo;
class WebUtil{
public static 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');
}
}
public static 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;
}
}
+1 -1
View File
@@ -2,7 +2,7 @@
require('../twe/lib.php');
$jsonPost = parseJsonPost();
$jsonPost = WebUtil::parseJsonPost();
echo json_encode([
'result'=>true,
+2 -2
View File
@@ -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;
+1 -1
View File
@@ -2,7 +2,7 @@
require('../twe/lib.php');
$jsonPost = parseJsonPost();
$jsonPost = WebUtil::parseJsonPost();
echo json_encode([
'result'=>true,
+2 -3
View File
@@ -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);
+1 -1
View File
@@ -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);
-24
View File
@@ -1,24 +0,0 @@
<?php
function delInDir($dir) {
$handle = opendir($dir);
if($handle !== false){
while(false !== ($FolderOrFile = readdir($handle))) {
if ($FolderOrFile == "." || $FolderOrFile == "..") {
continue;
}
$filepath = sprintf('%s/%s', $dir, $FolderOrFile);
if (is_dir($filepath)) {
delInDir($filepath);
} // recursive
else {
@unlink($filepath);
}
}
}
closedir($handle);
// if(rmdir($dir)) {
// $success = true;
// }
return true;
}
+10 -10
View File
@@ -55,17 +55,17 @@ function getWorldMap($req){
$db = getDB();
$game = $db->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 [
+1 -1
View File
@@ -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,
+2
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
include('lib.php');
include('func.php');
+2
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
include('lib.php');
include('func.php');
+2 -58
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
require(__dir__.'/../vendor/autoload.php');
require(__dir__.'/../d_setting/conf.php');
@@ -9,64 +11,6 @@ require(__dir__.'/../d_setting/conf.php');
* 이 파일만 예외적으로 lib.php, func.php를 참조하지 않고 독자적으로 동작함.
*/
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(file_exist(__dir__.'/d_setting/conf.php')){
Json::die([
'result'=>false,
+4 -2
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
include "lib.php";
include "func.php";
@@ -34,7 +36,7 @@ $db->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");
+4 -2
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
include('lib.php');
include('func.php');
@@ -8,9 +10,9 @@ $generalID = getGeneralID();
session_write_close(); // 이제 세션 안 쓴다
$jsonPost = parseJsonPost();
$jsonPost = WebUtil::parseJsonPost();
$reqSequence = toInt(Util::array_get($jsonPost['sequence'], 0));
$reqSequence = Util::toInt(Util::array_get($jsonPost['sequence'], 0));
$nationID = getDB()->queryFirstField(
+3 -1
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
require(__DIR__.'/../f_func/func.php');
require('func_install.php');
@@ -12,7 +14,7 @@ if($session->userGrade < 5){
]);
}
$scenarioIdx = toInt(Util::array_get($_GET['scenarioIdx']));
$scenarioIdx = Util::toInt(Util::array_get($_GET['scenarioIdx']));
if($scenarioIdx === null){
Json::die([
+2
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
include "lib.php";
include "func.php";
+2
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
include "lib.php";
include "func.php";
include "schema.php";
+3 -3
View File
@@ -18,7 +18,7 @@ $defaultPost = [
'neutralView' => 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;
+2
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
include('lib.php');
include('func.php');
+4 -2
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
include 'lib.php';
include 'func.php';
@@ -17,9 +19,9 @@ if (!$generalID) {
session_write_close(); // 이제 세션 안 쓴다
$jsonPost = parseJsonPost();
$jsonPost = WebUtil::parseJsonPost();
$msgID = toInt(Util::array_get($jsonPost['msgID'], null), false);
$msgID = Util::toInt(Util::array_get($jsonPost['msgID'], null), false);
$msgResponse = Util::array_get($jsonPost['response'], null);
if ($msgID === null || !is_bool($msgResponse)) {
+1 -1
View File
@@ -15,7 +15,7 @@ include 'func.php';
//읽기 전용이다. 빠르게 세션 끝내자
session_write_close();
$post = parseJsonPost();
$post = WebUtil::parseJsonPost();
if(!isset($post['genlist']) || !isset($post['msg'])){
Json::die([
+2
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
include "lib.php";
include "func.php";
+2
View File
@@ -1,4 +1,6 @@
<?php
namespace sammo;
include "lib.php";
include "func.php";
+3 -3
View File
@@ -126,13 +126,13 @@ if($id_num) {
}
//중, 소 공백지 개수
$citycount = toInt($db->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;
+2 -207
View File
@@ -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("&nbsp;","",$temp);
$temp=str_replace(" ","",$temp);
if(preg_match("/[^[:space:]]/i",$temp)) return 0;
return 1;
}
function Debug($str) {
echo "<script>alert('$str');</script>";
}
function MessageBox($str) {
echo "<script>alert('$str');</script>";
}
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 "<table width=1000 align=center style=font-size:10;><tr><td align=right>경과시간 : {$_endTime}초</td></tr></table>";
}
/**
* '비교적' 안전한 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);
+1 -1
View File
@@ -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();
+1 -1
View File
@@ -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<br>Error!!!","");
delInDir("logs");
FileUtil::delInDir("logs");
@unlink("data/connected.php");
// 관리자 테이블 삭제
+2 -2
View File
@@ -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<br>Error!!!","");
delInDir("logs");
delInDir("data/session");
FileUtil::delInDir("logs");
FileUtil::delInDir("data/session");
@unlink("data/connected.php");