PSR에 맞게 수정

This commit is contained in:
2018-04-06 19:03:35 +09:00
parent 37339b91b0
commit 2bce82c73e
18 changed files with 584 additions and 481 deletions
+1
View File
@@ -23,6 +23,7 @@ class RootDB{
* DB 객체 생성 * DB 객체 생성
* *
* @return \MeekroDB * @return \MeekroDB
* @suppress PhanTypeMismatchProperty
*/ */
public static function db(){ public static function db(){
if(self::$uDB === null){ if(self::$uDB === null){
+1
View File
@@ -21,6 +21,7 @@ class DB{
* DB 객체 생성 * DB 객체 생성
* *
* @return \MeekroDB * @return \MeekroDB
* @suppress PhanTypeMismatchProperty
*/ */
public static function db(){ public static function db(){
if(self::$uDB === null){ if(self::$uDB === null){
+2 -2
View File
@@ -92,7 +92,7 @@ function getSpecial($leader, $power, $intel) {
$type = array(20, 31); $type = array(20, 31);
$special = $type[array_rand($type)]; $special = $type[array_rand($type)];
// 귀모는 50% * 5% = 2.5% // 귀모는 50% * 5% = 2.5%
if($special == 31 && randBool(0.95)) { if($special == 31 && Util::randBool(0.95)) {
$special = 20; $special = 20;
} }
//무장 //무장
@@ -100,7 +100,7 @@ function getSpecial($leader, $power, $intel) {
$type = array(10, 11, 12, 31); $type = array(10, 11, 12, 31);
$special = $type[array_rand($type)]; $special = $type[array_rand($type)];
// 귀모는 그중에 25% * 10% = 2.5% // 귀모는 그중에 25% * 10% = 2.5%
if($special == 31 && randBool(0.9)) { if($special == 31 && Util::randBool(0.9)) {
$type = array(10, 11, 12); $type = array(10, 11, 12);
$special = $type[array_rand($type)]; $special = $type[array_rand($type)];
} }
-1
View File
@@ -13,7 +13,6 @@ $session = Session::getInstance();
use \kakao\KakaoKey as KakaoKey; use \kakao\KakaoKey as KakaoKey;
if ($session->isLoggedIn()) { if ($session->isLoggedIn()) {
header('Location:i_entrance/entrance.php'); header('Location:i_entrance/entrance.php');
die(); die();
+37 -25
View File
@@ -2,7 +2,8 @@
namespace kakao; namespace kakao;
if (class_exists('\\kakao\\KakaoKey') === false) { if (class_exists('\\kakao\\KakaoKey') === false) {
class KakaoKey{ class KakaoKey
{
const REST_KEY = ''; const REST_KEY = '';
const ADMIN_KEY = ''; const ADMIN_KEY = '';
const REDIRECT_URI = ''; const REDIRECT_URI = '';
@@ -68,8 +69,8 @@ class Kakao_REST_API_Helper
private $access_token; private $access_token;
private $admin_key; private $admin_key;
public function __construct($access_token = '') { public function __construct($access_token = '')
{
if ($access_token) { if ($access_token) {
$this->access_token = $access_token; $this->access_token = $access_token;
} }
@@ -102,17 +103,13 @@ class Kakao_REST_API_Helper
CURLOPT_SSLVERSION => 1, CURLOPT_SSLVERSION => 1,
); );
if ($api_path != '/oauth/token') if ($api_path != '/oauth/token') {
{
if (in_array($api_path, self::$admin_apis)) { if (in_array($api_path, self::$admin_apis)) {
if (!$this->admin_key) { if (!$this->admin_key) {
throw new Exception('admin key should not be null or empty.'); throw new Exception('admin key should not be null or empty.');
} }
$headers = array('Authorization: KakaoAK ' . $this->admin_key); $headers = array('Authorization: KakaoAK ' . $this->admin_key);
} else { } else {
if (!$this->access_token) { if (!$this->access_token) {
throw new Exception('access token should not be null or empty.'); throw new Exception('access token should not be null or empty.');
} }
@@ -146,11 +143,13 @@ class Kakao_REST_API_Helper
} }
} }
public function set_access_token($access_token) { public function set_access_token($access_token)
{
$this->access_token = $access_token; $this->access_token = $access_token;
} }
public function set_admin_key($admin_key) { public function set_admin_key($admin_key)
{
$this->admin_key = $admin_key; $this->admin_key = $admin_key;
} }
@@ -158,11 +157,13 @@ class Kakao_REST_API_Helper
// User Management // User Management
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
private function _create_or_refresh_access_token($params) { private function _create_or_refresh_access_token($params)
{
return $this->request(User_Management_Path::$TOKEN, $params, 'POST'); return $this->request(User_Management_Path::$TOKEN, $params, 'POST');
} }
public function create_access_token($authorization_code){ public function create_access_token($authorization_code)
{
$this->AUTHORIZATION_CODE = $authorization_code; $this->AUTHORIZATION_CODE = $authorization_code;
$params = [ $params = [
'grant_type'=>'authorization_code', 'grant_type'=>'authorization_code',
@@ -175,7 +176,8 @@ class Kakao_REST_API_Helper
return $result; return $result;
} }
public function refresh_access_token($refresh_token){ public function refresh_access_token($refresh_token)
{
$params = [ $params = [
'grant_type'=>'refresh_token', 'grant_type'=>'refresh_token',
'client_id'=>$this->REST_KEY, 'client_id'=>$this->REST_KEY,
@@ -187,34 +189,41 @@ class Kakao_REST_API_Helper
return $result; return $result;
} }
public function signup() { public function signup()
{
return $this->request(User_Management_Path::$SIGNUP); return $this->request(User_Management_Path::$SIGNUP);
} }
public function unlink() { public function unlink()
{
return $this->request(User_Management_Path::$UNLINK); return $this->request(User_Management_Path::$UNLINK);
} }
public function logout() { public function logout()
{
return $this->request(User_Management_Path::$UNLINK); return $this->request(User_Management_Path::$UNLINK);
} }
public function me() { public function me()
{
return $this->request(User_Management_Path::$ME); return $this->request(User_Management_Path::$ME);
} }
public function meWithEmail(){ public function meWithEmail()
{
$params = [ $params = [
'propertyKeys'=>'["id","kaacount_email","kaccount_email_verified"]' '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) { public function update_profile($params)
{
return $this->request(User_Management_Path::$UPDATE_PROFILE, $params, 'POST'); return $this->request(User_Management_Path::$UPDATE_PROFILE, $params, 'POST');
} }
public function user_ids() { public function user_ids()
{
return $this->request(User_Management_Path::$USER_IDS); return $this->request(User_Management_Path::$USER_IDS);
} }
@@ -222,11 +231,13 @@ class Kakao_REST_API_Helper
// Kakao Story // Kakao Story
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
public function isstoryuser() { public function isstoryuser()
{
return $this->request(Story_Path::$ISSTORYUSER); return $this->request(Story_Path::$ISSTORYUSER);
} }
public function story_profile() { public function story_profile()
{
return $this->request(Story_Path::$PROFILE); return $this->request(Story_Path::$PROFILE);
} }
@@ -234,12 +245,13 @@ class Kakao_REST_API_Helper
// Kakao Talk // Kakao Talk
/////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////
public function talk_profile() { public function talk_profile()
{
return $this->request(Talk_Path::$TALK_PROFILE); return $this->request(Talk_Path::$TALK_PROFILE);
} }
public function talk_to_me_default($req){ public function talk_to_me_default($req)
{
$params = [ $params = [
'template_object' => json_encode($req) 'template_object' => json_encode($req)
]; ];
+8 -4
View File
@@ -1,7 +1,8 @@
<?php <?php
namespace sammo; namespace sammo;
class AppConf{ class AppConf
{
private static $serverList = null; private static $serverList = null;
/** /**
@@ -9,7 +10,8 @@ class AppConf{
* *
* @return \sammo\Setting[] * @return \sammo\Setting[]
*/ */
public static function getList(){ public static function getList()
{
if (self::$serverList === null) { if (self::$serverList === null) {
self::$serverList = [ self::$serverList = [
'che'=>new Setting(ROOT.'/che', '체', 'white'), 'che'=>new Setting(ROOT.'/che', '체', 'white'),
@@ -27,7 +29,8 @@ class AppConf{
* *
* @return \MeekroDB * @return \MeekroDB
*/ */
public static function requireRootDB(){ public static function requireRootDB()
{
if (!class_exists('\\sammo\\RootDB')) { if (!class_exists('\\sammo\\RootDB')) {
trigger_error('RootDB.php가 설정되지 않았습니다.', E_USER_ERROR); trigger_error('RootDB.php가 설정되지 않았습니다.', E_USER_ERROR);
die(); die();
@@ -40,7 +43,8 @@ class AppConf{
* *
* @return \MeekroDB * @return \MeekroDB
*/ */
public static function requireDB(){ public static function requireDB()
{
if (!class_exists('\\sammo\\DB')) { if (!class_exists('\\sammo\\DB')) {
trigger_error('DB.php가 설정되지 않았습니다.', E_USER_ERROR); trigger_error('DB.php가 설정되지 않았습니다.', E_USER_ERROR);
die(); die();
+2 -2
View File
@@ -1,6 +1,6 @@
<?php <?php
namespace sammo; namespace sammo;
class FileTail extends \PhpExtended\Tail\Tail{ class FileTail extends \PhpExtended\Tail\Tail
{
}; };
+6 -3
View File
@@ -1,8 +1,10 @@
<?php <?php
namespace sammo; namespace sammo;
class FileUtil{ class FileUtil
public static function delInDir(string $dir) { {
public static function delInDir(string $dir)
{
$handle = opendir($dir); $handle = opendir($dir);
if ($handle !== false) { if ($handle !== false) {
while (false !== ($FolderOrFile = readdir($handle))) { while (false !== ($FolderOrFile = readdir($handle))) {
@@ -27,7 +29,8 @@ class FileUtil{
return true; return true;
} }
function delExpiredInDir($dir, $t) { public function delExpiredInDir($dir, $t)
{
$handle = opendir($dir); $handle = opendir($dir);
if ($handle !== false) { if ($handle !== false) {
while (false !== ($FolderOrFile = readdir($handle))) { while (false !== ($FolderOrFile = readdir($handle))) {
+8 -4
View File
@@ -1,12 +1,14 @@
<?php <?php
namespace sammo; namespace sammo;
class Json{ class Json
{
const PRETTY = 1; const PRETTY = 1;
const DELETE_NULL = 2; const DELETE_NULL = 2;
const NO_CACHE = 4; const NO_CACHE = 4;
public static function encode($value, $flag = 0){ public static function encode($value, $flag = 0)
{
$rawFlag = JSON_UNESCAPED_UNICODE; $rawFlag = JSON_UNESCAPED_UNICODE;
if ($flag & static::PRETTY) { if ($flag & static::PRETTY) {
$rawFlag |= JSON_PRETTY_PRINT; $rawFlag |= JSON_PRETTY_PRINT;
@@ -17,11 +19,13 @@ class Json{
return json_encode($value, $rawFlag); return json_encode($value, $rawFlag);
} }
public static function decode($value){ public static function decode($value)
{
return json_decode($value, true); return json_decode($value, true);
} }
public static function die($value, $flag = self::NO_CACHE){ public static function die($value, $flag = self::NO_CACHE)
{
//NOTE: REST 형식에 맞게, ok(), fail()로 쪼개는게 낫지 않을까 생각해봄. //NOTE: REST 형식에 맞게, ok(), fail()로 쪼개는게 낫지 않을까 생각해봄.
if ($flag & static::NO_CACHE) { if ($flag & static::NO_CACHE) {
WebUtil::setHeaderNoCache(); WebUtil::setHeaderNoCache();
+30 -15
View File
@@ -1,27 +1,37 @@
<?php <?php
namespace sammo; namespace sammo;
class Lock { class Lock
{
private static $l = ROOT.'/d_log/lock.txt'; private static $l = ROOT.'/d_log/lock.txt';
public static function Busy() { public static function Busy()
{
$fp = fopen(Lock::$l, 'r'); $fp = fopen(Lock::$l, 'r');
$lock = fread($fp, 1); $lock = fread($fp, 1);
fclose($fp); fclose($fp);
if($lock == 1) return true; if ($lock == 1) {
else return false; return true;
} else {
return false;
}
} }
private static function LockFile() { private static function LockFile()
{
$fp = fopen(Lock::$l, 'r'); $fp = fopen(Lock::$l, 'r');
$lock = fread($fp, 1); $lock = fread($fp, 1);
fclose($fp); fclose($fp);
if($lock == 1) return false; if ($lock == 1) {
return false;
}
$fp = fopen(Lock::$l, 'w'); $fp = fopen(Lock::$l, 'w');
if(!flock($fp, LOCK_EX)) { return false; } if (!flock($fp, LOCK_EX)) {
return false;
}
fwrite($fp, '1'); fwrite($fp, '1');
fclose($fp); fclose($fp);
flock($fp, LOCK_UN); flock($fp, LOCK_UN);
@@ -29,15 +39,20 @@ class Lock {
return true; return true;
} }
private static function UnlockFile() { private static function UnlockFile()
{
$fp = fopen(Lock::$l, 'r'); $fp = fopen(Lock::$l, 'r');
$lock = fread($fp, 1); $lock = fread($fp, 1);
fclose($fp); fclose($fp);
if($lock == 0) return false; if ($lock == 0) {
return false;
}
$fp = fopen(Lock::$l, 'w'); $fp = fopen(Lock::$l, 'w');
if(!flock($fp, LOCK_EX)) { return false; } if (!flock($fp, LOCK_EX)) {
return false;
}
fwrite($fp, '0'); fwrite($fp, '0');
fclose($fp); fclose($fp);
flock($fp, LOCK_UN); flock($fp, LOCK_UN);
@@ -45,11 +60,12 @@ class Lock {
return true; return true;
} }
public static function Lock() { public static function Lock()
{
/* /*
// 키 생성 // 키 생성
$key = fileinode(Lock::$l); $key = fileinode(Lock::$l);
// 뮤텍스 획득 // 뮤 스 획득
$mutex = sem_get($key); $mutex = sem_get($key);
// 락 획득 // 락 획득
sem_acquire($mutex); sem_acquire($mutex);
@@ -58,7 +74,8 @@ class Lock {
return Lock::LockFile(); return Lock::LockFile();
} }
public static function Unlock() { public static function Unlock()
{
// 파일에 잠금 풀기 // 파일에 잠금 풀기
$res = Lock::UnlockFile(); $res = Lock::UnlockFile();
/* /*
@@ -68,5 +85,3 @@ class Lock {
return $res; return $res;
} }
} }
+44 -32
View File
@@ -9,8 +9,8 @@ namespace sammo;
* @property int $userGrade 유저등급 * @property int $userGrade 유저등급
* @property string $ip IP * @property string $ip IP
*/ */
class Session { class Session
{
const PROTECTED_NAMES = [ const PROTECTED_NAMES = [
'ip'=>true, 'ip'=>true,
'time'=>true, 'time'=>true,
@@ -31,7 +31,8 @@ class Session {
private $writeClosed = false; private $writeClosed = false;
private $sessionID = null; private $sessionID = null;
public static function getInstance(): Session{ public static function getInstance(): Session
{
static $inst = null; static $inst = null;
if ($inst === null) { if ($inst === null) {
$inst = new Session(); $inst = new Session();
@@ -39,7 +40,8 @@ class Session {
return $inst; return $inst;
} }
public function restart(): Session{ public function restart(): Session
{
//NOTE: logout 프로세스는 아예 세션을 날려버리기도 하므로, 항상 안전하게 session_restart가 가능함을 보장하지 않음. //NOTE: logout 프로세스는 아예 세션을 날려버리기도 하므로, 항상 안전하게 session_restart가 가능함을 보장하지 않음.
ini_set('session.use_only_cookies', false); ini_set('session.use_only_cookies', false);
ini_set('session.use_cookies', false); ini_set('session.use_cookies', false);
@@ -50,7 +52,8 @@ class Session {
return $this; return $this;
} }
private static function die($result){ private static function die($result)
{
if (is_string($result)) { if (is_string($result)) {
header('Location:'.$result); header('Location:'.$result);
die(); die();
@@ -68,7 +71,8 @@ class Session {
Json::die($jsonResult); Json::die($jsonResult);
} }
public static function requireLogin($result = '..'): Session{ public static function requireLogin($result = '..'): Session
{
$session = Session::getInstance(); $session = Session::getInstance();
if ($session->isLoggedIn()) { if ($session->isLoggedIn()) {
return $session; return $session;
@@ -77,7 +81,8 @@ class Session {
static::die($result); static::die($result);
} }
public static function requireGameLogin($result = '..'): Session{ public static function requireGameLogin($result = '..'): Session
{
$session = Session::requireLogin($result)->loginGame(); $session = Session::requireLogin($result)->loginGame();
if ($session->generalID) { if ($session->generalID) {
@@ -87,7 +92,8 @@ class Session {
static::die($result); static::die($result);
} }
public function __construct() { public function __construct()
{
//session_cache_limiter('nocache, must_revalidate'); //session_cache_limiter('nocache, must_revalidate');
// 세션 변수의 등록 // 세션 변수의 등록
@@ -104,7 +110,8 @@ class Session {
} }
} }
public function setReadOnly(): Session{ public function setReadOnly(): Session
{
if (!$this->writeClosed) { if (!$this->writeClosed) {
session_write_close(); session_write_close();
$this->writeClosed = true; $this->writeClosed = true;
@@ -112,7 +119,8 @@ class Session {
return $this; return $this;
} }
public function __set(string $name, $value){ public function __set(string $name, $value)
{
if (key_exists($name, $this->PROTECED_NAMES)) { if (key_exists($name, $this->PROTECED_NAMES)) {
trigger_error("{$name}은 외부에서 쓰기 금지된 Session 변수입니다.", E_USER_NOTICE); trigger_error("{$name}은 외부에서 쓰기 금지된 Session 변수입니다.", E_USER_NOTICE);
return; return;
@@ -121,16 +129,17 @@ class Session {
$this->set($name, $value); $this->set($name, $value);
} }
private function set(string $name, $value){ private function set(string $name, $value)
{
if ($value === null) { if ($value === null) {
unset($_SESSION[$name]); unset($_SESSION[$name]);
} } else {
else{
$_SESSION[$name] = $value; $_SESSION[$name] = $value;
} }
} }
public function __get(string $name){ public function __get(string $name)
{
if ($name == 'generalID') { if ($name == 'generalID') {
return $this->get(UniqueConst::$serverID.static::GAME_KEY_GENERAL_ID); return $this->get(UniqueConst::$serverID.static::GAME_KEY_GENERAL_ID);
} }
@@ -140,11 +149,13 @@ class Session {
return $this->get($name); return $this->get($name);
} }
private function get(string $name){ private function get(string $name)
{
return Util::array_get($_SESSION[$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('userID', $userID);
$this->set('userName', $userName); $this->set('userName', $userName);
$this->set('ip', Util::get_client_ip(true)); $this->set('ip', Util::get_client_ip(true));
@@ -155,7 +166,8 @@ class Session {
} }
public function logout(): Session { public function logout(): Session
{
if ($this->writeClosed) { if ($this->writeClosed) {
$this->restart(); $this->restart();
} }
@@ -170,7 +182,8 @@ class Session {
return $this; return $this;
} }
public function loginGame(&$result = null): Session{ public function loginGame(&$result = null): Session
{
$userID = $this->userID; $userID = $this->userID;
if (!$userID) { if (!$userID) {
if ($result !== null) { if ($result !== null) {
@@ -240,7 +253,6 @@ class Session {
} }
return $this; return $this;
} }
} }
$db->update('general', [ $db->update('general', [
@@ -256,7 +268,8 @@ class Session {
return $this; return $this;
} }
public function logoutGame(): Session{ public function logoutGame(): Session
{
if ($this->writeClosed) { if ($this->writeClosed) {
$this->restart(); $this->restart();
} }
@@ -273,11 +286,11 @@ class Session {
* 로그인 유저의 전역 grade를 받아옴 * 로그인 유저의 전역 grade를 받아옴
* @return int|null * @return int|null
*/ */
public static function getUserGrade(bool $requireLogin = false, string $exitPath = '..'){ public static function getUserGrade(bool $requireLogin = false, string $exitPath = '..')
{
if ($requireLogin) { if ($requireLogin) {
$obj = self::requireLogin($exitPath); $obj = self::requireLogin($exitPath);
} } else {
else{
$obj = self::getInstance(); $obj = self::getInstance();
} }
@@ -289,28 +302,27 @@ class Session {
* *
* @return int|null * @return int|null
*/ */
public static function getUserID(bool $requireLogin = false, string $exitPath = '..'){ public static function getUserID(bool $requireLogin = false, string $exitPath = '..')
{
if ($requireLogin) { if ($requireLogin) {
$obj = self::requireLogin($exitPath); $obj = self::requireLogin($exitPath);
} } else {
else{
$obj = self::getInstance(); $obj = self::getInstance();
} }
return $obj->userID; return $obj->userID;
} }
public function isLoggedIn() { public function isLoggedIn()
{
if ($this->userID) { if ($this->userID) {
return true; return true;
} } else {
else{
return false; return false;
} }
} }
public function __destruct() { public function __destruct()
{
} }
} }
+30 -21
View File
@@ -1,7 +1,8 @@
<?php <?php
namespace sammo; namespace sammo;
class Setting { class Setting
{
private $basepath; private $basepath;
private $settingFile; private $settingFile;
private $htaccessFile; private $htaccessFile;
@@ -14,7 +15,8 @@ class Setting {
private $color; private $color;
private $version = null; private $version = null;
public function __construct(string $basepath, string $korName, string $color, string $name=null) { public function __construct(string $basepath, string $korName, string $color, string $name=null)
{
$this->basepath = $basepath; $this->basepath = $basepath;
$this->settingFile = realpath($basepath.'/d_setting/DB.php'); $this->settingFile = realpath($basepath.'/d_setting/DB.php');
$this->htaccessFile = realpath($basepath.'/.htaccess'); $this->htaccessFile = realpath($basepath.'/.htaccess');
@@ -24,8 +26,7 @@ class Setting {
$this->color = $color; $this->color = $color;
if ($name) { if ($name) {
$this->shortName = $name; $this->shortName = $name;
} } else {
else{
$this->shortName = basename($this->basepath); $this->shortName = basename($this->basepath);
} }
@@ -38,35 +39,43 @@ class Setting {
} }
} }
public function isRunning(){ public function isRunning()
{
return $this->running; return $this->running;
} }
public function isExists() { public function isExists()
{
return $this->exist; return $this->exist;
} }
public function getShortName(){ public function getShortName()
{
return $this->shortName; return $this->shortName;
} }
public function getColor(){ public function getColor()
{
return $this->color; return $this->color;
} }
public function getKorName(){ public function getKorName()
{
return $this->korName; return $this->korName;
} }
public function getBasePath(){ public function getBasePath()
{
return $this->basepath; return $this->basepath;
} }
public function getSettingFile() { public function getSettingFile()
{
return $this->settingFile; return $this->settingFile;
} }
public function getVersion(){ public function getVersion()
{
if ($this->version !== null) { if ($this->version !== null) {
return $this->version; return $this->version;
} }
@@ -87,10 +96,10 @@ class Setting {
} }
$this->version = $version; $this->version = $version;
return $version; return $version;
} }
public function closeServer(){ public function closeServer()
{
if (!file_exists($this->basepath) || !is_dir($this->basepath)) { if (!file_exists($this->basepath) || !is_dir($this->basepath)) {
return false; return false;
} }
@@ -98,21 +107,23 @@ class Setting {
//TODO: .htaccess가 서버 오픈에도 사용될 수 있으니 별도의 방법이 필요함 //TODO: .htaccess가 서버 오픈에도 사용될 수 있으니 별도의 방법이 필요함
$allow_ip = Util::get_client_ip(false); $allow_ip = Util::get_client_ip(false);
if (Util::starts_with($allow_ip, '192.168.') || if (Util::starts_with($allow_ip, '192.168.') ||
Util::starts_with($allow_ip, '10.')) Util::starts_with($allow_ip, '10.')) {
{
//172.16~172.31은 코딩하기 귀찮으니까 안할거다 //172.16~172.31은 코딩하기 귀찮으니까 안할거다
$allow_ip = Util::get_client_ip(true); $allow_ip = Util::get_client_ip(true);
} }
$xforward_allow_ip = WebUtil::escapeIPv4($allow_ip); $xforward_allow_ip = WebUtil::escapeIPv4($allow_ip);
$htaccess = $templates->render('block_htaccess', $htaccess = $templates->render(
['allow_ip' => $allow_ip, 'xforward_allow_ip' => $xforward_allow_ip]); 'block_htaccess',
['allow_ip' => $allow_ip, 'xforward_allow_ip' => $xforward_allow_ip]
);
file_put_contents($this->basepath.'/.htaccess', $htaccess); file_put_contents($this->basepath.'/.htaccess', $htaccess);
return true; return true;
} }
public function openServer(){ public function openServer()
{
if (!file_exists($this->basepath) || !is_dir($this->basepath)) { if (!file_exists($this->basepath) || !is_dir($this->basepath)) {
return false; return false;
} }
@@ -122,5 +133,3 @@ class Setting {
return true; return true;
} }
} }
+36 -19
View File
@@ -1,8 +1,10 @@
<?php <?php
namespace sammo; namespace sammo;
class StringUtil { class StringUtil
public static function GetStrLen($str) { {
public static function GetStrLen($str)
{
$count = strlen($str); $count = strlen($str);
$len = 0; $len = 0;
for ($i=0; $i < $count;) { for ($i=0; $i < $count;) {
@@ -25,16 +27,19 @@ class StringUtil {
return $len; return $len;
} }
public static function SubStr($str, $s, $l=1000) { public static function SubStr($str, $s, $l=1000)
{
$count = strlen($str); $count = strlen($str);
$startByte = 0; $isSet = 0; $startByte = 0;
$isSet = 0;
$endByte = $count; $endByte = $count;
$len = 0; $len = 0;
for ($i=0; $i < $count;) { for ($i=0; $i < $count;) {
$code = ord($str[$i]); $code = ord($str[$i]);
if ($isSet == 0 && $len >= $s) { if ($isSet == 0 && $len >= $s) {
$startByte = $i; $isSet = 1; $startByte = $i;
$isSet = 1;
} }
if ($isSet == 1 && $len-$s >= $l) { if ($isSet == 1 && $len-$s >= $l) {
$endByte = $i; $endByte = $i;
@@ -59,17 +64,21 @@ class StringUtil {
return $str; return $str;
} }
public static function SubStrForWidth($str, $s, $w) { public static function SubStrForWidth($str, $s, $w)
{
$count = strlen($str); $count = strlen($str);
$startByte = 0; $isSet = 0; $startByte = 0;
$endByte = $count; $last = 0; $isSet = 0;
$endByte = $count;
$last = 0;
$len = 0; $len = 0;
$width = 0; $width = 0;
for ($i=0; $i < $count;) { for ($i=0; $i < $count;) {
$code = ord($str[$i]); $code = ord($str[$i]);
if ($isSet == 0 && $len >= $s) { if ($isSet == 0 && $len >= $s) {
$startByte = $i; $isSet = 1; $startByte = $i;
$isSet = 1;
$width = 0; $width = 0;
} }
if ($isSet == 1 && $width == $w) { if ($isSet == 1 && $width == $w) {
@@ -107,18 +116,22 @@ class StringUtil {
return $str; return $str;
} }
public static function CutStrForWidth($str, $s, $w, $ch='..') { public static function CutStrForWidth($str, $s, $w, $ch='..')
{
$isCut = 0; $isCut = 0;
$count = strlen($str); $count = strlen($str);
$startByte = 0; $isSet = 0; $startByte = 0;
$endByte = $count; $last = 0; $isSet = 0;
$endByte = $count;
$last = 0;
$len = 0; $len = 0;
$width = 0; $width = 0;
for ($i=0; $i < $count;) { for ($i=0; $i < $count;) {
$code = ord($str[$i]); $code = ord($str[$i]);
if ($isSet == 0 && $len >= $s) { if ($isSet == 0 && $len >= $s) {
$startByte = $i; $isSet = 1; $startByte = $i;
$isSet = 1;
$width = 0; $width = 0;
} }
if ($isSet == 1 && $width >= $w) { if ($isSet == 1 && $width >= $w) {
@@ -156,7 +169,8 @@ class StringUtil {
} }
//중간정렬 //중간정렬
public static function staticFill($str, $maxsize, $ch) { public static function staticFill($str, $maxsize, $ch)
{
if (!$str) { if (!$str) {
$str = ''; $str = '';
} }
@@ -175,7 +189,8 @@ class StringUtil {
return $string; return $string;
} }
public static function Fill($str, $maxsize, $ch) { public static function Fill($str, $maxsize, $ch)
{
if (!$str) { if (!$str) {
$str = ''; $str = '';
} }
@@ -195,7 +210,8 @@ class StringUtil {
} }
//우측정렬 //우측정렬
public static function Fill2($str, $maxsize, $ch='0') { public static function Fill2($str, $maxsize, $ch='0')
{
if (!$str) { if (!$str) {
$str = ''; $str = '';
} }
@@ -211,7 +227,8 @@ class StringUtil {
return $string; return $string;
} }
public static function EscapeTag($str) { public static function EscapeTag($str)
{
$str = htmlspecialchars($str); $str = htmlspecialchars($str);
$str = str_replace(["\r\n", "\r", "\n"], '<br>', $str); $str = str_replace(["\r\n", "\r", "\n"], '<br>', $str);
// return nl2br(htmlspecialchars($str)); // return nl2br(htmlspecialchars($str));
@@ -219,7 +236,8 @@ class StringUtil {
return $str; return $str;
} }
public static function removeSpecialCharacter($str) { public static function removeSpecialCharacter($str)
{
return str_replace([ return str_replace([
' ', '"', '\'', 'ⓝ', 'ⓜ', 'ⓖ', '\\', '/', '`', ' ', '"', '\'', 'ⓝ', 'ⓜ', 'ⓖ', '\\', '/', '`',
'-', '=', '[', ']', ';', ',', '.', '~', '!', '@', '-', '=', '[', ']', ';', ',', '.', '~', '!', '@',
@@ -227,5 +245,4 @@ class StringUtil {
'|', '{', '}', ':', '', '<', '>', '?', ' ' '|', '{', '}', ':', '', '<', '>', '?', ' '
], '', $str); ], '', $str);
} }
} }
+24 -14
View File
@@ -1,46 +1,57 @@
<?php <?php
namespace sammo; namespace sammo;
class TimeUtil { class TimeUtil
public static function DateToday() { {
public static function DateToday()
{
return date('Y-m-d'); return date('Y-m-d');
} }
public static function DatetimeNow() { public static function DatetimeNow()
{
return date('Y-m-d H:i:s'); return date('Y-m-d H:i:s');
} }
public static function DatetimeFromNowDay($day) { public static function DatetimeFromNowDay($day)
{
return date('Y-m-d H:i:s', strtotime("{$day} days")); return date('Y-m-d H:i:s', strtotime("{$day} days"));
} }
public static function DatetimeFromNowHour($hour) { public static function DatetimeFromNowHour($hour)
{
return date('Y-m-d H:i:s', strtotime("{$hour} hours")); return date('Y-m-d H:i:s', strtotime("{$hour} hours"));
} }
public static function DatetimeFromNowMinute($minute) { public static function DatetimeFromNowMinute($minute)
{
return date('Y-m-d H:i:s', strtotime("{$minute} minutes")); return date('Y-m-d H:i:s', strtotime("{$minute} minutes"));
} }
public static function DatetimeFromNowSecond($second) { public static function DatetimeFromNowSecond($second)
{
return date('Y-m-d H:i:s', strtotime("{$second} seconds")); return date('Y-m-d H:i:s', strtotime("{$second} seconds"));
} }
public static function DatetimeFromMinute($date, $minute) { public static function DatetimeFromMinute($date, $minute)
{
return date('Y-m-d H:i:s', strtotime($date) + $minute*60); return date('Y-m-d H:i:s', strtotime($date) + $minute*60);
} }
public static function DatetimeFromSecond($date, $second) { public static function DatetimeFromSecond($date, $second)
{
return date('Y-m-d H:i:s', strtotime($date) + $second); return date('Y-m-d H:i:s', strtotime($date) + $second);
} }
public static function CutSecond($date) { public static function CutSecond($date)
{
$date[17] = '0'; $date[17] = '0';
$date[18] = '0'; $date[18] = '0';
return $date; return $date;
} }
public static function CutMinute($date) { public static function CutMinute($date)
{
$date[14] = '0'; $date[14] = '0';
$date[15] = '0'; $date[15] = '0';
$date[17] = '0'; $date[17] = '0';
@@ -48,9 +59,8 @@ class TimeUtil {
return $date; return $date;
} }
public static function HourMinuteSecond($second) { public static function HourMinuteSecond($second)
{
return date('H:i:s', strtotime('00:00:00') + $second); return date('H:i:s', strtotime('00:00:00') + $second);
} }
} }
+31 -22
View File
@@ -1,15 +1,18 @@
<?php <?php
namespace sammo; namespace sammo;
class Util extends \utilphp\util{ class Util extends \utilphp\util
public static function hashPassword($salt, $password){ {
public static function hashPassword($salt, $password)
{
return hash('sha512', $salt.$password.$salt); return hash('sha512', $salt.$password.$salt);
} }
/** /**
* 변환할 내용이 _tK_$key_ 형태로 작성된 단순한 템플릿 파일을 이용하여 결과물을 생성해주는 함수. * 변환할 내용이 _tK_$key_ 형태로 작성된 단순한 템플릿 파일을 이용하여 결과물을 생성해주는 함수.
*/ */
public static function generateFileUsingSimpleTemplate(string $srcFilePath, string $destFilePath, array $params, bool $canOverwrite=false){ public static function generateFileUsingSimpleTemplate(string $srcFilePath, string $destFilePath, array $params, bool $canOverwrite=false)
{
if ($destFilePath === $srcFilePath) { if ($destFilePath === $srcFilePath) {
return 'invalid destFilePath'; return 'invalid destFilePath';
} }
@@ -42,7 +45,8 @@ class Util extends \utilphp\util{
* *
* @return int|null * @return int|null
*/ */
public static function toInt($val, $silent=false){ public static function toInt($val, $silent=false)
{
if (!isset($val)) { if (!isset($val)) {
return null; return null;
} }
@@ -90,7 +94,8 @@ class Util extends \utilphp\util{
return $str; return $str;
} }
public static function mapWithDict($callback, $dict){ public static function mapWithDict($callback, $dict)
{
$result = []; $result = [];
foreach (array_keys($dict) as $key) { foreach (array_keys($dict) as $key) {
$result[$key] = ($callback)($dict[$key]); $result[$key] = ($callback)($dict[$key]);
@@ -98,7 +103,8 @@ class Util extends \utilphp\util{
return $result; return $result;
} }
public static function convertArrayToDict($arr, $keyName){ public static function convertArrayToDict($arr, $keyName)
{
$result = []; $result = [];
foreach ($arr as $obj) { foreach ($arr as $obj) {
@@ -109,7 +115,8 @@ class Util extends \utilphp\util{
return $result; return $result;
} }
public static function convertDictToArray($dict, $keys){ public static function convertDictToArray($dict, $keys)
{
$result = []; $result = [];
foreach ($keys as $key) { foreach ($keys as $key) {
@@ -118,7 +125,8 @@ class Util extends \utilphp\util{
return $result; return $result;
} }
public static function isDict(&$array){ public static function isDict(&$array)
{
if (!is_array($array)) { if (!is_array($array)) {
//배열이 아니면 dictionary 조차 아님. //배열이 아니면 dictionary 조차 아님.
return false; return false;
@@ -136,13 +144,13 @@ class Util extends \utilphp\util{
if ($jmp * 5 >= count($array)) { if ($jmp * 5 >= count($array)) {
//빈칸이 많으면 dictionary인걸로. //빈칸이 많으면 dictionary인걸로.
return true; return true;
} } else {
else{
return false; return false;
} }
} }
public static function eraseNullValue($dict, $depth=512){ public static function eraseNullValue($dict, $depth=512)
{
//TODO:Test 추가 //TODO:Test 추가
if ($dict === null) { if ($dict === null) {
return null; return null;
@@ -159,16 +167,13 @@ class Util extends \utilphp\util{
foreach ($dict as $key=>$value) { foreach ($dict as $key=>$value) {
if ($value === null) { if ($value === null) {
unset($dict[$key]); unset($dict[$key]);
} } elseif (Util::isDict($value)) {
else if(Util::isDict($value)){
$newValue = Util::eraseNullValue($value, $depth - 1); $newValue = Util::eraseNullValue($value, $depth - 1);
if ($newValue === null) { if ($newValue === null) {
unset($dict[$key]); unset($dict[$key]);
} } else {
else{
$dict[$key] = $newValue; $dict[$key] = $newValue;
} }
} }
} }
@@ -180,7 +185,8 @@ class Util extends \utilphp\util{
* 0.0~1.0 사이의 랜덤 float * 0.0~1.0 사이의 랜덤 float
* @return float * @return float
*/ */
public static function randF(){ public static function randF()
{
return mt_rand() / mt_getrandmax(); return mt_rand() / mt_getrandmax();
} }
@@ -188,7 +194,8 @@ class Util extends \utilphp\util{
* $prob의 확률로 true를 반환 * $prob의 확률로 true를 반환
* @return boolean * @return boolean
*/ */
public static function randBool($prob = 0.5){ public static function randBool($prob = 0.5)
{
return self::randF() < $prob; return self::randF() < $prob;
} }
@@ -196,7 +203,8 @@ class Util extends \utilphp\util{
/** /**
* $min과 $max 사이의 값으로 교정 * $min과 $max 사이의 값으로 교정
*/ */
public static function valueFit($value, $min, $max){ public static function valueFit($value, $min, $max)
{
if ($value < $min) { if ($value < $min) {
return $min; return $min;
} }
@@ -213,7 +221,8 @@ class Util extends \utilphp\util{
* *
* @return int|string 선택된 랜덤 값의 key값. 단순 배열인 경우에는 index * @return int|string 선택된 랜덤 값의 key값. 단순 배열인 경우에는 index
*/ */
public static function choiceRandomUsingWeight(array $items){ public static function choiceRandomUsingWeight(array $items)
{
$sum = 0; $sum = 0;
foreach ($items as $value) { foreach ($items as $value) {
$sum += $value; $sum += $value;
@@ -239,8 +248,8 @@ class Util extends \utilphp\util{
* *
* @return object 선택된 value값. * @return object 선택된 value값.
*/ */
public static function choiceRandom(array $items){ public static function choiceRandom(array $items)
{
return $items[array_rand($items)]; return $items[array_rand($items)];
} }
}; };
+7 -3
View File
@@ -1,12 +1,16 @@
<?php <?php
namespace sammo; namespace sammo;
class Validator extends \Valitron\Validator{ class Validator extends \Valitron\Validator
{
protected static $_lang = 'ko'; protected static $_lang = 'ko';
public function errorStr(){ public function errorStr()
{
$errors = array_values((array)$this->errors()); $errors = array_values((array)$this->errors());
$errors = array_map(function($value){return join(', ', $value);}, $errors); $errors = array_map(function ($value) {
return join(', ', $value);
}, $errors);
$errors = join(', ', $errors); $errors = join(', ', $errors);
return $errors; return $errors;
} }
+11 -8
View File
@@ -1,26 +1,29 @@
<?php <?php
namespace sammo; namespace sammo;
class WebUtil{ class WebUtil
{
private function __construct(){ private function __construct()
{
} }
public static function escapeIPv4($ip){ public static function escapeIPv4($ip)
{
return str_replace('.', '\\.', $ip); return str_replace('.', '\\.', $ip);
} }
public static function setHeaderNoCache(){ public static function setHeaderNoCache()
{
if (!headers_sent()) { if (!headers_sent()) {
header('Expires: Wed, 01 Jan 2014 00:00:00 GMT'); header('Expires: Wed, 01 Jan 2014 00:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate'); header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE); header('Cache-Control: post-check=0, pre-check=0', false);
header('Pragma: no-cache'); header('Pragma: no-cache');
} }
} }
public static function parseJsonPost(){ public static function parseJsonPost()
{
// http://thisinterestsme.com/receiving-json-post-data-via-php/ // http://thisinterestsme.com/receiving-json-post-data-via-php/
// http://thisinterestsme.com/php-json-error-handling/ // http://thisinterestsme.com/php-json-error-handling/
if (strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0) { if (strcasecmp($_SERVER['REQUEST_METHOD'], 'POST') != 0) {