Compare commits

..

4 Commits

Author SHA1 Message Date
756b1ba199 Automation init...4 2024-09-24 17:42:34 +09:00
a2129e49ae Automation init...4 2024-09-24 17:17:22 +09:00
1893200123 Automation init...4 2024-09-24 17:17:09 +09:00
2d41c92d98 Automation init...4 2024-09-24 17:09:29 +09:00
20 changed files with 335 additions and 774 deletions

View File

@ -135,4 +135,4 @@ define('AUTH_FIELDS', [
define('DB_ACTION', [
'CREATE' => 'create',
'MODIFY' => 'modify',
]);
]);

View File

@ -14,7 +14,7 @@ $routes->addPlaceholder('uuid', '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}
$routes->get('/', 'Home::index');
$routes->group('mangboard', ['namespace' => 'App\Controllers\Mangboard'], function ($routes) {
$routes->group('user', function ($routes) {
$routes->get('/', 'UserController::index', ['filter' => 'authFilter:manager']);
$routes->get('/', 'UserController::index');
$routes->cli('point/(:alpha)/(:num)', 'UserController::point/$1/$2');
$routes->cli('point/(:alpha)/(:num)/(:any)', 'UserController::point/$1/$2/$3');
$routes->cli('level/(:alpha)/(:num)', 'UserController::level/$1/$2');

View File

@ -1,156 +0,0 @@
<?php
namespace App\Controllers;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\RedirectResponse;
abstract class MVController extends CommonController
{
public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger)
{
parent::initController($request, $response, $logger);
helper('common');
}
abstract protected function create_init(): void;
abstract protected function getModel(): mixed;
//Field별 Form Option용
protected function getFormFieldOption(string $field, array $options = []): array
{
switch ($field) {
default:
$temps = lang($this->class_name . '.' . strtoupper($field));
if (!is_array($temps)) {
throw new \Exception(__FUNCTION__ . "에서 {$field}의 데이터가 array가 아닙니다.\n" . var_export($temps, true));
}
$options = [
"" => lang($this->class_name . '.label.' . $field) . ' 선택',
...lang($this->class_name . '.' . strtoupper($field)),
];
break;
}
return $options;
}
protected function getFormFieldInput(string $field, string $value, array $inputs = []): array
{
switch ($field) {
case 'status':
$inputs[$field] = form_dropdown(
$field,
$this->getFormFieldOption($field),
$value
);
break;
case 'updated_at':
case 'created_at':
$inputs[$field] = form_input($field, $value, ["class" => " calender"]);
break;
default:
$inputs[$field] = form_input($field, $value);
break;
}
return $inputs;
}
final public function getFormFieldInputs(array $inputs = []): array
{
foreach ($this->fields as $field) {
if (is_array($field)) {
throw new \Exception(__FUNCTION__ . "에서 field array 입니다.\n" . var_export($field, true));
}
$inputs = $this->getFormFieldInput($field, old($field) ?? DEFAULTS['EMPTY'], $inputs);
}
return $inputs;
}
protected function getFormFieldRule(string $field, array $rules): array
{
if (is_array($field)) {
throw new \Exception(__FUNCTION__ . "=> field가 array 입니다.\n" . var_export($field, true));
}
switch ($field) {
default:
$rules[$field] = $this->_model->getFieldRule($field, $rules);
;
break;
}
return $rules;
}
final public function getFormFieldRules(array $rules = []): array
{
foreach ($this->fields as $field) {
$rules = $this->getFormFieldRule($field, $rules);
}
return $rules;
}
//전송된 데이터 검증
protected function validateFormData(): void
{
//변경할 값 확인 : Upload된 파일 검증시 $this->request->getVar()보다 먼처 체크필요
$validation = service('validation');
$validation->setRules($this->getModel()->getFieldRules($this->fields));
if (!$validation->withRequest($this->request)->run()) {
throw new \Exception("데이터 검증 오류발생\n" . implode("\n", $validation->getErrors()));
}
}
//전송된 데이터
protected function getFormData(string $field): void
{
switch ($field) {
default:
$this->formDatas[$field] = rtrim($this->request->getVar($field));
break;
}
}
//전송된 데이터 재정의
protected function convertFormData(string $field): void
{
switch ($field) {
default:
break;
}
}
final public function create_form_process(): RedirectResponse|string
{
helper(['form']);
try {
$this->create_init();
$this->forminputs = $this->getFormFieldInputs();
$this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
$this->forms = ['attributes' => ['method' => "post",], 'hiddens' => []];
return view(
strtolower($this->class_name) . "/create",
['viewDatas' => $this->getAttributes()]
);
} catch (\Exception $e) {
log_message("error", $e->getMessage());
return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/")->with(SESSION_NAMES['RETURN_MSG'], $e->getMessage());
}
}
abstract protected function create_process_submit(): mixed;
final protected function create_process(): mixed
{
$this->getModel()->transStart();
try {
$this->create_init();
$this->validateFormData();
foreach ($this->fields as $field) {
$this->getFormData($field);
}
foreach ($this->fields as $field) {
$this->convertFormData($field);
}
$entity = $this->create_process_submit();
log_message("notice", __FUNCTION__ . "=>{$entity->getTitle()} 작업을 완료하였습니다.");
return redirect()->to($this->session->getFlashdata(SESSION_NAMES['RETURN_URL']) ?: "/");
} catch (\Exception $e) {
//Transaction Rollback
$this->getModel()->transRollback();
log_message("error", $e->getMessage());
$this->session->setFlashdata(SESSION_NAMES['RETURN_MSG'], __FUNCTION__ . " 실패하였습니다.\n" . $e->getMessage());
$this->session->keepFlashdata(SESSION_NAMES['RETURN_URL']);
return redirect()->back()->withInput();
}
}
}

View File

@ -1,14 +1,13 @@
<?php
namespace App\Controllers\Mangboard;
namespace App\Controllers\Mangboard\Admin;
use Psr\Log\LoggerInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\HTTP\RequestInterface;
use App\Models\Mangboard\UserModel;
use App\Libraries\MyMangboard\User;
use App\Controllers\CommonController;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Psr\Log\LoggerInterface;
use App\Models\Mangboard\UserModel;
class UserController extends CommonController
{
@ -25,13 +24,6 @@ class UserController extends CommonController
}
return $this->_model;
}
private function getUser(): User
{
if ($this->_user === null) {
$this->_user = new User();
}
return $this->_user;
}
public function point(string $id, string $point, string $sign = "+"): string
{
@ -40,7 +32,7 @@ class UserController extends CommonController
if (!$entity) {
throw new \Exception("해당 {$id}의 회원이 없습니다.");
}
$this->getUser()->setPoint($entity, intval($point), $sign);
$this->getModel()->setPoint($entity, intval($point), $sign);
return __FUNCTION__ . " 작업이 완료되었습니다.";
} catch (\Exception $e) {
log_message("error", $e->getMessage());
@ -54,7 +46,7 @@ class UserController extends CommonController
if (!$entity) {
throw new \Exception("해당 {$id}의 회원이 없습니다.");
}
$this->getUser()->setLevel($entity, intval($level));
$this->getModel()->setLevel($entity, intval($level));
log_message("notice", "Mangboard->level 작업이 완료되었습니다.");
return __FUNCTION__ . " 작업이 완료되었습니다.";
} catch (\Exception $e) {
@ -68,16 +60,16 @@ class UserController extends CommonController
try {
if (!$id) {
foreach ($this->getModel()->getEntitys() as $entity) {
$level = $this->getUser()->getLevelByPoint($entity);
$this->getUser()->setLevel($entity, intval($level));
$level = $this->getModel->checkLevel($entity);
$this->getModel()->setLevel($entity, intval($level));
}
} else {
$entity = is_numeric($id) ? $this->getModel()->getEntityByPK(intval($id)) : $this->getModel()->getEntityByID($id);
if (!$entity) {
throw new \Exception("해당 {$id}의 회원이 없습니다.");
}
$level = $this->getUser()->getLevelByPoint($entity);
$this->getUser()->setLevel($entity, intval($level));
$level = $this->getModel->checkLevel($entity);
$this->getModel()->setLevel($entity, intval($level));
}
return __FUNCTION__ . " 작업이 완료되었습니다.";
} catch (\Exception $e) {

View File

@ -0,0 +1,32 @@
<?php
namespace App\Entities;
use App\Entities\CommonEntity;
use App\Models\SNSUserModel;
class SNSUserEntity extends CommonEntity
{
public function __toString(): string
{
return "{$this->getPK()}|{$this->getID()}|{$this->getTitle()}";
}
public function getTitle(): string
{
return $this->attributes[SNSUserModel::TITLE];
}
public function setTitle(string $title): void
{
$this->attributes[SNSUserModel::TITLE] = $title;
}
//Common Function
public function getPK(): int
{
return $this->attributes[SNSUserModel::PK];
}
public function getID(): string
{
return $this->attributes['id'];
}
}

View File

@ -0,0 +1,49 @@
<?php
namespace App\Entities;
use App\Entities\CommonEntity;
use App\Models\UserModel;
class UserEntity extends CommonEntity
{
public function __toString(): string
{
return "{$this->getPK()}:{$this->getID()}:{$this->getTitle()},{$this->getLevel()}/{$this->getPoint()}";
}
public function getPK(): int
{
return $this->attributes[UserModel::PK];
}
public function getTitle(): string
{
return $this->attributes[UserModel::TITLE];
}
public function setTitle(string $title): void
{
$this->attributes[UserModel::TITLE] = $title;
}
//Common Function
public function getID(): string
{
return $this->attributes['id'];
}
public function getPoint(): int
{
return $this->attributes['point'];
}
public function setPoint(int $point): void
{
$this->attributes['point'] = $point;
}
public function getLevel(): int
{
return $this->attributes['level'];
}
public function setLevel(int $value): void
{
$this->attributes['level'] = $value;
}
}

View File

@ -1,110 +0,0 @@
<?php
namespace App\Libraries\MyAuth;
use App\Libraries\MySocket\Web\GoogleSocket;
use App\Entities\UserEntity;
use App\Entities\SNSUserEntity;
class GoogleAuth extends MyAuth
{
private $_mySocket = null;
private $_site = "GOOGLE";
public function __construct()
{
parent::__construct();
}
public function getMySocket(): GoogleSocket
{
if ($this->_mySocket === null) {
$this->_mySocket = new GoogleSocket(getenv('yamap.host.url'));
}
return $this->_mySocket;
}
public function getAuthButton()
{
$button = "";
if (!$this->getMySocket()->getAccessToken()) {
$button = anchor(
$this->getMySocket()->getClient()->createAuthUrl(),
ICONS['GOOGLE'],
["target" => "_self"]
);
}
return $button;
}
public function execute(): UserEntity
{
return new UserEntity();
// try {
// //Google 접근 권한 설정.
// $this->getMySocket()->setAccessToken();
// //Google 서비스 설정
// //$service = new \Google\Service\Oauth2($this->getMySocket());
// $service = new \Google\Service\Oauth2($this->getMySocket());
// $result = $service->userinfo->get();
// log_message("debug", var_export($result, true));
// // throw new \Exception(__METHOD__ . "에서 데이터 처리 필요");
// // DEBUG - 2023-07-13 12:54:51 --> \Google\Service\Oauth2\Userinfo::__set_state(array(
// // 'internal_gapi_mappings' =>
// // array (
// // 'familyName' => 'family_name',
// // 'givenName' => 'given_name',
// // 'verifiedEmail' => 'verified_email',
// // ),
// // 'modelData' =>
// // array (
// // 'verified_email' => true,
// // 'given_name' => '이름',
// // 'family_name' => '성',
// // ),
// // 'processed' =>
// // array (
// // ),
// // 'email' => 'twsdfsew342s@gmail.com',
// // 'familyName' => '성',
// // 'gender' => NULL,
// // 'givenName' => '이름',
// // 'hd' => NULL,
// // 'id' => '103667492432234234236838324',
// // 'link' => NULL,
// // 'locale' => 'ko',
// // 'name' => '성이름',
// // 'picture' => 'https://lh3.googleusercontent.com/a/AAcHTteFSgefsdfsdRJBkJA2tBEmg4PQrvI1Ta_5IXu5=s96-c',
// // 'verifiedEmail' => true,
// // ))
// //조건에 해당하는 이미 등록된 사용자가 있는지 검사
// $snsEntity = null;
// try {
// $snsEntity = $this->getUserSNSModel()->asObject(SNSUSerEntity::class)->where(
// array("site" => $this->_site, "id" => $result['id'])
// )->first();
// } catch (\Exception $e) {
// $snsEntity = new SNSUSerEntity([
// 'site' => $this->_site,
// 'id' => $result['id'],
// 'name' => $result['name'],
// 'email' => $result['email'],
// 'detail' => json_encode($result),
// 'status' => 'standby',
// ]);
// $snsEntity = $this->getUserSNSModel()->create($snsEntity);
// }
// //상태가 use(승인완료)가 아니라면
// if ($snsEntity->status !== DEFAULTS['STATUS']) {
// throw new \Exception("{$this->_site}}의{$result['email']}:{$result['name']}님은 " . $snsEntity->status . "입니다");
// }
// //user_id가 연결되어있지 않았다면
// if (!$snsEntity->getID()) {
// throw new \Exception("{$this->_site}의{$result['email']}:{$result['name']}님은 아직 사용자 지정이 되지 않았습니다. ");
// }
// //인증된 사용자 정보를 가져온후 로그인처리
// $entity = $this->getUserModel()->getEntityByID($snsEntity->getID());
// return $this->setSession_process($entity);;
// } catch (\Exception $e) {
// throw new \Exception("관리자에게 문의하시기 바랍니다.<BR>{$e->getMessage()}");
// }
}
}

View File

@ -1,33 +0,0 @@
<?php
namespace App\Libraries\MyAuth;
use App\Entities\UserEntity;
class LocalAuth extends MyAuth
{
public function __construct()
{
parent::__construct();
}
public function getAuthButton()
{
return "";
}
public function execute(): UserEntity
{
return new UserEntity();
// $formDatas = $this->getFormDatas();
// if (!isset($formDatas['id']) || !$formDatas['id'] || !isset($formDatas['passwd']) || !$formDatas['passwd']) {
// throw new \Exception("ID 나 암호의 값이 없습니다.");
// }
// $entity = $this->getUserModel()->getEntity(['id' => $formDatas['id'], 'status' => DEFAULTS['STATUS']]);
// if (!password_verify($formDatas['passwd'], $entity->passwd)) {
// throw new \Exception("암호가 맞지않습니다.");
// }
// //Session에 인증정보 설정
// return $this->setSession_process($entity);;
}
}

View File

@ -1,58 +0,0 @@
<?php
namespace App\Libraries\MyAuth;
use App\Entities\UserEntity;
use App\Models\UserModel;
use App\Models\SNSUserModel;
// 참고:https://github.com/SyntaxPhoenix/iloclient
abstract class MyAuth
{
private $_userModel = null;
private $_snsUserModel = null;
protected $_session = null;
protected function __construct()
{
$this->_session = \Config\Services::session();
}
abstract public function getAuthButton();
abstract public function execute(): UserEntity;
final protected function getUserModel(): UserModel
{
if (is_null($this->_userModel)) {
$this->_userModel = new UserModel();
}
return $this->_userModel;
}
final protected function getUserSNSModel(): SNSUSerModel
{
if (is_null($this->_snsUserModel)) {
$this->_snsUserModel = new SNSUserModel();
}
return $this->_snsUserModel;
}
protected function setSession_process(UserEntity $entity): UserEntity
{
$this->_session->set(SESSION_NAMES['ISLOGIN'], true);
$auths = [];
foreach (array_values(AUTH_FIELDS) as $field) {
switch ($field) {
case 'id':
$auths[$field] = $entity->getPK();
break;
case 'title':
$auths[$field] = $entity->getTitle();
break;
case 'role':
$auths[$field] = $entity->$field;
break;
}
}
$this->_session->set(SESSION_NAMES['AUTH'], $auths);
return $entity;
}
}

View File

@ -2,12 +2,13 @@
namespace App\Libraries\MyCrawler;
use App\Libraries\MySocket\WebSocket;
use App\Libraries\MyMangboard\Storage;
use Symfony\Component\DomCrawler\Crawler;
use App\Traits\FileTrait;
use App\Models\Mangboard\BoardsModel;
use App\Models\Mangboard\BoardModel;
use App\Libraries\MyMangboard\Storage;
use App\Libraries\MySocket\WebSocket;
use App\Libraries\CommonLibrary;
use App\Entities\Mangboard\UserEntity;
use App\Entities\Mangboard\BoardsEntity;
@ -27,8 +28,8 @@ abstract class MyCrawler extends CommonLibrary
protected function __construct(string $host, string $board_name, UserEntity $user_entity)
{
parent::__construct();
$this->_host = $host;
$this->_board_name = $board_name;
$this->_host = $host;
$this->_board_name = $board_name;
$this->_user_entity = $user_entity;
}
abstract protected function getDetailSelector(array $listInfo): array;
@ -50,7 +51,7 @@ abstract class MyCrawler extends CommonLibrary
final protected function getBoardsEntity(): BoardsEntity
{
if ($this->_boards_entity === null) {
$boardsModel = new BoardsModel();
$boardsModel = new BoardsModel();
$this->_boards_entity = $boardsModel->getEntityByID($this->getMyStorage()->getBoardName());
if ($this->_boards_entity === null) {
throw new \Exception(__FUNCTION__ . "=> {$this->getMyStorage()->getBoardName()}에 해당 Board 정보가 존재하지 않습니다.");
@ -85,7 +86,7 @@ abstract class MyCrawler extends CommonLibrary
{
return preg_match('/^[^?]+/', $url, $matches) ? $matches[0] : null;
}
protected function getUrlByMediaType(Crawler $node, string $media_tag, string $attr): null|string
protected function getUrlByMediaType(Crawler $node, string $media_tag, string $attr): null|string
{
switch ($media_tag) {
case 'video':
@ -143,8 +144,8 @@ abstract class MyCrawler extends CommonLibrary
throw new \Exception("URL이 파일명 형식이 아닙니다 : " . $this->getMySocket()->getHost() . $url);
}
$file_name = array_pop($file_names);
$temps = explode(".", $file_name);
$file_ext = array_pop($temps);
$temps = explode(".", $file_name);
$file_ext = array_pop($temps);
if (!$this->isFileType_FileTrait($file_ext, $media_tag)) {
throw new \Exception("파일명 형식이 {$media_tag}가 아닙니다");
}
@ -155,14 +156,14 @@ abstract class MyCrawler extends CommonLibrary
private function media_process(array $media_urls): array
{
$file_sequence = 1;
$storages = []; //CreateBoard에서 사용을 위해 DetailPage마다 초기화
$storages = []; //CreateBoard에서 사용을 위해 DetailPage마다 초기화
foreach ($media_urls as $media_tag => $urls) {
$total = count($urls);
foreach ($urls as $url) {
log_message("notice", __FUNCTION__ . " {$file_sequence}번째/총:{$total} MediaType->{$media_tag} 작업 시작");
try {
list($file_name, $content) = $this->media_download($media_tag, $url);
$storage = $this->media_save($file_sequence, $media_tag, $file_name, $content);
$storage = $this->media_save($file_sequence, $media_tag, $file_name, $content);
log_message("debug", __FUNCTION__ . " {$file_sequence}번째/총:{$total} 결과=>" . $storage->getOriginName());
$storages[] = $storage;
} catch (\Exception $e) {
@ -186,14 +187,14 @@ abstract class MyCrawler extends CommonLibrary
//Board DB 등록작업등
//미디어관련정보 entity에 넣기
$formDatas[BoardModel::TITLE] = $listInfo["title"];
$formDatas['user_pid'] = $this->getMyStorage()->getUserEntity()->getPK();
$formDatas['user_id'] = $this->getMyStorage()->getUserEntity()->getID();
$formDatas['user_name'] = $listInfo["nickname"] != "" ? $listInfo["nickname"] : $this->getMyStorage()->getUserEntity()->getTitle();
$formDatas['level'] = $this->getBoardsEntity()->getListLevel();
$formDatas['hit'] = intval($listInfo['hit']);
$formDatas['reg_date'] = date("Y-m-d H:i:s", strtotime($listInfo['date']));
$formDatas['data_type'] = "html";
$formDatas['editor_type'] = "S";
$formDatas['user_pid'] = $this->getMyStorage()->getUserEntity()->getPK();
$formDatas['user_id'] = $this->getMyStorage()->getUserEntity()->getID();
$formDatas['user_name'] = $listInfo["nickname"] != "" ? $listInfo["nickname"] : $this->getMyStorage()->getUserEntity()->getTitle();
$formDatas['level'] = $this->getBoardsEntity()->getListLevel();
$formDatas['hit'] = intval($listInfo['hit']);
$formDatas['reg_date'] = date("Y-m-d H:i:s", strtotime($listInfo['date']));
$formDatas['data_type'] = "html";
$formDatas['editor_type'] = "S";
foreach ($storages as $storage) {
if ($formDatas['image_path'] == "") {
$formDatas['image_path'] = $storage->getBasePath() . DIRECTORY_SEPARATOR . $storage->getPath() . DIRECTORY_SEPARATOR . $storage->getOriginName();
@ -243,9 +244,9 @@ abstract class MyCrawler extends CommonLibrary
private function detail_copy_process(int $cnt, array $listInfo): array
{
list($selector, $listInfo) = $this->getDetailSelector($listInfo);
$formDatas = [];
$formDatas['image_path'] = "";
$formDatas['content'] = $selector->html();
$formDatas = [];
$formDatas['image_path'] = "";
$formDatas['content'] = $selector->html();
//Board 등록작업등
$this->create_board($cnt, $listInfo, [], $formDatas);
log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다.");
@ -254,8 +255,8 @@ abstract class MyCrawler extends CommonLibrary
private function detail_download_process(int $cnt, array $listInfo): array
{
list($selector, $listInfo) = $this->getDetailSelector($listInfo);
$media_urls = $this->getUrlsByMediaType($selector, "img", "src");
$media_urls = $this->getUrlsByMediaType($selector, "video", "src", $media_urls);
$media_urls = $this->getUrlsByMediaType($selector, "img", "src");
$media_urls = $this->getUrlsByMediaType($selector, "video", "src", $media_urls);
if ($this->isDebug) {
throw new \Exception(sprintf(
"\n--------------%s Debug--------------\n%s%s\n---------------------------------------\n",
@ -281,8 +282,8 @@ abstract class MyCrawler extends CommonLibrary
{
//Limit가 0이면 $listInfos 갯수만큼 다하고, LIMIT 갯수 혹은 item의 갯수중 작은수만큼 한다.
$max_limit = !$max_limit || count($listInfos) <= $max_limit ? count($listInfos) : $max_limit;
$total = count($listInfos);
$i = 1;
$total = count($listInfos);
$i = 1;
foreach ($listInfos as $listInfo) {
if ($i <= $max_limit) {
log_message("notice", __FUNCTION__ . " 게시물 {$i}번째/총:{$total} {$listInfo["nickname"]} 작업시작");

View File

@ -2,13 +2,13 @@
namespace App\Libraries\MyMangboard;
use App\Traits\ImageTrait;
use App\Models\Mangboard\FileModel;
use App\Libraries\MyStorage\FileStorage;
use App\Entities\Mangboard\UserEntity;
use App\Entities\Mangboard\FileEntity;
use App\Entities\Mangboard\BoardsEntity;
use App\Entities\Mangboard\BoardEntity;
use App\Entities\Mangboard\BoardsEntity;
use App\Entities\Mangboard\FileEntity;
use App\Entities\Mangboard\UserEntity;
use App\Libraries\MyStorage\FileStorage;
use App\Models\Mangboard\FileModel;
use App\Traits\ImageTrait;
class Storage extends FileStorage
{
@ -19,7 +19,7 @@ class Storage extends FileStorage
public function __construct(string $board_name, UserEntity $user_entity)
{
parent::__construct($board_name);
$this->_board_name = $board_name;
$this->_board_name = $board_name;
$this->_user_entity = $user_entity;
}
final public function getBoardName(): string
@ -90,23 +90,24 @@ class Storage extends FileStorage
return $content;
}
private function create_db(BoardsEntity $boards_entity, BoardEntity $board_entity, string $board_table): FileEntity
private function create_file(BoardsEntity $boards_entity, BoardEntity $board_entity, string $board_table): FileEntity
{
$formDatas['board_pid'] = $board_entity->getPk();
$formDatas['user_pid'] = $this->_user_entity->getPK();
$formDatas['user_name'] = $this->_user_entity->getTitle();
$formDatas['board_name'] = $boards_entity->getTitle();
$formDatas['table_name'] = $board_table;
$formDatas['file_path'] = $this->getBasePath() . DIRECTORY_SEPARATOR . $this->getPath() . DIRECTORY_SEPARATOR . $this->getOriginName();
$formDatas[FileModel::TITLE] = $this->getOriginName();
$formDatas['file_type'] = $this->getMimeType();
$formDatas['file_caption'] = $this->getOriginName();
$formDatas['file_alt'] = $this->getOriginName();
$formDatas['board_pid'] = $board_entity->getPk();
$formDatas['user_pid'] = $this->_user_entity->getPK();
$formDatas['user_name'] = $this->_user_entity->getTitle();
$formDatas['board_name'] = $boards_entity->getTitle();
$formDatas['table_name'] = $board_table;
$formDatas['file_path'] = $this->getBasePath() . DIRECTORY_SEPARATOR . $this->getPath() . DIRECTORY_SEPARATOR . $this->getOriginName();
$formDatas[FileModel::TITLE] = $this->getOriginName();
$formDatas['file_type'] = $this->getMimeType();
$formDatas['file_caption'] = $this->getOriginName();
$formDatas['file_alt'] = $this->getOriginName();
$formDatas['file_description'] = "Filedata";
$formDatas['file_size'] = $this->getFileSize();
$formDatas['file_sequence'] = $this->getOriginSequence();
$formDatas['reg_date'] = date("Y-m-d H:i:s");
$entity = $this->getFileModel()->create($formDatas);
$formDatas['file_size'] = $this->getFileSize();
$formDatas['file_sequence'] = $this->getOriginSequence();
$formDatas['reg_date'] = date("Y-m-d H:i:s");
$entity = $this->getFileModel()->create($formDatas);
log_message("notice", sprintf(
"%s -> %s 게시물의 %s번째:%s 파일 등록 완료",
__FUNCTION__,
@ -117,9 +118,9 @@ class Storage extends FileStorage
return $entity;
}
public function create_small_image(BoardEntity $board_entity, $target_name = "small", int $width = 480, int $height = 319): void
private function create_small_image(BoardEntity $board_entity, $target_name = "small", int $width = 480, int $height = 319): void
{
$fileInfo = pathinfo($this->getFullPath() . DIRECTORY_SEPARATOR . $this->getOriginName(), PATHINFO_ALL);
$fileInfo = pathinfo($this->getFullPath() . DIRECTORY_SEPARATOR . $this->getOriginName(), PATHINFO_ALL);
$target_file_name = sprintf("%s_%s.%s", $fileInfo['filename'], $target_name, $fileInfo['extension']);
if (!$this->isFileType_FileTrait($fileInfo['extension'])) {
throw new \Exception("{$this->getOriginName()} Image 형식파일이 아닙니다.");
@ -147,7 +148,7 @@ class Storage extends FileStorage
final public function create(BoardsEntity $boards_entity, BoardEntity $board_entity, string $board_table): void
{
//File DB에 넣기
$this->create_db($boards_entity, $board_entity, $board_table);
$this->create_file($boards_entity, $board_entity, $board_table);
//작은이미지 만들기
$this->create_small_image($board_entity);
}

View File

@ -1,105 +0,0 @@
<?php
namespace App\Libraries\MyMangboard;
use App\Models\Mangboard\UserModel;
use App\Libraries\CommonLibrary;
use App\Entities\Mangboard\UserEntity;
class User extends CommonLibrary
{
private $_myStorage = null;
public function __construct()
{
parent::__construct();
}
final protected function getMyStorage(): UserModel
{
if ($this->_myStorage === null) {
$this->_myStorage = new UserModel();
}
return $this->_myStorage;
}
public function getLevelByPoint(UserEntity $entity): int
{
//Admin용 Level로는 변경불가
if ($entity->getLevel() == getenv('mangboard.admin.level')) {
log_message("notice", "Admin용 Level을 변경하실수 없습니다.");
return $entity->getLevel();
}
//사용자 Point별 Level 계산
$levelup_point = getenv('mangboard.level.up.point.unit');
$level = intdiv($entity->getPoint(), $levelup_point);
//운영자면 7~9
if (getenv('mangboard.level.manager.min') <= $level && $level <= getenv('mangboard.level.manager.max')) {
$level = $level < getenv('mangboard.level.manager.min') ? getenv('mangboard.level.manager.min') : $level;
$level = getenv('mangboard.level.manager.max') < $level ? getenv('mangboard.level.manager.max') : $level;
}
// echo "point:" . $entity->getPoint() . ",level:" . $level . "\n";
//사용자 Level 1~5;
if (getenv('mangboard.level.user.min') <= $level && $level <= getenv('mangboard.level.user.max')) {
$level = $level < getenv('mangboard.level.user.min') ? getenv('mangboard.level.user.min') : $level;
$level = getenv('mangboard.level.user.max') < $level ? getenv('mangboard.level.user.max') : $level;
}
// echo "point:" . $entity->getPoint() . ",level:" . $level . "\n";
return $level;
}
public function setPoint(UserEntity $entity, int $point, $sign = '+'): UserEntity
{
switch ($sign) {
case '-':
if ($point < $point) {
throw new \Exception("기존포인트:{$point}가 감소 포인트:-{$point} 작습니다.\n");
}
$point = $point - $point;
break;
case '+':
$point = $point + $point;
break;
default:
throw new \Exception(__FUNCTION__ . "에서는 {$sign}은 사용할수 없습니다.\n");
// break;
}
//기존정보와 Point값이 다르면 저장
if ($entity->getPoint() != $point) {
$formDatas = ["point" => $point];
$entity = $this->modify($entity, $formDatas);
log_message("notice", __FUNCTION__ . "=>{$entity->getTitle()}님의 Point가 {$entity->getPoint()}에서 {$point}로 변경되었습니다.");
}
return $this->setLevel($entity, $this->getLevelByPoint($entity));
}
public function setLevel(UserEntity $entity, int $level): UserEntity
{
//기존정보와 Level값이 다르면 저장
if ($entity->getLevel() != $level) {
$formDatas = ["level" => $level];
$entity = $this->modify($entity, $formDatas);
log_message("notice", __FUNCTION__ . "=>{$entity->getTitle()}님의 Level이 {$entity->getLevel()}에서 {$level}로 변경되었습니다.");
}
return $entity;
}
public function create(array $formDatas): UserEntity
{
$entity = $this->$this->getMyStorage()->create($formDatas);
log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
return $entity;
}
public function modify(UserEntity $entity, array $formDatas): UserEntity
{
$entity = $this->$this->getMyStorage()->modify($formDatas);
log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
return $entity;
}
public function delete(UserEntity $entity): void
{
$this->$this->getMyStorage()->delete($entity);
log_message("notice", "Record:" . __FUNCTION__ . "=> 작업을 완료하였습니다.");
}
}

View File

@ -0,0 +1,69 @@
<?php
namespace App\Libraries\MySocket;
use Cloudflare\API\Auth\APIKey;
use Cloudflare\API\Adapter\Guzzle;
use App\Models\Cloudflare\AccountModel;
use App\Libraries\CommonLibrary;
// use App\Entities\Cloudflare\AccountEntity;
// use Cloudflare\API\Endpoints\Zones;
// use Cloudflare\API\Endpoints\DNS;
// use Cloudflare\API\Endpoints\Accounts;
class CloudflareSocket extends CommonLibrary
{
private static int $_request = 0;
private static int $_request_max = 100;
private static int $_request_timewait = 60;
private $_accountModel = null;
private $_clients = [];
public function __construct()
{
parent::__construct();
$this->initAdapters();
self::$_request_max = getenv("cfmgr.request.max");
}
final protected function getAccountModel(): AccountModel
{
if ($this->_accountModel === null) {
$this->_accountModel = new AccountModel();
}
return $this->_accountModel;
}
final public function initAdapters(): void
{
foreach ($this->getAccountModel()->getEntitys() as $entity) {
$this->_clients[$entity->getAPIKey()] = new Guzzle(
new APIKey($entity->getTitle(), $entity->getAPIKey())
);
}
}
public function request(string $apikey): Guzzle
{
if (!array_key_exists($apikey, $this->_clients)) {
throw new \Exception(+__FUNCTION__ . " => {$apikey}에 해당하는 Adapter를 찾을수 없습니다.");
}
if (self::$_request >= self::$_request_max) {
log_message('warning', sprintf("--Cloudflare API Call %s초 대기 시작--", self::$_request_timewait));
sleep(intval(getenv("cf.mgr.request.time.wait")));
self::$_request = 0;
log_message('warning', sprintf("--Cloudflare API Call %s초 대기 종료--", self::$_request_timewait));
}
self::$_request++;
return $this->_clients[$apikey];
}
// public function getAccount(string $apikey): Accounts
// {
// return new Accounts($this->request($apikey));
// }
// public function getZone(string $apikey): Zones
// {
// return new Zones($this->request($apikey));
// }
// public function getRecord(string $apikey): DNS
// {
// return new DNS($this->request($apikey));
// }
}

View File

@ -6,14 +6,14 @@ use CodeIgniter\Model;
abstract class CommonModel extends Model
{
protected $table = '';
protected $primaryKey = '';
protected $table = '';
protected $primaryKey = '';
protected $useAutoIncrement = true;
protected $returnType = 'array';
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = [];
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = [];
protected bool $allowEmptyInserts = false;
protected bool $updateOnlyChanged = true;
@ -23,27 +23,27 @@ abstract class CommonModel extends Model
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
// Validation
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
protected $cleanValidationRules = true;
// Callbacks
protected $allowCallbacks = true;
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
protected $beforeInsert = [];
protected $afterInsert = [];
protected $beforeUpdate = [];
protected $afterUpdate = [];
protected $beforeFind = [];
protected $afterFind = [];
protected $beforeDelete = [];
protected $afterDelete = [];
private $_action = DB_ACTION["CREATE"];
protected function __construct()
@ -92,10 +92,11 @@ abstract class CommonModel extends Model
$rules[$field] .= $this->getAction() == DB_ACTION["CREATE"] ? "|is_unique[{$this->table}.{$field}]" : "";
} else {
$rules[$field] = "required|numeric";
};
}
;
break;
case $this->getTitleField():
$rules[$field] = "required|string";
$rules[$field] = "required|string";
break;
case "passwd":
$rules[$field] = $this->getAction() == DB_ACTION["CREATE"] ? "required" : "if_exist" . "|trim|string";
@ -104,13 +105,13 @@ abstract class CommonModel extends Model
$rules["confirmpassword"] = $this->getAction() == DB_ACTION["CREATE"] ? "required" : "if_exist" . "|trim|string|matches[passwd]";
break;
case "email":
$rules[$field] = "if_exist|trim|valid_email";
$rules[$field] = "if_exist|trim|valid_email";
break;
case 'image':
$rules[$field] = "is_image[{$field}]|mime_in[{$field},image/jpg,image/jpeg,image/gif,image/png,image/webp]|max_size[{$field},300]|max_dims[{$field},2048,768]";
$rules[$field] = "is_image[{$field}]|mime_in[{$field},image/jpg,image/jpeg,image/gif,image/png,image/webp]|max_size[{$field},300]|max_dims[{$field},2048,768]";
break;
case "status":
$rules[$field] = "if_exist|in_list[use,unuse]";
$rules[$field] = "if_exist|in_list[use,unuse]";
break;
case "updated_at":
case "created_at":
@ -130,12 +131,12 @@ abstract class CommonModel extends Model
}
return $rules;
}
public function getFormFieldOption(string $field, array $options = []): array
public function getFormFieldInputOption(string $field, array $options = []): array
{
switch ($field) {
default:
foreach ($this->getEntitys() as $entity) {
$options[$field][$entity->getPK()] = $entity->getTitle();
$options[$entity->getPK()] = $entity->getTitle();
}
break;
}
@ -157,7 +158,7 @@ abstract class CommonModel extends Model
//$formDatas에 전달된 값이 없는경우
if (!array_key_exists($field, $formDatas)) {
$randomBytes = bin2hex(random_bytes(32));
$value = sprintf(
$value = sprintf(
'%08s-%04s-%04x-%04x-%12s',
substr($randomBytes, 0, 8),
substr($randomBytes, 8, 4),
@ -212,8 +213,8 @@ abstract class CommonModel extends Model
$entity = $this->save_process($entity);
//primaryKey가 자동입력이면
if ($this->useAutoIncrement) {
$pkField = $this->getPKField();
$entity->$pkField = $this->getInsertID();
$pkField = $this->getPKField();
$entity->$pkField = $this->getInsertID();
}
log_message("debug", $this->table . "=> " . __FUNCTION__ . " 작업 완료");
return $entity;
@ -231,4 +232,24 @@ abstract class CommonModel extends Model
log_message("debug", $this->table . "=> " . __FUNCTION__ . " 작업 완료");
return $entity;
}
//List용
final public function setList_FieldFilter(string $field, int|string $value): void
{
$this->where($field, $value);
}
public function setList_WordFilter(string $word, string $field = null): void
{
$this->like($field ?? $this->getTitleField(), $word, 'before'); //befor , after , both
}
public function setList_DateFilter(string $start, string $end, $field = "created_at"): void
{
$this->where("{$field} >= {$start}");
$this->where("{$field} <= {$end}");
}
public function setList_OrderBy(string $order)
{
$this->orderBy($order);
}
}

View File

@ -169,4 +169,68 @@ class UserModel extends CommonModel
$this->where('passwd', password_hash($password, PASSWORD_DEFAULT));
return $this->getEntity();
}
private function getLevelByPoint(UserEntity $entity): int
{
//Admin용 Level로는 변경불가
if ($entity->getLevel() == getenv('mangboard.admin.level')) {
log_message("notice", "Admin용 Level을 변경하실수 없습니다.");
return $entity->getLevel();
}
//사용자 Point별 Level 계산
$levelup_point = getenv('mangboard.level.up.point.unit');
$level = intval($entity->getPoint() / $levelup_point * $levelup_point / $levelup_point);
//운영자면 7~9
if (getenv('mangboard.level.manager.min') <= $level && $level <= getenv('mangboard.level.manager.max')) {
$level = $level < getenv('mangboard.level.manager.min') ? getenv('mangboard.level.manager.min') : $level;
$level = getenv('mangboard.level.manager.max') < $level ? getenv('mangboard.level.manager.max') : $level;
}
// echo "point:" . $entity->getPoint() . ",level:" . $level . "\n";
//사용자 Level 1~5;
if (getenv('mangboard.level.user.min') <= $level && $level <= getenv('mangboard.level.user.max')) {
$level = $level < getenv('mangboard.level.user.min') ? getenv('mangboard.level.user.min') : $level;
$level = getenv('mangboard.level.user.max') < $level ? getenv('mangboard.level.user.max') : $level;
}
// echo "point:" . $entity->getPoint() . ",level:" . $level . "\n";
return $level;
}
public function setPoint(UserEntity $entity, int $point, $sign = '+'): UserEntity
{
switch ($sign) {
case '-':
if ($point < $point) {
throw new \Exception("기존포인트:{$point}가 감소 포인트:-{$point} 작습니다.\n");
}
$point = $point - $point;
break;
case '+':
$point = $point + $point;
break;
default:
throw new \Exception(__FUNCTION__ . "에서는 {$sign}은 사용할수 없습니다.\n");
// break;
}
//기존정보와 Point값이 다르면 저장
if ($entity->getPoint() != $point) {
$formDatas = ["point" => $point];
$entity = $this->modify($entity, $formDatas);
log_message("notice", __FUNCTION__ . "=>{$entity->getTitle()}님의 Point가 {$entity->getPoint()}에서 {$point}로 변경되었습니다.");
}
return $this->setLevel($entity, $this->getLevelByPoint($entity));
}
public function setLevel(UserEntity $entity, int $level): UserEntity
{
//기존정보와 Level값이 다르면 저장
if ($entity->getLevel() != $level) {
$formDatas = ["level" => $level];
$entity = $this->modify($entity, $formDatas);
log_message("notice", __FUNCTION__ . "=>{$entity->getTitle()}님의 Level이 {$entity->getLevel()}에서 {$level}로 변경되었습니다.");
}
return $entity;
}
}

View File

@ -1,71 +0,0 @@
<?php
namespace App\Models;
use App\Entities\SNSUSerEntity;
use App\Models\CommonModel;
class SNSUserModel extends CommonModel
{
const TABLE = "sns_users";
const PK = "uid";
const TITLE = "name";
protected $table = self::TABLE;
protected $primaryKey = self::PK;
protected $returnType = SNSUSerEntity::class;
protected $allowedFields = [
"id",
"name",
"email",
"detail",
"status"
];
public function __construct()
{
parent::__construct();
}
public function getTitleField(): string
{
return self::TITLE;
}
public function getFieldRule(string $field, array $rules): array
{
switch ($field) {
case "id":
$rules[$field] = "required|trim|min_length[4]|max_length[20]|is_unique[{$this->table}.{$field}]";
break;
case $this->getTitleField():
$rules[$field] = "required|trim|string";
break;
case "email":
$rules[$field] = "if_exist|trim|valid_email";
break;
default:
$rules = parent::getFieldRule($field, $rules);
break;
}
return $rules;
}
public function getEntityByPK(int $uid): null|SNSUSerEntity
{
$this->where($this->getPKField(), $uid);
return $this->getEntity();
}
public function getEntityByID(string $id): null|SNSUSerEntity
{
$this->where('id', $id);
return $this->getEntity();
}
//create용
public function create(array $formDatas = []): SNSUSerEntity
{
return $this->create_process(new SNSUSerEntity(), $formDatas);
}
//modify용
public function modify(SNSUSerEntity $entity, array $formDatas): SNSUSerEntity
{
return $this->modify_process($entity, $formDatas);
}
}

View File

@ -1,86 +0,0 @@
<?php
namespace App\Models;
use App\Entities\UserEntity;
use App\Models\CommonModel;
class UserModel extends CommonModel
{
const TABLE = "users";
const PK = "uid";
const TITLE = "name";
protected $table = self::TABLE;
protected $primaryKey = self::PK;
protected $returnType = UserEntity::class;
protected $allowedFields = [
"id",
"passwd",
"name",
"email",
"pohne",
"mobild",
"role",
"status"
];
public function __construct()
{
parent::__construct();
}
public function getTitleField(): string
{
return 'name';
}
public function getFieldRule(string $field, array $rules): array
{
switch ($field) {
case "id":
if ($this->getAction() == DB_ACTION["CREATE"]) {
$rules[$field] = "required|trim|min_length[4]|max_length[20]|is_unique[{$this->table}.{$field}]";
} else {
$rules[$field] = "required|trim|min_length[4]|max_length[20]";
}
break;
case $this->getTitleField():
$rules[$field] = "required|trim|string";
break;
case "email":
$rules[$field] = "if_exist|trim|valid_email";
break;
case "role":
//아래 Rule은 입력시에는 되는데 수정시에는 않됨 이유를 ?
// $rules[$field] = "required|in_list[master,director,cloudflare,manager,gold,silver,brone,vip,user]";
//아래 Rule은 checkbox를 사용시에는 required만 우선 써야 수정시 validate문제없음
$rules[$field] = "if_exist|trim|string";
break;
case "passwd":
default:
$rules = parent::getFieldRule($field, $rules);
break;
}
return $rules;
}
public function getEntityByPK(int $uid): null|UserEntity
{
$this->where($this->getPKField(), $uid);
return $this->getEntity();
}
public function getEntityByID(string $id): null|UserEntity
{
$this->where('id', $id);
return $this->getEntity();
}
//create용
public function create(array $formDatas = []): UserEntity
{
return $this->create_process(new UserEntity(), $formDatas);
}
//modify용
public function modify(UserEntity $entity, array $formDatas): UserEntity
{
return $this->modify_process($entity, $formDatas);
}
}

View File

@ -22,7 +22,7 @@ trait ImageTrait
// 이미지 파일을 로드하는 메소드
final public function load_ImageTrait($file)
{
$imageInfo = getimagesize($file);
$imageInfo = getimagesize($file);
$this->_imageType = $imageInfo[2];
switch ($this->_imageType) {
case IMAGETYPE_JPEG:
@ -60,7 +60,7 @@ trait ImageTrait
// 이미지 비율을 유지하면서 크기를 조정하는 메소드
final public function resizeToWidth_ImageTrait($width)
{
$ratio = $width / $this->getWidth_ImageTrait();
$ratio = $width / $this->getWidth_ImageTrait();
$height = $this->getHeight_ImageTrait() * $ratio;
$this->resize_ImageTrait($width, $height);
}
@ -72,7 +72,7 @@ trait ImageTrait
}
final public function scale($scale)
{
$width = $this->getWidth_ImageTrait() * ($scale / 100);
$width = $this->getWidth_ImageTrait() * ($scale / 100);
$height = $this->getHeight_ImageTrait() * ($scale / 100);
$this->resize_ImageTrait($width, $height);
}

View File

@ -1,49 +0,0 @@
# Disable directory browsing
Options -Indexes
# ----------------------------------------------------------------------
# Rewrite engine
# ----------------------------------------------------------------------
# Turning on the rewrite engine is necessary for the following rules and features.
# FollowSymLinks must be enabled for this to work.
<IfModule mod_rewrite.c>
Options +FollowSymlinks
RewriteEngine On
# If you installed CodeIgniter in a subfolder, you will need to
# change the following line to match the subfolder you need.
# http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewritebase
# RewriteBase /
# Redirect Trailing Slashes...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Rewrite "www.example.com -> example.com"
RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]
# Checks to see if the user is attempting to access a valid file,
# such as an image or css document, if this isn't true it sends the
# request to the front controller, index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([\s\S]*)$ index.php/$1 [L,NC,QSA]
# Ensure Authorization header is passed along
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>
<IfModule !mod_rewrite.c>
# If we don't have mod_rewrite installed, all 404's
# can be sent to index.php, and everything works as normal.
ErrorDocument 404 index.php
</IfModule>
# Disable server signature start
ServerSignature Off
# Disable server signature end

Binary file not shown.

Before

Width:  |  Height:  |  Size: 5.3 KiB