diff --git a/app/Config/Routes.php b/app/Config/Routes.php index ff1f65b..087d603 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -30,14 +30,8 @@ $routes->group('mangboard', ['namespace' => 'App\Controllers\Mangboard'], functi $routes->cli('check_level', 'UserController::check_level'); $routes->cli('check_level/(:alpha)', 'UserController::check_level/$1'); }); - $routes->group('crawler', ['namespace' => 'App\Controllers\Mangboard\Crawler'], function ($routes) { - $routes->cli('yamap/(:any)', 'YamapCrawler::execute/$1'); - $routes->cli('yamap/(:any)/(:any)', 'YamapCrawler::execute/$1/$2'); - $routes->cli('yamoon/(:any)', 'YamoonCrawler::execute/$1'); - $routes->cli('yamoon/(:any)/(:any)', 'YamoonCrawler::execute/$1/$2'); - $routes->cli('sir/(:any)', 'SirCrawler::execute/$1'); - $routes->cli('sir/(:any)/(:any)', 'SirCrawler::execute/$1/$2'); - $routes->cli('inven/(:any)', 'InvenCrawler::execute/$1'); - $routes->cli('inven/(:any)/(:any)', 'InvenCrawler::execute/$1/$2'); + $routes->group('crawler', function ($routes) { + $routes->cli('(:alpha)/(:any)', 'CrawlerController::$1/$2'); + $routes->cli('(:alpha)/(:any)/(:any)', 'CrawlerController::$1/$2'); }); }); diff --git a/app/Controllers/Cloudflare/AccountController.php b/app/Controllers/Cloudflare/AccountController.php index 2adbed1..a51564a 100644 --- a/app/Controllers/Cloudflare/AccountController.php +++ b/app/Controllers/Cloudflare/AccountController.php @@ -3,6 +3,7 @@ namespace App\Controllers\Cloudflare; use App\Controllers\MVController; +use App\Libraries\MyCloudflare\Account; use Psr\Log\LoggerInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\RequestInterface; @@ -10,8 +11,9 @@ use CodeIgniter\HTTP\RedirectResponse; use App\Traits\AuthTrait; use App\Models\Cloudflare\AccountModel; -use App\Libraries\MySocket\CloudflareSocket; use App\Entities\Cloudflare\AccountEntity; +use App\Libraries\MySocket\CloudflareSocket; + class AccountController extends MVController { @@ -24,7 +26,6 @@ class AccountController extends MVController $this->class_name = 'Account'; helper($this->class_name); } - final protected function getMySocket(): CloudflareSocket { if ($this->_mySocket === null) { @@ -32,7 +33,6 @@ class AccountController extends MVController } return $this->_mySocket; } - final protected function getModel(): AccountModel { if ($this->_model === null) { @@ -40,7 +40,6 @@ class AccountController extends MVController } return $this->_model; } - protected function create_init(): void { $this->fields = ['id', 'apikey']; @@ -52,32 +51,10 @@ class AccountController extends MVController { return $this->create_form_process(); } - - //Result 형태 - // [ - // {"id":"078e88a7735965b661715af13031ecb0", - // "name":"Cloudwin002@idcjp.jp's Auth", - // "type":"standard", - // "settings":{ - // "enforce_twofactor":false, - // "api_access_enabled":null, - // "access_approval_expiry":null, - // "use_account_custom_ns_by_default":false - // }, - // "legacy_flags":{"enterprise_zone_quota":{"maximum":0,"current":0,"available":0}}, - // "created_on":"2017-06-26T05:44:49.470184Z"} - // ] protected function create_process_submit(): AccountEntity { - $this->getMySocket()->setAPIKey($this->formDatas['apikey']); - $result = $this->getMySocket()->getAccount()->addAccount($this->formDatas['id']); - $this->formDatas[$this->getModel()->PK()] = $result->id; - $this->formDatas[$this->getModel()->getTitleField()] = $result->name; - $this->formDatas['type'] = $result->type; - $this->formDatas['status'] = 'use'; - $this->formDatas['updated_at'] = $result->created_on; - $this->formDatas['created_at'] = $result->created_on; - return $this->getModel()->create($this->formDatas); + $account = new Account($this->getMySocket(), $this->getModel()); + return $account->create($this->formDatas); } public function create(): RedirectResponse { diff --git a/app/Controllers/Cloudflare/RecordController.php b/app/Controllers/Cloudflare/RecordController.php new file mode 100644 index 0000000..9b2670a --- /dev/null +++ b/app/Controllers/Cloudflare/RecordController.php @@ -0,0 +1,75 @@ +session = $this->session_AuthTrait(); + $this->class_name = 'Record'; + helper($this->class_name); + } + final protected function getMySocket(): CloudflareSocket + { + if ($this->_mySocket === null) { + $this->_mySocket = new CloudflareSocket(); + } + return $this->_mySocket; + } + final protected function getModel(): RecordModel + { + if ($this->_model === null) { + $this->_model = new RecordModel(); + } + return $this->_model; + } + final protected function getAccountModel(): AccountModel + { + if ($this->_accountModel === null) { + $this->_accountModel = new AccountModel(); + } + return $this->_accountModel; + } + protected function create_init(): void + { + $this->fields = ['id', 'apikey']; + $this->filter_fields = ['status']; + $this->action = 'create'; + $this->getModel()->setAction($this->action); + } + public function create_form(): RedirectResponse|string + { + return $this->create_form_process(); + } + protected function create_process_submit(): RecordEntity + { + $Record = new Record( + $this->getMySocket(), + $this->getModel(), + $this->getAccountModel()->getEntityByPK($this->formDatas['account_uid']) + ); + return $Record->create($this->formDatas); + } + public function create(): RedirectResponse + { + return parent::create_process(); + } +} diff --git a/app/Controllers/Cloudflare/ZoneController.php b/app/Controllers/Cloudflare/ZoneController.php index 7aa04ae..17283de 100644 --- a/app/Controllers/Cloudflare/ZoneController.php +++ b/app/Controllers/Cloudflare/ZoneController.php @@ -2,21 +2,24 @@ namespace App\Controllers\Cloudflare; -use App\Controllers\MVController; use Psr\Log\LoggerInterface; use CodeIgniter\HTTP\ResponseInterface; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\RedirectResponse; - use App\Traits\AuthTrait; + use App\Models\Cloudflare\ZoneModel; +use App\Models\Cloudflare\AccountModel; use App\Libraries\MySocket\CloudflareSocket; +use App\Libraries\MyCloudflare\Zone; use App\Entities\Cloudflare\ZoneEntity; +use App\Controllers\MVController; class ZoneController extends MVController { use AuthTrait; private $_model = null; + private $_accountModel = null; public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger) { parent::initController($request, $response, $logger); @@ -24,7 +27,6 @@ class ZoneController extends MVController $this->class_name = 'Zone'; helper($this->class_name); } - final protected function getMySocket(): CloudflareSocket { if ($this->_mySocket === null) { @@ -32,7 +34,6 @@ class ZoneController extends MVController } return $this->_mySocket; } - final protected function getModel(): ZoneModel { if ($this->_model === null) { @@ -40,7 +41,13 @@ class ZoneController extends MVController } return $this->_model; } - + final protected function getAccountModel(): AccountModel + { + if ($this->_accountModel === null) { + $this->_accountModel = new AccountModel(); + } + return $this->_accountModel; + } protected function create_init(): void { $this->fields = ['id', 'apikey']; @@ -52,32 +59,14 @@ class ZoneController extends MVController { return $this->create_form_process(); } - - //Result 형태 - // [ - // {"id":"078e88a7735965b661715af13031ecb0", - // "name":"Cloudwin002@idcjp.jp's Auth", - // "type":"standard", - // "settings":{ - // "enforce_twofactor":false, - // "api_access_enabled":null, - // "access_approval_expiry":null, - // "use_account_custom_ns_by_default":false - // }, - // "legacy_flags":{"enterprise_zone_quota":{"maximum":0,"current":0,"available":0}}, - // "created_on":"2017-06-26T05:44:49.470184Z"} - // ] protected function create_process_submit(): ZoneEntity { - $this->getMySocket()->setAPIKey($this->formDatas['apikey']); - $result = $this->getMySocket()->getZone()->addZone($this->formDatas['id']); - $this->formDatas[$this->getModel()->PK()] = $result->id; - $this->formDatas[$this->getModel()->getTitleField()] = $result->name; - $this->formDatas['type'] = $result->type; - $this->formDatas['status'] = 'use'; - $this->formDatas['updated_at'] = $result->created_on; - $this->formDatas['created_at'] = $result->created_on; - return $this->getModel()->create($this->formDatas); + $zone = new Zone( + $this->getMySocket(), + $this->getModel(), + $this->getAccountModel()->getEntityByPK($this->formDatas['account_uid']) + ); + return $zone->create($this->formDatas); } public function create(): RedirectResponse { diff --git a/app/Controllers/Mangboard/Crawler/YamapCrawler.php b/app/Controllers/Mangboard/Crawler/YamapCrawler.php deleted file mode 100644 index 87563a6..0000000 --- a/app/Controllers/Mangboard/Crawler/YamapCrawler.php +++ /dev/null @@ -1,103 +0,0 @@ -getMySocket()->getContent($listInfo['detail_url']); - return array($this->getSelector($response, getenv("yamap.view.content.tag")), $listInfo); - } - //리스트내용 - //
- //
요즘 패션
- //
- // - // 괴강고귀 - // - // - // | 추천 (14) | 조회 (432) - // - //
- //
- // - // - // - // 2024-09-14 01:53:45 - // - //
- //
- //
- //

- //

 

- //
- //
- //
- // - // - //
- //
- //
- - final public function execute(string $board_name, string $user_id = null, ...$params): void - { - try { - //추가옵션 - $this->isDebug = in_array('debug', $params); - $this->isCopy = in_array('copy', $params); - $this->setBoardName($board_name); - $this->login_process($user_id); - if ($this->isDebug) { - $listInfo = []; - $listInfo['title'] = 'test_title'; - $listInfo['nickname'] = 'test_name'; - $listInfo['hit'] = 1; - $listInfo['date'] = date("Y-m-d H:i:s"); - $listInfo['detail_url'] = getenv("yamap.view.test.url.{$this->getBoardName()}"); - $listInfos[] = $listInfo; - } else { - $response = $this->getMySocket()->getContent(getenv("yamap.list.url.{$this->getBoardName()}")); - $this->getSelector($response, getenv("yamap.list.tag.{$this->getBoardName()}"))->each( - function (Crawler $node) use (&$listInfos): void { - $nickname = $node->filter(getenv("yamap.list.item.nickname.tag"))->text(); - $hit = $node->filter(getenv("yamap.list.item.hit.tag"))->text(); - $date = $node->filter(getenv("yamap.list.item.date.tag"))->text(); - //title및 detail url - $link_node = $node->filter(getenv("yamap.list.item.link.tag")); - $detail_url = $link_node->attr("href"); - $title = $link_node->children()->last()->text(); - //title에서 예외사항비교 - if (strpos($title, getenv("yamap.list.tag.except.{$this->getBoardName()}")) === false) { - $listInfos[] = ['title' => $title, 'nickname' => $nickname, 'detail_url' => $detail_url, 'date' => $date, 'hit' => $hit]; - } - } - ); - } - if (!count($listInfos)) { - throw new \Exception("Target URL이 없습니다."); - } - $this->list_process(intval(getenv("yamap.list.max_limit.{$this->getBoardName()}")), $listInfos); - log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다."); - } catch (\Exception $e) { - log_message("warning", sprintf( - "\n---%s 오류---\n%s\n-----------------------------------------\n", - __FUNCTION__, - $e->getMessage() - )); - } - } -} diff --git a/app/Controllers/Mangboard/CrawlerController.php b/app/Controllers/Mangboard/CrawlerController.php new file mode 100644 index 0000000..f080110 --- /dev/null +++ b/app/Controllers/Mangboard/CrawlerController.php @@ -0,0 +1,136 @@ +_user_model === null) { + return $this->_user_model = new UserModel(); + } + return $this->_user_model; + } + final protected function login_process(string $user_id = null): UserEntity + { + $user_id = $user_id ?? getenv("mangboard.login.default.id"); + $password = getenv("mangboard.login.default.password"); + // $response = $this->getWebLibrary($host)->getResponse( + // getenv("mangboard.host.url") . getenv("mangboard.login.url"), + // "post", + // [ + // 'form_params' => [ + // 'user_id' => $id, + // 'password' => $password, + // ], + // ] + // ); + // if ($response->getStatusCode() == 200) { + // $entity = $this->getUserModel()->getEntityByLoginCheck($id, $password); + // if ($entity === null) { + // throw new \Exception("{$id}는 회원이 아니거나 암호가 맞지 않습니다."); + // } + // } else { + // throw new \Exception("연결실패:" . $response->getStatusCode()); + // } + $entity = $this->getUserModel()->getEntityByID($user_id); + if ($entity === null) { + throw new \Exception("{$user_id}로 로그인 실패"); + } + log_message("notice", "{$user_id}로 로그인 성공"); + return $entity; + } + + public function yamap(string $board_name, string $user_id = null, ...$params): void + { + try { + $user_entity = $this->login_process($user_id); + $mySocket = new WebSocket(getenv("yamap.host.url")); + $myStorage = new MangboardStorage($board_name, $user_entity); + $myCrawler = new Yamap($mySocket, $myStorage); + //추가옵션 + $myCrawler->isDebug = in_array('debug', $params); + $myCrawler->isCopy = in_array('copy', $params); + $myCrawler->execute(); + } catch (\Exception $e) { + log_message("warning", sprintf( + "\n---%s 오류---\n%s\n-----------------------------------------\n", + __FUNCTION__, + $e->getMessage() + )); + } + } + public function yamoon(string $board_name, string $user_id = null, ...$params): void + { + try { + $user_entity = $this->login_process($user_id); + $mySocket = new WebSocket(getenv("yamoon.host.url")); + $myStorage = new MangboardStorage($board_name, $user_entity); + $myCrawler = new Yamap($mySocket, $myStorage); + //추가옵션 + $myCrawler->isDebug = in_array('debug', $params); + $myCrawler->isCopy = in_array('copy', $params); + $myCrawler->execute(); + } catch (\Exception $e) { + log_message("warning", sprintf( + "\n---%s 오류---\n%s\n-----------------------------------------\n", + __FUNCTION__, + $e->getMessage() + )); + } + } + public function sir(string $board_name, string $user_id = null, ...$params): void + { + try { + $user_entity = $this->login_process($user_id); + $mySocket = new WebSocket(getenv("sir.host.url")); + $myStorage = new MangboardStorage($board_name, $user_entity); + $myCrawler = new Yamap($mySocket, $myStorage); + //추가옵션 + $myCrawler->isDebug = in_array('debug', $params); + $myCrawler->isCopy = in_array('copy', $params); + $myCrawler->execute(); + } catch (\Exception $e) { + log_message("warning", sprintf( + "\n---%s 오류---\n%s\n-----------------------------------------\n", + __FUNCTION__, + $e->getMessage() + )); + } + } + public function inven(string $board_name, string $user_id = null, ...$params): void + { + // echo "{$board_name}|{$user_id}|", implode("|", $params); + // exit; + try { + $user_entity = $this->login_process($user_id); + $mySocket = new WebSocket(getenv("inven.host.url")); + $myStorage = new MangboardStorage($board_name, $user_entity); + $myCrawler = new Yamap($mySocket, $myStorage); + //추가옵션 + $myCrawler->isDebug = in_array('debug', $params); + $myCrawler->isCopy = in_array('copy', $params); + $myCrawler->execute(); + } catch (\Exception $e) { + log_message("warning", sprintf( + "\n---%s 오류---\n%s\n-----------------------------------------\n", + __FUNCTION__, + $e->getMessage() + )); + } + } +} diff --git a/app/Entities/Cloudflare/APIEntity.php b/app/Entities/Cloudflare/APIEntity.php deleted file mode 100644 index 2d5a442..0000000 --- a/app/Entities/Cloudflare/APIEntity.php +++ /dev/null @@ -1,15 +0,0 @@ -getParentField(); - return $this->$field; - } -} diff --git a/app/Entities/Cloudflare/AccountEntity.php b/app/Entities/Cloudflare/AccountEntity.php index 84319f3..5092cb1 100644 --- a/app/Entities/Cloudflare/AccountEntity.php +++ b/app/Entities/Cloudflare/AccountEntity.php @@ -2,6 +2,7 @@ namespace App\Entities\Cloudflare; +use App\Models\Cloudflare\AccountModel; use App\Entities\CommonEntity; class AccountEntity extends CommonEntity @@ -12,15 +13,15 @@ class AccountEntity extends CommonEntity } public function getPK(): int { - return $this->attributes['uid']; + return $this->attributes[AccountModel::PK]; } public function getTitle(): string { - return $this->attributes['id']; + return $this->attributes[AccountModel::TITLE]; } public function setTitle(string $title): void { - $this->attributes['id'] = $title; + $this->attributes[AccountModel::TITLE] = $title; } //Common Function public function getAPIKey(): string diff --git a/app/Entities/Cloudflare/FirewallEntity.php b/app/Entities/Cloudflare/FirewallEntity.php deleted file mode 100644 index d66057d..0000000 --- a/app/Entities/Cloudflare/FirewallEntity.php +++ /dev/null @@ -1,27 +0,0 @@ -attributes['uid']; - } - public function getTitle() - { - return $this->attributes['description']; - } - public function __toString() - { - return "uid:{$this->attributes['uid']}|zone_uid:{$this->attributes['zone_uid']}|host:{$this->attributes['description']}|content:{$this->attributes['action']}"; - } - public function getParentField(): string - { - return "zone_uid"; - } -} diff --git a/app/Entities/Cloudflare/RecordEntity.php b/app/Entities/Cloudflare/RecordEntity.php index abf36b4..45fd9d5 100644 --- a/app/Entities/Cloudflare/RecordEntity.php +++ b/app/Entities/Cloudflare/RecordEntity.php @@ -1,27 +1,31 @@ attributes['uid']; - } - public function getTitle() - { - return "{$this->attributes['host']}-{$this->attributes['content']}"; - } public function __toString() { - return "uid:{$this->attributes['uid']}|zone_uid:{$this->attributes['zone_uid']}|host:{$this->attributes['host']}|content:{$this->attributes['content']}|proxied:{$this->attributes['proxied']}|fixed:{$this->attributes['fixed']}|locked:{$this->attributes['locked']}"; + return "{$this->getPK()}|{$this->getParent()}|{$this->getTitle()}|{$this->attributes['host']}|{$this->attributes['content']}|{$this->attributes['proxied']}|{$this->attributes['fixed']}|{$this->attributes['locked']}"; } - public function getParentField(): string + public function getPK(): int { - return "zone_uid"; + return $this->attributes[RecordModel::PK]; + } + public function getTitle(): string + { + return $this->attributes[RecordModel::TITLE]; + } + public function setTitle(string $title): void + { + $this->attributes[RecordModel::TITLE] = $title; + } + //Common Function + public function getParent(): string + { + return $this->attributes[RecordModel::PARENT]; } } diff --git a/app/Entities/Cloudflare/ZoneEntity.php b/app/Entities/Cloudflare/ZoneEntity.php index 83c673e..5eb6802 100644 --- a/app/Entities/Cloudflare/ZoneEntity.php +++ b/app/Entities/Cloudflare/ZoneEntity.php @@ -2,25 +2,30 @@ namespace App\Entities\Cloudflare; +use App\Models\Cloudflare\ZoneModel; use App\Entities\CommonEntity; class ZoneEntity extends CommonEntity { public function __toString() { - return "{$this->getPK()}|{$this->attributes['account_uid']}|{$this->getTitle()}|{$this->attributes['development_mode']}|{$this->attributes['ipv6']}|{$this->attributes['security_level']}"; + return "{$this->getPK()}|{$this->getParent()}|{$this->getTitle()}|{$this->attributes['development_mode']}|{$this->attributes['ipv6']}|{$this->attributes['security_level']}"; } public function getPK(): int { - return $this->attributes['uid']; + return $this->attributes[ZoneModel::PK]; } public function getTitle(): string { - return $this->attributes['id']; + return $this->attributes[ZoneModel::TITLE]; } public function setTitle(string $title): void { - $this->attributes['id'] = $title; + $this->attributes[ZoneModel::TITLE] = $title; } //Common Function + public function getParent(): string + { + return $this->attributes[ZoneModel::PARENT]; + } } diff --git a/app/Entities/Mangboard/BoardEntity.php b/app/Entities/Mangboard/BoardEntity.php index dce5d65..c408115 100644 --- a/app/Entities/Mangboard/BoardEntity.php +++ b/app/Entities/Mangboard/BoardEntity.php @@ -3,6 +3,7 @@ namespace App\Entities\Mangboard; use App\Entities\CommonEntity; +use App\Models\Mangboard\BoardModel; class BoardEntity extends CommonEntity { @@ -12,17 +13,17 @@ class BoardEntity extends CommonEntity } public function getTitle(): string { - return $this->attributes['title']; + return $this->attributes[BoardModel::TITLE]; } public function setTitle(string $title): void { - $this->attributes['title'] = $title; + $this->attributes[BoardModel::TITLE] = $title; } //Common Function public function getPK(): int { - return $this->attributes['pid']; + return $this->attributes[BoardModel::PK]; } public function getImagePath(): string { diff --git a/app/Entities/Mangboard/BoardsEntity.php b/app/Entities/Mangboard/BoardsEntity.php index b894e50..6f45045 100644 --- a/app/Entities/Mangboard/BoardsEntity.php +++ b/app/Entities/Mangboard/BoardsEntity.php @@ -3,6 +3,7 @@ namespace App\Entities\Mangboard; use App\Entities\CommonEntity; +use App\Models\Mangboard\BoardsModel; class BoardsEntity extends CommonEntity { @@ -12,17 +13,17 @@ class BoardsEntity extends CommonEntity } public function getTitle(): string { - return $this->attributes['board_name']; + return $this->attributes[BoardsModel::TITLE]; } public function setTitle(string $board_name): void { - $this->attributes['board_name'] = $board_name; + $this->attributes[BoardsModel::TITLE] = $board_name; } //Common Function public function getPK(): int { - return $this->attributes['pid']; + return $this->attributes[BoardsModel::PK]; } public function getListLevel(): int { diff --git a/app/Entities/Mangboard/FileEntity.php b/app/Entities/Mangboard/FileEntity.php index 96d85d2..0e908c9 100644 --- a/app/Entities/Mangboard/FileEntity.php +++ b/app/Entities/Mangboard/FileEntity.php @@ -2,6 +2,7 @@ namespace App\Entities\Mangboard; +use App\Models\Mangboard\FileModel; use App\Entities\CommonEntity; class FileEntity extends CommonEntity @@ -12,16 +13,16 @@ class FileEntity extends CommonEntity } public function getTitle(): string { - return $this->attributes['file_name']; + return $this->attributes[FileModel::TITLE]; } public function setTitle(string $file_name): void { - $this->attributes['file_name'] = $file_name; + $this->attributes[FileModel::TITLE] = $file_name; } //Common Function public function getPK(): int { - return $this->attributes['pid']; + return $this->attributes[FileModel::PK]; } public function getPath(): string { diff --git a/app/Entities/Mangboard/UserEntity.php b/app/Entities/Mangboard/UserEntity.php index 601939a..561feea 100644 --- a/app/Entities/Mangboard/UserEntity.php +++ b/app/Entities/Mangboard/UserEntity.php @@ -2,6 +2,7 @@ namespace App\Entities\Mangboard; +use App\Models\Mangboard\UserModel; use App\Entities\CommonEntity; class UserEntity extends CommonEntity @@ -12,17 +13,17 @@ class UserEntity extends CommonEntity } public function getTitle(): string { - return $this->attributes['user_name']; + return $this->attributes[UserModel::TITLE]; } public function setTitle(string $title): void { - $this->attributes['user_name'] = $title; + $this->attributes[UserModel::TITLE] = $title; } //Common Function public function getPK(): int { - return $this->attributes['pid']; + return $this->attributes[UserModel::PK]; } public function getID(): string { diff --git a/app/Entities/SNSUserEntity.php b/app/Entities/SNSUserEntity.php index 476a06c..511ca1c 100644 --- a/app/Entities/SNSUserEntity.php +++ b/app/Entities/SNSUserEntity.php @@ -3,6 +3,7 @@ namespace App\Entities; use App\Entities\CommonEntity; +use App\Models\SNSUserModel; class SNSUserEntity extends CommonEntity { @@ -12,17 +13,17 @@ class SNSUserEntity extends CommonEntity } public function getTitle(): string { - return $this->attributes['_name']; + return $this->attributes[SNSUserModel::TITLE]; } public function setTitle(string $title): void { - $this->attributes['name'] = $title; + $this->attributes[SNSUserModel::TITLE] = $title; } //Common Function public function getPK(): int { - return $this->attributes['uid']; + return $this->attributes[SNSUserModel::PK]; } public function getID(): string { diff --git a/app/Entities/UserEntity.php b/app/Entities/UserEntity.php index 528e75f..fd6a5a7 100644 --- a/app/Entities/UserEntity.php +++ b/app/Entities/UserEntity.php @@ -3,6 +3,7 @@ namespace App\Entities; use App\Entities\CommonEntity; +use App\Models\UserModel; class UserEntity extends CommonEntity { @@ -12,15 +13,15 @@ class UserEntity extends CommonEntity } public function getPK(): int { - return $this->attributes['uid']; + return $this->attributes[UserModel::PK]; } public function getTitle(): string { - return $this->attributes['_name']; + return $this->attributes[UserModel::TITLE]; } public function setTitle(string $title): void { - $this->attributes['name'] = $title; + $this->attributes[UserModel::TITLE] = $title; } //Common Function @@ -37,7 +38,6 @@ class UserEntity extends CommonEntity $this->attributes['point'] = $point; } - public function getLevel(): int { return $this->attributes['level']; diff --git a/app/Libraries/MyCloudflare/Account.php b/app/Libraries/MyCloudflare/Account.php index 7500386..97dd986 100644 --- a/app/Libraries/MyCloudflare/Account.php +++ b/app/Libraries/MyCloudflare/Account.php @@ -1,10 +1,51 @@ _myStorage === null) { + throw new \Exception("MyStorage가 정의되지 않았습니다."); + } + return $this->_myStorage; + } + //Result 형태 + // [ + // {"id":"078e88a7735965b661715af13031ecb0", + // "name":"Cloudwin002@idcjp.jp's Auth", + // "type":"standard", + // "settings":{ + // "enforce_twofactor":false, + // "api_access_enabled":null, + // "access_approval_expiry":null, + // "use_account_custom_ns_by_default":false + // }, + // "legacy_flags":{"enterprise_zone_quota":{"maximum":0,"current":0,"available":0}}, + // "created_on":"2017-06-26T05:44:49.470184Z"} + // ] + public function create(array $formDatas): AccountEntity + { + //Socket용 + $cf = $this->getMySocket()->getAccount($formDatas['apikey'])->addAccount($formDatas['id']); + //Storage용 + $formDatas[$this->getMyStorage()->PK()] = $cf->id; + $formDatas[$this->getMyStorage()->getTitleField()] = $cf->name; + $formDatas['type'] = $cf->type; + $formDatas['status'] = 'use'; + $formDatas['updated_at'] = $cf->created_on; + $formDatas['created_at'] = $cf->created_on; + $entity = $this->getMyStorage()->create($formDatas); + log_message("notice", "Account::" . __FUNCTION__ . "=> 작업을 완료하였습니다."); + return $entity; + } +} diff --git a/app/Libraries/MyCloudflare/Firewall.php b/app/Libraries/MyCloudflare/Firewall.php deleted file mode 100644 index e1115c5..0000000 --- a/app/Libraries/MyCloudflare/Firewall.php +++ /dev/null @@ -1,96 +0,0 @@ -_model = new \App\Models\Cloudflare\API\FirewallModel(); - } - final protected function setAdapter() - { - if (!is_null($this->_adapter)) { - throw new \Exception("Adapter가 이미 지정되었습니다."); - } - $accountModel = new \App\Models\Cloudflare\API\AccountModel(); - $account = $accountModel->getEntity($this->getParent()->getParentFieldData()); - $authModel = new \App\Models\Cloudflare\API\AuthModel(); - $auth = $authModel->getEntity($account->getParentFieldData()); - $apikey = new \Cloudflare\API\Auth\APIKey($auth->getAuthId(), $auth->getAuthKey()); - $this->_adapter = new \Cloudflare\API\Adapter\Guzzle($apikey); - // throw new \Exception(var_export($this->_adapter, true)); - } - public function getClassName() - { - return 'Firewall'; - } - protected function getEntityByResult(\stdClass $cfResult): \App\Entities\Cloudflare\API\FirewallEntity - { - $entity = is_null($this->_entity) ? new \App\Entities\Cloudflare\API\FirewallEntity() : $this->_entity; - $entity->uid = $cfResult->id; - $entity->zone_uid = $this->getParent()->getPrimaryKey(); - $entity->description = $cfResult->description; - $entity->filter_id = $cfResult->filter->id; - $entity->filter_expression = isset($cfResult->filter->expression) && $cfResult->filter->expression ? $cfResult->filter->expression : ' '; - $entity->filter_paused = isset($cfResult->filter->paused) && $cfResult->filter->paused ? 'on' : 'off'; - $entity->action = $cfResult->action; - $entity->paused = $cfResult->paused ? 'off' : 'on'; - $entity->updated_at = $cfResult->modified_on; - $entity->created_at = $cfResult->created_on; - // parent::add_logs("notice","host:[{$cfResult->name}<>{$entity->description}] | proxied:[{$cfResult->proxied}<>{$entity->proxied}] | locked:[{$cfResult->locked}<>{$entity->locked}]"); - return $entity; - } - - // public function insert(){ } - public function update(\App\Entities\Cloudflare\API\FirewallEntity $entity, array $fieldDatas): \App\Entities\Cloudflare\API\FirewallEntity - { - $rule = array_merge( - [ - 'id' => $entity->getPrimaryKey(), - 'filter' => [ - 'id' => $entity->filter_id, - 'expression' => $entity->filter_expression, - 'paused' => isset($entity->filter_paused) && $entity->filter_paused === 'on' ? true : false - ] - ], - [ - 'paused' => isset($entity->paused) && $entity->paused === 'on' ? false : true, - 'action' => $entity->action - ] - ); - if (!is_null($entity->description)) { - $rule['description'] = $entity->description; - } - - $cfResult = $this->getAdapter()->put('zones/' . $this->getParent()->getPrimaryKey() . '/firewall/rules/' . $entity->getPrimaryKey(), $rule); - $cfResult = json_decode($cfResult->getBody()); - if (!$cfResult->success) { - throw new \Exception(var_export($cfResult, true)); - } - $entity = $this->getEntityByResult($cfResult->result); - Log::add("warning", "Record API: {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); - return $entity; - } - // public function delete(){ } - public function sync(\App\Entities\Cloudflare\API\FirewallEntity $entity): \App\Entities\Cloudflare\API\FirewallEntity - { - $cfResult = $this->getAdapter()->get('zones/' . $this->getParent()->getPrimaryKey() . '/firewall/rules/' . $entity->getPrimaryKey()); - $cfResult = json_decode($cfResult->getBody()); - if (!$cfResult->success) { - throw new \Exception(var_export($cfResult, true)); - } - Log::add("warning", "Record API: {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); - return $this->getEntityByResult($cfResult->result); - } - protected function getCFResults_List(int $page): array - { - $this->_endPoint = is_null($this->_endPoint) ? new \Cloudflare\API\Endpoints\Firewall($this->getAdapter()) : $this->_endPoint; - return $this->_endPoint->listFirewallRules($this->getParent()->getPrimaryKey(), $page, CF_ADAPTER_PERPAGE_MAX)->result; - } -} diff --git a/app/Libraries/MyCloudflare/MyCloudflare.php b/app/Libraries/MyCloudflare/MyCloudflare.php new file mode 100644 index 0000000..bbcc024 --- /dev/null +++ b/app/Libraries/MyCloudflare/MyCloudflare.php @@ -0,0 +1,27 @@ +_mySocket = $mySocket; + $this->_myStorage = $myStorage; + } + abstract protected function getMyStorage(): mixed; + //-----------------------필수항목-------------------// + final protected function getMySocket(): CloudflareSocket + { + if ($this->_mySocket === null) { + throw new \Exception("MySocket이 정의되지 않았습니다."); + } + return $this->_mySocket; + } +} diff --git a/app/Libraries/MyCloudflare/Zone.php b/app/Libraries/MyCloudflare/Zone.php index 7a39d7a..6f57b45 100644 --- a/app/Libraries/MyCloudflare/Zone.php +++ b/app/Libraries/MyCloudflare/Zone.php @@ -1,152 +1,158 @@ _isGetSetting = $isGetSetting; - $this->_model = new \App\Models\Cloudflare\API\ZoneModel(); + parent::__construct($mySocket, $myStorage); + $this->_account_entity = $account_entity; } - final protected function setAdapter() + final protected function getMyStorage(): ZoneModel { - if (!is_null($this->_adapter)) { - throw new \Exception("Adapter가 이미 지정되었습니다."); + if ($this->_myStorage === null) { + throw new \Exception("MyStorage가 정의되지 않았습니다."); } - $authModel = new \App\Models\Cloudflare\API\AuthModel(); - $auth = $authModel->getEntity($this->getParent()->getParentFieldData()); - $apikey = new \Cloudflare\API\Auth\APIKey($auth->getAuthId(), $auth->getAuthKey()); - $this->_adapter = new \Cloudflare\API\Adapter\Guzzle($apikey); - // throw new \Exception(var_export($this->_adapter, true)); + return $this->_myStorage; } - public function getClassName() + private function getArrayByResult($cf): array { - return 'Zone'; + $formDatas['uid'] = $cf->id; + $formDatas['account_uid'] = $cf->account->id; + $formDatas['domain'] = $cf->name; + $formDatas['status'] = $cf->status; + //$formDatas['type'] = $cf->type; // full 이게있는데 뭔지 잘모름 + $formDatas['name_servers'] = 'none'; + if (isset($cf->name_servers)) { + $formDatas['name_servers'] = is_array($cf->name_servers) ? + implode( + ',', + $cf->name_servers + ) : $cf->name_servers; + } + $formDatas['original_name_servers'] = 'none'; + if (isset($cf->original_name_servers)) { + $formDatas['original_name_servers'] = is_array($cf->original_name_servers) ? + implode( + ',', + $cf->original_name_servers + ) : $cf->original_name_servers; + } + $formDatas['updated_at'] = $cf->modified_on; + $formDatas['created_at'] = $cf->created_on; + $formDatas['plan'] = $cf->plan->name; + return $formDatas; } //Cfzone에서 가져온 값을 zone에 setting - protected function getEntityByResult(\stdClass $cfResult): \App\Entities\Cloudflare\API\ZoneEntity + final public function getCFSetting(ZoneEntity $entity): ZoneEntity { - $entity = is_null($this->_entity) ? new \App\Entities\Cloudflare\API\ZoneEntity() : $this->_entity; - $entity->uid = $cfResult->id; - $entity->account_uid = $cfResult->account->id; - $entity->domain = $cfResult->name; - $entity->status = $cfResult->status; - //$entity->type = $cfResult->type; // full 이게있는데 뭔지 잘모름 - $entity->name_servers = 'none'; - if (isset($cfResult->name_servers)) { - $entity->name_servers = is_array($cfResult->name_servers) ? - implode(',', $cfResult->name_servers) : $cfResult->name_servers; + $cf = $this->getMySocket()->getAdapter($this->_account_entity->getAPIKey()) + ->patch('zones/' . $entity->getPK() . '/settings/'); + $cf = json_decode($cf->getBody()); + if (!$cf->success) { + throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); } - $entity->original_name_servers = 'none'; - if (isset($cfResult->original_name_servers)) { - $entity->original_name_servers = is_array($cfResult->original_name_servers) ? - implode(',', $cfResult->original_name_servers) : $cfResult->original_name_servers; - } - $entity->updated_at = $cfResult->modified_on; - $entity->created_at = $cfResult->created_on; - $entity->plan = $cfResult->plan->name; - return $this->_isGetSetting ? $this->getCFSetting($entity) : $entity; - } - - //Cfzone에서 가져온 값을 zone에 setting - final public function getCFSetting(\App\Entities\Cloudflare\API\ZoneEntity $entity): \App\Entities\Cloudflare\API\ZoneEntity - { - $cfResult = $this->getAdapter()->get('zones/' . $entity->getPrimaryKey() . '/settings/'); - $cfResult = json_decode($cfResult->getBody()); - if (!$cfResult->success) { - throw new \Exception(__FUNCTION__ . "에서 Call Error:\n" . var_export($cfResult, true)); - } - foreach ($cfResult->result as $cfResult) { - switch ($cfResult->id) { + foreach ($cf->result as $cf) { + switch ($cf->id) { case 'development_mode': - $entity->development_mode = $cfResult->value; + $entity->development_mode = $cf->value; break; case 'ipv6': - $entity->ipv6 = $cfResult->value; + $entity->ipv6 = $cf->value; break; case 'security_level': - $entity->security_level = $cfResult->value; + $entity->security_level = $cf->value; break; } } return $entity; } - //Cfzone에 해당 키값 변경용 - final public function setCFSetting(\App\Entities\Cloudflare\API\ZoneEntity $entity, string $field, string $value): \App\Entities\Cloudflare\API\ZoneEntity + final public function setCFSetting(ZoneEntity $entity, string $field, string $value): ZoneEntity { - $cfResult = $this->getAdapter()->patch('zones/' . $entity->getPrimaryKey() . '/settings/' . $field, array('value' => $value)); - $cfResult = json_decode($cfResult->getBody()); - if (!$cfResult->success || $cfResult->result->id !== $field) { - throw new \Exception(__FUNCTION__ . "에서 {$field}->{$value} 변경오류:\n" . var_export($cfResult, true)); + $cf = $this->getMySocket()->getAdapter($this->_account_entity->getAPIKEY()) + ->patch('zones/' . $entity->getPK() . '/settings/' . $field, array('value' => $value)); + $cf = json_decode($cf->getBody()); + if (!$cf->success || $cf->result->id !== $field) { + throw new \Exception(__FUNCTION__ . "에서 {$field}->{$value} 변경실패:\n" . var_export($cf, true)); } //최종 결과값은 body->result->id='필드명',body->result->value='on/off'이런식으로 받음 - $entity->$field = $cfResult->result->value; - Log::add("warning", "Zone API: {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); + $entity->$field = $cf->result->value; return $entity; } + //Result 형태 - public function insert(array $fieldDatas): \App\Entities\Cloudflare\API\ZoneEntity + public function create(array $formDatas, $jump_start = false): ZoneEntity { + //Socket용 + // $cf = $this->getMySocket()->getZone($this->_account_entity->getAPIKEY()) + // ->addZone($formDatas[ZoneModel::TITLE], $jump_start, $this->_account_entity->getPK()); //도메인생성을 위해 Cloudflare에 전송 $options = [ - 'accountId' => $this->getParent()->getPrimaryKey(), - 'name' => $fieldDatas['domain'], - 'jump_start' => false, + 'accountId' => $this->_account_entity->getPK(), + 'name' => $formDatas['domain'], + 'jump_start' => $jump_start, ]; - $cfResult = $this->getAdapter()->post('zones/', $options); - $cfResult = json_decode($cfResult->getBody()); - if (!$cfResult->success) { - throw new \Exception(var_export($cfResult, true)); + $cf = $this->getMySocket()->getAdapter($this->_account_entity->getAPIKey()) + ->post('zones/', $options); + $cf = json_decode($cf->getBody()); + if (!$cf->success) { + throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); } - $entity = $this->getEntityByResult($cfResult->result); + + //Storage용 + $formDatas = $this->getArrayByResult($cf->result); + $entity = $this->$this->getMyStorage()->create($formDatas); //아래는 추가 셋팅 ipv6 TurnOFF , //Development mode TurnOFF $entity = $this->setCFSetting($entity, 'ipv6', 'off'); $entity = $this->setCFSetting($entity, 'development_mode', 'off'); $entity = $this->setCFSetting($entity, 'security_level', 'medium'); - Log::add("warning", "Record API: {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); + log_message("notice", "Zone::" . __FUNCTION__ . "=> 작업을 완료하였습니다."); return $entity; } - public function update(\App\Entities\Cloudflare\API\ZoneEntity $entity, array $fieldDatas): \App\Entities\Cloudflare\API\ZoneEntity + public function update(ZoneEntity $entity, array $fieldDatas): ZoneEntity { //ipv6 , //development_mode , //security_level foreach ($fieldDatas as $field => $value) { $entity = $this->setCFSetting($entity, $field, $value); } - Log::add("warning", "API {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); + log_message("notice", "Zone::" . __FUNCTION__ . "=> 작업을 완료하였습니다."); return $entity; } - public function delete(\App\Entities\Cloudflare\API\ZoneEntity $entity) + public function delete(ZoneEntity $entity): void { - //Zone 삭제 - $cfResult = $this->getAdapter()->delete('zones/' . $entity->getPrimaryKey()); - $cfResult = json_decode($cfResult->getBody()); - if (!$cfResult->success) { - throw new \Exception(var_export($cfResult, true)); + $cf = $this->getMySocket()->getAdapter($this->_account_entity->getAPIKey()) + ->delete('zones/' . $entity->getPK()); + $cf = json_decode($cf->getBody()); + if (!$cf->success) { + throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); } - Log::add("warning", "Zone API: {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); + log_message("notice", "Zone::" . __FUNCTION__ . "=> 작업을 완료하였습니다."); } - public function sync(\App\Entities\Cloudflare\API\ZoneEntity $entity): \App\Entities\Cloudflare\API\ZoneEntity + public function sync(ZoneEntity $entity): ZoneEntity { - $cfResult = $this->getAdapter()->get('zones/' . $entity->getPrimaryKey()); - $cfResult = json_decode($cfResult->getBody()); - if (!$cfResult->success) { - throw new \Exception(var_export($cfResult, true)); + $cf = $this->getMySocket()->getAdapter($this->_account_entity->getAPIKey()) + ->get('zones/' . $entity->getPK()); + $cf = json_decode($cf->getBody()); + if (!$cf->success) { + throw new \Exception(__FUNCTION__ . "에서 실패:\n" . var_export($cf, true)); } - Log::add("warning", "Zone API: {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); - return $this->getEntityByResult($cfResult->result); - } - - protected function getCFResults_List(int $page): array - { - $this->_endPoint = is_null($this->_endPoint) ? new \Cloudflare\API\Endpoints\Zones($this->getAdapter()) : $this->_endPoint; - return $this->_endPoint->listZones('', '', $page, CF_ADAPTER_PERPAGE_MAX)->result; + log_message("notice", "Zone::" . __FUNCTION__ . "=> 작업을 완료하였습니다."); + $formDatas = $this->getArrayByResult($cf->result); + return $this->$this->getMyStorage()->create($formDatas); } + // protected function getCFResults_List(int $page): array + // { + // $this->_endPoint = is_null($this->_endPoint) ? new \Cloudflare\API\Endpoints\Zones($this->getAdapter()) : $this->_endPoint; + // return $this->_endPoint->listZones('', '', $page, CF_ADAPTER_PERPAGE_MAX)->result; + // } + public function reload() {} } diff --git a/app/Libraries/MyCloudflare/Zone_old.php b/app/Libraries/MyCloudflare/Zone_old.php new file mode 100644 index 0000000..7a39d7a --- /dev/null +++ b/app/Libraries/MyCloudflare/Zone_old.php @@ -0,0 +1,152 @@ +_isGetSetting = $isGetSetting; + $this->_model = new \App\Models\Cloudflare\API\ZoneModel(); + } + final protected function setAdapter() + { + if (!is_null($this->_adapter)) { + throw new \Exception("Adapter가 이미 지정되었습니다."); + } + $authModel = new \App\Models\Cloudflare\API\AuthModel(); + $auth = $authModel->getEntity($this->getParent()->getParentFieldData()); + $apikey = new \Cloudflare\API\Auth\APIKey($auth->getAuthId(), $auth->getAuthKey()); + $this->_adapter = new \Cloudflare\API\Adapter\Guzzle($apikey); + // throw new \Exception(var_export($this->_adapter, true)); + } + public function getClassName() + { + return 'Zone'; + } + + //Cfzone에서 가져온 값을 zone에 setting + protected function getEntityByResult(\stdClass $cfResult): \App\Entities\Cloudflare\API\ZoneEntity + { + $entity = is_null($this->_entity) ? new \App\Entities\Cloudflare\API\ZoneEntity() : $this->_entity; + $entity->uid = $cfResult->id; + $entity->account_uid = $cfResult->account->id; + $entity->domain = $cfResult->name; + $entity->status = $cfResult->status; + //$entity->type = $cfResult->type; // full 이게있는데 뭔지 잘모름 + $entity->name_servers = 'none'; + if (isset($cfResult->name_servers)) { + $entity->name_servers = is_array($cfResult->name_servers) ? + implode(',', $cfResult->name_servers) : $cfResult->name_servers; + } + $entity->original_name_servers = 'none'; + if (isset($cfResult->original_name_servers)) { + $entity->original_name_servers = is_array($cfResult->original_name_servers) ? + implode(',', $cfResult->original_name_servers) : $cfResult->original_name_servers; + } + $entity->updated_at = $cfResult->modified_on; + $entity->created_at = $cfResult->created_on; + $entity->plan = $cfResult->plan->name; + return $this->_isGetSetting ? $this->getCFSetting($entity) : $entity; + } + + //Cfzone에서 가져온 값을 zone에 setting + final public function getCFSetting(\App\Entities\Cloudflare\API\ZoneEntity $entity): \App\Entities\Cloudflare\API\ZoneEntity + { + $cfResult = $this->getAdapter()->get('zones/' . $entity->getPrimaryKey() . '/settings/'); + $cfResult = json_decode($cfResult->getBody()); + if (!$cfResult->success) { + throw new \Exception(__FUNCTION__ . "에서 Call Error:\n" . var_export($cfResult, true)); + } + foreach ($cfResult->result as $cfResult) { + switch ($cfResult->id) { + case 'development_mode': + $entity->development_mode = $cfResult->value; + break; + case 'ipv6': + $entity->ipv6 = $cfResult->value; + break; + case 'security_level': + $entity->security_level = $cfResult->value; + break; + } + } + return $entity; + } + //Cfzone에 해당 키값 변경용 + final public function setCFSetting(\App\Entities\Cloudflare\API\ZoneEntity $entity, string $field, string $value): \App\Entities\Cloudflare\API\ZoneEntity + { + $cfResult = $this->getAdapter()->patch('zones/' . $entity->getPrimaryKey() . '/settings/' . $field, array('value' => $value)); + $cfResult = json_decode($cfResult->getBody()); + if (!$cfResult->success || $cfResult->result->id !== $field) { + throw new \Exception(__FUNCTION__ . "에서 {$field}->{$value} 변경오류:\n" . var_export($cfResult, true)); + } + //최종 결과값은 body->result->id='필드명',body->result->value='on/off'이런식으로 받음 + $entity->$field = $cfResult->result->value; + Log::add("warning", "Zone API: {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); + return $entity; + } + + public function insert(array $fieldDatas): \App\Entities\Cloudflare\API\ZoneEntity + { + //도메인생성을 위해 Cloudflare에 전송 + $options = [ + 'accountId' => $this->getParent()->getPrimaryKey(), + 'name' => $fieldDatas['domain'], + 'jump_start' => false, + ]; + $cfResult = $this->getAdapter()->post('zones/', $options); + $cfResult = json_decode($cfResult->getBody()); + if (!$cfResult->success) { + throw new \Exception(var_export($cfResult, true)); + } + $entity = $this->getEntityByResult($cfResult->result); + //아래는 추가 셋팅 ipv6 TurnOFF , //Development mode TurnOFF + $entity = $this->setCFSetting($entity, 'ipv6', 'off'); + $entity = $this->setCFSetting($entity, 'development_mode', 'off'); + $entity = $this->setCFSetting($entity, 'security_level', 'medium'); + Log::add("warning", "Record API: {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); + return $entity; + } + public function update(\App\Entities\Cloudflare\API\ZoneEntity $entity, array $fieldDatas): \App\Entities\Cloudflare\API\ZoneEntity + { + //ipv6 , //development_mode , //security_level + foreach ($fieldDatas as $field => $value) { + $entity = $this->setCFSetting($entity, $field, $value); + } + Log::add("warning", "API {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); + return $entity; + } + public function delete(\App\Entities\Cloudflare\API\ZoneEntity $entity) + { + //Zone 삭제 + $cfResult = $this->getAdapter()->delete('zones/' . $entity->getPrimaryKey()); + $cfResult = json_decode($cfResult->getBody()); + if (!$cfResult->success) { + throw new \Exception(var_export($cfResult, true)); + } + Log::add("warning", "Zone API: {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); + } + public function sync(\App\Entities\Cloudflare\API\ZoneEntity $entity): \App\Entities\Cloudflare\API\ZoneEntity + { + $cfResult = $this->getAdapter()->get('zones/' . $entity->getPrimaryKey()); + $cfResult = json_decode($cfResult->getBody()); + if (!$cfResult->success) { + throw new \Exception(var_export($cfResult, true)); + } + Log::add("warning", "Zone API: {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); + return $this->getEntityByResult($cfResult->result); + } + + protected function getCFResults_List(int $page): array + { + $this->_endPoint = is_null($this->_endPoint) ? new \Cloudflare\API\Endpoints\Zones($this->getAdapter()) : $this->_endPoint; + return $this->_endPoint->listZones('', '', $page, CF_ADAPTER_PERPAGE_MAX)->result; + } +} diff --git a/app/Controllers/Mangboard/Crawler/InvenCrawler.php b/app/Libraries/MyCrawler/Inven.php similarity index 57% rename from app/Controllers/Mangboard/Crawler/InvenCrawler.php rename to app/Libraries/MyCrawler/Inven.php index f24385a..5504ff0 100644 --- a/app/Controllers/Mangboard/Crawler/InvenCrawler.php +++ b/app/Libraries/MyCrawler/Inven.php @@ -1,21 +1,14 @@ // // - public function execute(string $board_name, string $user_id = null, ...$params): void + public function execute(): void { - try { - //추가옵션 - $this->isDebug = in_array('debug', $params); - $this->isCopy = in_array('copy', $params); - $this->setBoardName($board_name); - $this->login_process($user_id); - //실행 - $listInfos = []; - if ($this->isDebug) { - $listInfo = []; - $listInfo['title'] = 'test_title'; - $listInfo['nickname'] = 'test_name'; - $listInfo['hit'] = 1; - $listInfo['date'] = date("Y-m-d H:i:s"); - $listInfo['detail_url'] = getenv("inven.view.test.url.{$this->getBoardName()}"); - $listInfos[] = $listInfo; - } else { - $response = $this->getMySocket()->getContent(getenv("inven.list.url.{$this->getBoardName()}")); - $this->getSelector($response, getenv("inven.list.tag.{$this->getBoardName()}"))->each( - function (Crawler $node) use (&$listInfos): void { - $nickname = $node->filter(getenv("inven.list.item.nickname.tag"))->text(); - $hit = $node->filter(getenv("inven.list.item.hit.tag"))->text(); - $date = date("Y") . "-" . $node->filter(getenv("inven.list.item.date.tag"))->text(); - //title및 detail url - $link_node = $node->filter(getenv("inven.list.item.link.tag")); - $detail_url = $link_node->attr("href"); - $title = $link_node->text(); - //title에서 예외사항비교 - if (strpos($title, getenv("inven.list.tag.except.{$this->getBoardName()}")) === false) { - $listInfos[] = ['title' => $title, 'nickname' => $nickname, 'detail_url' => $detail_url, 'date' => $date, 'hit' => $hit]; - } + $listInfos = []; + if ($this->isDebug) { + $listInfo = []; + $listInfo['title'] = 'test_title'; + $listInfo['nickname'] = 'test_name'; + $listInfo['hit'] = 1; + $listInfo['date'] = date("Y-m-d H:i:s"); + $listInfo['detail_url'] = getenv("inven.view.test.url.{$this->getMyStorage()->getBoardName()}"); + $listInfos[] = $listInfo; + } else { + $response = $this->getMySocket()->getContent(getenv("inven.list.url.{$this->getMyStorage()->getBoardName()}")); + $this->getSelector($response, getenv("inven.list.tag.{$this->getMyStorage()->getBoardName()}"))->each( + function (Crawler $node) use (&$listInfos): void { + $nickname = $node->filter(getenv("inven.list.item.nickname.tag"))->text(); + $hit = $node->filter(getenv("inven.list.item.hit.tag"))->text(); + $date = date("Y") . "-" . $node->filter(getenv("inven.list.item.date.tag"))->text(); + //title및 detail url + $link_node = $node->filter(getenv("inven.list.item.link.tag")); + $detail_url = $link_node->attr("href"); + $title = $link_node->text(); + //title에서 예외사항비교 + if (strpos($title, getenv("inven.list.tag.except.{$this->getMyStorage()->getBoardName()}")) === false) { + $listInfos[] = ['title' => $title, 'nickname' => $nickname, 'detail_url' => $detail_url, 'date' => $date, 'hit' => $hit]; } - ); - } - if (!count($listInfos)) { - throw new \Exception("Target URL이 없습니다."); - } - $this->list_process(intval(getenv("inven.list.max_limit.{$this->getBoardName()}")), $listInfos); - log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다."); - } catch (\Exception $e) { - log_message("warning", sprintf( - "\n---%s 오류---\n%s\n-----------------------------------------\n", - __FUNCTION__, - $e->getMessage() - )); + } + ); } + if (!count($listInfos)) { + throw new \Exception("Target URL이 없습니다."); + } + $this->list_process(intval(getenv("inven.list.max_limit.{$this->getMyStorage()->getBoardName()}")), $listInfos); + log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다."); } } diff --git a/app/Controllers/Mangboard/Crawler/MyCrawler.php b/app/Libraries/MyCrawler/MyCrawler.php similarity index 81% rename from app/Controllers/Mangboard/Crawler/MyCrawler.php rename to app/Libraries/MyCrawler/MyCrawler.php index 6f83d45..06ae68a 100644 --- a/app/Controllers/Mangboard/Crawler/MyCrawler.php +++ b/app/Libraries/MyCrawler/MyCrawler.php @@ -1,72 +1,56 @@ _mySocket = $mySocket; + $this->_myStorage = $myStorage; } - abstract protected function getHost(): string; abstract protected function getDetailSelector(array $listInfo): array; - final protected function getBoardName(): string - { - return $this->_board_name; - } - final protected function setBoardName(string $board_name): void - { - $this->_board_name = $board_name; - } - final protected function getUserEntity(): UserEntity - { - return $this->_user_entity; - } - final protected function setUserEntity(UserEntity $user_entity): void - { - $this->_user_entity = $user_entity; - } //-----------------------필수항목-------------------// - final protected function getMySocket() + final protected function getMySocket(): WebSocket { if ($this->_mySocket === null) { - $this->_mySocket = new WebSocket($this->getHost()); + throw new \Exception("MySocket이 정의되지 않았습니다."); } return $this->_mySocket; } - final protected function createMyStorage(): MangboardStorage + final protected function getMyStorage(): MangboardStorage { - return new MangboardStorage($this->getBoardName(), $this->getUserEntity()); + if ($this->_myStorage === null) { + throw new \Exception("MyStorage가 정의되지 않았습니다."); + } + return $this->_myStorage; } final protected function getBoardsEntity(): BoardsEntity { if ($this->_boards_entity === null) { $boardsModel = new BoardsModel(); - $this->_boards_entity = $boardsModel->getEntityByID($this->getBoardName()); + $this->_boards_entity = $boardsModel->getEntityByID($this->getMyStorage()->getBoardName()); if ($this->_boards_entity === null) { - throw new \Exception(__FUNCTION__ . "=> {$this->getBoardName()}에 해당 Board 정보가 존재하지 않습니다."); + throw new \Exception(__FUNCTION__ . "=> {$this->getMyStorage()->getBoardName()}에 해당 Board 정보가 존재하지 않습니다."); } } return $this->_boards_entity; @@ -74,43 +58,10 @@ abstract class MyCrawler extends CommonController final protected function getBoardModel(): BoardModel { if ($this->_board_model === null) { - $this->_board_model = new BoardModel("mb_" . $this->getBoardName()); + $this->_board_model = new BoardModel("mb_" . $this->getMyStorage()->getBoardName()); } return $this->_board_model; } - final protected function getUserModel(): UserModel - { - if ($this->_user_model === null) { - return $this->_user_model = new UserModel(); - } - return $this->_user_model; - } - final protected function login_process(string $user_id = null): void - { - $user_id = $user_id ?? getenv("mangboard.login.default.id"); - $password = getenv("mangboard.login.default.password"); - $this->setUserEntity($this->getUserModel()->getEntityByID($user_id)); - // $response = $this->getWebLibrary($host)->getResponse( - // getenv("mangboard.host.url") . getenv("mangboard.login.url"), - // "post", - // [ - // 'form_params' => [ - // 'user_id' => $id, - // 'password' => $password, - // ], - // ] - // ); - // if ($response->getStatusCode() == 200) { - // $entity = $this->getUserModel()->getEntityByLoginCheck($id, $password); - // if ($entity === null) { - // throw new \Exception("{$id}는 회원이 아니거나 암호가 맞지 않습니다."); - // } - // } else { - // throw new \Exception("연결실패:" . $response->getStatusCode()); - // } - log_message("notice", "{$user_id}로 로그인 성공"); - } - final protected function getSelector(string $content, string $tag): Crawler { $crawler = new Crawler($content); @@ -174,7 +125,7 @@ abstract class MyCrawler extends CommonController private function media_save(int $file_sequence, string $media_tag, string $file_name, string $content): mixed { log_message("debug", __FUNCTION__ . " 원본파일 {$file_name} 작업 시작"); - $storage = $this->createMyStorage(); + $storage = clone $this->getMyStorage(); $storage->setOriginName($file_name); $storage->setOriginContent($content); $storage->setOriginMediaTag($media_tag); @@ -230,10 +181,10 @@ abstract class MyCrawler extends CommonController { //Board DB 등록작업등 //미디어관련정보 entity에 넣기 - $formDatas['title'] = $listInfo["title"]; - $formDatas['user_pid'] = $this->getUserEntity()->getPK(); - $formDatas['user_id'] = $this->getUserEntity()->getID(); - $formDatas['user_name'] = $listInfo["nickname"] != "" ? $listInfo["nickname"] : $this->getUserEntity()->getTitle(); + $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'])); diff --git a/app/Controllers/Mangboard/Crawler/SirCrawler.php b/app/Libraries/MyCrawler/Sir.php similarity index 63% rename from app/Controllers/Mangboard/Crawler/SirCrawler.php rename to app/Libraries/MyCrawler/Sir.php index d194032..87e9380 100644 --- a/app/Controllers/Mangboard/Crawler/SirCrawler.php +++ b/app/Libraries/MyCrawler/Sir.php @@ -1,22 +1,15 @@ 6 // yeeyuu | 6 | 369 | No 89372 | 2024-09-13 // - public function execute(string $board_name, string $user_id = null, ...$params): void + public function execute(): void { - try { - //추가옵션 - $this->isDebug = in_array('debug', $params); - $this->isCopy = in_array('copy', $params); - $this->setBoardName($board_name); - $this->login_process($user_id); - //실행 - $listInfos = []; - if ($this->isDebug) { - $listInfo = []; - $listInfo['title'] = 'test_title'; - $listInfo['nickname'] = 'test_name'; - $listInfo['hit'] = 1; - $listInfo['date'] = date("Y-m-d H:i:s"); - $listInfo['detail_url'] = getenv("sir.view.test.url.{$this->getBoardName()}"); - $listInfos[] = $listInfo; - } else { - $response = $this->getMySocket()->getContent(getenv("sir.list.url.{$this->getBoardName()}")); - $this->getSelector($response, getenv("sir.list.tag.{$this->getBoardName()}"))->each( - function (Crawler $node) use (&$listInfos): void { - $nickname = $node->filter(getenv("sir.list.item.nickname.tag"))->text(); - $hit = $node->filter(getenv("sir.list.item.hit.tag"))->text(); - // 작성시간은 detail에서 정의 - // $date = $node->filter(getenv("sir.list.item.date.tag"))->text(); - //title및 detail url - $link_node = $node->filter(getenv("sir.list.item.link.tag")); - // href url의 맨 앞이 /sir.kr가 빼기 - $detail_url = $this->changeURLByCrawler($link_node->attr("href")); - $title = $link_node->text(); - $listInfos[] = ['title' => $title, 'nickname' => $nickname, 'detail_url' => $detail_url, 'date' => "", 'hit' => $hit]; - } - ); - } - if (!count($listInfos)) { - throw new \Exception("Target URL이 없습니다."); - } - $this->list_process(intval(getenv("sir.list.max_limit.{$this->getBoardName()}")), $listInfos); - log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다."); - } catch (\Exception $e) { - log_message("warning", sprintf( - "\n---%s 오류---\n%s\n-----------------------------------------\n", - __FUNCTION__, - $e->getMessage() - )); + $listInfos = []; + if ($this->isDebug) { + $listInfo = []; + $listInfo['title'] = 'test_title'; + $listInfo['nickname'] = 'test_name'; + $listInfo['hit'] = 1; + $listInfo['date'] = date("Y-m-d H:i:s"); + $listInfo['detail_url'] = getenv("sir.view.test.url.{$this->getMyStorage()->getBoardName()}"); + $listInfos[] = $listInfo; + } else { + $response = $this->getMySocket()->getContent(getenv("sir.list.url.{$this->getMyStorage()->getBoardName()}")); + $this->getSelector($response, getenv("sir.list.tag.{$this->getMyStorage()->getBoardName()}"))->each( + function (Crawler $node) use (&$listInfos): void { + $nickname = $node->filter(getenv("sir.list.item.nickname.tag"))->text(); + $hit = $node->filter(getenv("sir.list.item.hit.tag"))->text(); + // 작성시간은 detail에서 정의 + // $date = $node->filter(getenv("sir.list.item.date.tag"))->text(); + //title및 detail url + $link_node = $node->filter(getenv("sir.list.item.link.tag")); + // href url의 맨 앞이 /sir.kr가 빼기 + $detail_url = $this->changeURLByCrawler($link_node->attr("href")); + $title = $link_node->text(); + $listInfos[] = ['title' => $title, 'nickname' => $nickname, 'detail_url' => $detail_url, 'date' => "", 'hit' => $hit]; + } + ); } + if (!count($listInfos)) { + throw new \Exception("Target URL이 없습니다."); + } + $this->list_process(intval(getenv("sir.list.max_limit.{$this->getMyStorage()->getBoardName()}")), $listInfos); + log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다."); } } diff --git a/app/Libraries/MyCrawler/Yamap.php b/app/Libraries/MyCrawler/Yamap.php new file mode 100644 index 0000000..203728e --- /dev/null +++ b/app/Libraries/MyCrawler/Yamap.php @@ -0,0 +1,84 @@ +getMySocket()->getContent($listInfo['detail_url']); + return array($this->getSelector($response, getenv("yamap.view.content.tag")), $listInfo); + } + //리스트내용 + //
+ //
요즘 패션
+ //
+ // + // 괴강고귀 + // + // + // | 추천 (14) | 조회 (432) + // + //
+ //
+ // + // + // + // 2024-09-14 01:53:45 + // + //
+ //
+ //
+ //

+ //

 

+ //
+ //
+ //
+ // + // + //
+ //
+ //
+ + final public function execute(): void + { + $listInfos = []; + if ($this->isDebug) { + $listInfo = []; + $listInfo['title'] = 'test_title'; + $listInfo['nickname'] = 'test_name'; + $listInfo['hit'] = 1; + $listInfo['date'] = date("Y-m-d H:i:s"); + $listInfo['detail_url'] = getenv("yamap.view.test.url.{$this->getMyStorage()->getBoardName()}"); + $listInfos[] = $listInfo; + } else { + $response = $this->getMySocket()->getContent(getenv("yamap.list.url.{$this->getMyStorage()->getBoardName()}")); + $this->getSelector($response, getenv("yamap.list.tag.{$this->getMyStorage()->getBoardName()}"))->each( + function (Crawler $node) use (&$listInfos): void { + $nickname = $node->filter(getenv("yamap.list.item.nickname.tag"))->text(); + $hit = $node->filter(getenv("yamap.list.item.hit.tag"))->text(); + $date = $node->filter(getenv("yamap.list.item.date.tag"))->text(); + //title및 detail url + $link_node = $node->filter(getenv("yamap.list.item.link.tag")); + $detail_url = $link_node->attr("href"); + $title = $link_node->children()->last()->text(); + //title에서 예외사항비교 + if (strpos($title, getenv("yamap.list.tag.except.{$this->getMyStorage()->getBoardName()}")) === false) { + $listInfos[] = ['title' => $title, 'nickname' => $nickname, 'detail_url' => $detail_url, 'date' => $date, 'hit' => $hit]; + } + } + ); + } + if (!count($listInfos)) { + throw new \Exception("Target URL이 없습니다."); + } + $this->list_process(intval(getenv("yamap.list.max_limit.{$this->getMyStorage()->getBoardName()}")), $listInfos); + log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다."); + } +} diff --git a/app/Controllers/Mangboard/Crawler/YamoonCrawler.php b/app/Libraries/MyCrawler/Yamoon.php similarity index 59% rename from app/Controllers/Mangboard/Crawler/YamoonCrawler.php rename to app/Libraries/MyCrawler/Yamoon.php index 4213fbd..3d50614 100644 --- a/app/Controllers/Mangboard/Crawler/YamoonCrawler.php +++ b/app/Libraries/MyCrawler/Yamoon.php @@ -1,21 +1,14 @@ @@ -60,50 +53,36 @@ class YamoonCrawler extends MyCrawler // 6 // yeeyuu | 6 | 369 | No 89372 | 2024-09-13 // - public function execute(string $board_name, string $user_id = null, ...$params): void + public function execute(): void { - try { - //추가옵션 - $this->isDebug = in_array('debug', $params); - $this->isCopy = in_array('copy', $params); - $this->setBoardName($board_name); - $this->login_process($user_id); - //실행 - $listInfos = []; - if ($this->isDebug) { - $listInfo = []; - $listInfo['title'] = 'test_title'; - $listInfo['nickname'] = 'test_name'; - $listInfo['hit'] = 1; - $listInfo['date'] = date("Y-m-d H:i:s"); - $listInfo['detail_url'] = getenv("yamoon.view.test.url.{$this->getBoardName()}"); - $listInfos[] = $listInfo; - } else { - $response = $this->getMySocket()->getContent(getenv("yamoon.list.url.{$this->getBoardName()}")); - $this->getSelector($response, getenv("yamoon.list.tag.{$this->getBoardName()}"))->each( - function (Crawler $node) use (&$listInfos): void { - //title및 detail url - $link_node = $node->filter(getenv("yamoon.list.item.link.tag")); - $detail_url = $link_node->attr("href"); - $title = $link_node->text(); - //기타정보기 |로 구분되어 있어 작업 - $info_node = $node->filter(getenv("yamoon.list.item.info.tag")); - $infos = explode("|", $info_node->text()); - $listInfos[] = ['title' => $title, 'detail_url' => $detail_url, 'nickname' => trim($infos[0]), 'hit' => trim($infos[2]), 'date' => trim($infos[4])]; - } - ); - } - if (!count($listInfos)) { - throw new \Exception("Target URL이 없습니다."); - } - $this->list_process(intval(getenv("yamoon.list.max_limit.{$this->getBoardName()}")), $listInfos); - log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다."); - } catch (\Exception $e) { - log_message("warning", sprintf( - "\n---%s 오류---\n%s\n-----------------------------------------\n", - __FUNCTION__, - $e->getMessage() - )); + $listInfos = []; + if ($this->isDebug) { + $listInfo = []; + $listInfo['title'] = 'test_title'; + $listInfo['nickname'] = 'test_name'; + $listInfo['hit'] = 1; + $listInfo['date'] = date("Y-m-d H:i:s"); + $listInfo['detail_url'] = getenv("yamoon.view.test.url.{$this->getMyStorage()->getBoardName()}"); + $listInfos[] = $listInfo; + } else { + $response = $this->getMySocket()->getContent(getenv("yamoon.list.url.{$this->getMyStorage()->getBoardName()}")); + $this->getSelector($response, getenv("yamoon.list.tag.{$this->getMyStorage()->getBoardName()}"))->each( + function (Crawler $node) use (&$listInfos): void { + //title및 detail url + $link_node = $node->filter(getenv("yamoon.list.item.link.tag")); + $detail_url = $link_node->attr("href"); + $title = $link_node->text(); + //기타정보기 |로 구분되어 있어 작업 + $info_node = $node->filter(getenv("yamoon.list.item.info.tag")); + $infos = explode("|", $info_node->text()); + $listInfos[] = ['title' => $title, 'detail_url' => $detail_url, 'nickname' => trim($infos[0]), 'hit' => trim($infos[2]), 'date' => trim($infos[4])]; + } + ); } + if (!count($listInfos)) { + throw new \Exception("Target URL이 없습니다."); + } + $this->list_process(intval(getenv("yamoon.list.max_limit.{$this->getMyStorage()->getBoardName()}")), $listInfos); + log_message("notice", __FUNCTION__ . " 작업이 완료되었습니다."); } } diff --git a/app/Libraries/MySocket/CloudflareSocket.php b/app/Libraries/MySocket/CloudflareSocket.php index eb648d6..95152b2 100644 --- a/app/Libraries/MySocket/CloudflareSocket.php +++ b/app/Libraries/MySocket/CloudflareSocket.php @@ -2,13 +2,14 @@ namespace App\Libraries\MySocket; -use App\Libraries\CommonLibrary; -use App\Models\Cloudflare\AccountModel; +use Cloudflare\API\Endpoints\Zones; +use Cloudflare\API\Endpoints\DNS; +use Cloudflare\API\Endpoints\Accounts; use Cloudflare\API\Auth\APIKey; use Cloudflare\API\Adapter\Guzzle; -use Cloudflare\API\Endpoints\Zones; -use Cloudflare\API\Endpoints\Accounts; -use Cloudflare\API\Endpoints\DNS; +use App\Models\Cloudflare\AccountModel; +use App\Libraries\CommonLibrary; +use App\Entities\Cloudflare\AccountEntity; class CloudflareSocket extends CommonLibrary { @@ -24,17 +25,6 @@ class CloudflareSocket extends CommonLibrary $this->initAdapters(); self::$_request_max = getenv("cfmgr.request.max"); } - final public function getAPIKey(): string - { - if ($this->_apikey == "") { - throw new \Exception("APIKey가 정의되지 않았습니다."); - } - return $this->_apikey; - } - final public function setAPIKey(string $apikey): void - { - $this->_apikey = $apikey; - } final protected function getAccountModel(): AccountModel { if ($this->_accountModel === null) { @@ -50,11 +40,10 @@ class CloudflareSocket extends CommonLibrary ); } } - - private function getAdapter(): Guzzle + public function getAdapter(string $apikey): Guzzle { - if (!array_key_exists($this->getAPIKey(), $this->_clients)) { - throw new \Exception(+__FUNCTION__ . " => {$this->getAPIKey()}에 해당하는 Adapter를 찾을수 없습니다."); + 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)); @@ -63,19 +52,18 @@ class CloudflareSocket extends CommonLibrary log_message('warning', sprintf("--Cloudflare API Call %s초 대기 종료--", self::$_request_timewait)); } self::$_request++; - return $this->_clients[$this->getAPIKey()]; + return $this->_clients[$apikey]; } - - public function getAccount(): Accounts + public function getAccount(string $apikey): Accounts { - return new Accounts($this->getAdapter()); + return new Accounts($this->getAdapter($apikey)); } - public function getZone(): Zones + public function getZone(string $apikey): Zones { - return new Zones($this->getAdapter()); + return new Zones($this->getAdapter($apikey)); } - public function getRecord(): DNS + public function getRecord(string $apikey): DNS { - return new DNS($this->getAdapter()); + return new DNS($this->getAdapter($apikey)); } } diff --git a/app/Libraries/MyStorage/MangboardStorage.php b/app/Libraries/MyStorage/MangboardStorage.php index b9a8071..bd2f8d2 100644 --- a/app/Libraries/MyStorage/MangboardStorage.php +++ b/app/Libraries/MyStorage/MangboardStorage.php @@ -20,6 +20,20 @@ class MangboardStorage extends FileStorage $this->_board_name = $board_name; $this->_user_entity = $user_entity; } + final public function getBoardName(): string + { + if ($this->_board_name === "") { + throw new \Exception("BoardName이 정의되지 않았습니다."); + } + return $this->_board_name; + } + final public function getUserEntity(): UserEntity + { + if ($this->_user_entity === null) { + throw new \Exception("UserEntity가 정의되지 않았습니다."); + } + return $this->_user_entity; + } final protected function getFileModel(): FileModel { if ($this->_fileModel === null) { @@ -83,7 +97,7 @@ class MangboardStorage extends FileStorage $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['file_name'] = $this->getOriginName(); + $formDatas[FileModel::TITLE] = $this->getOriginName(); $formDatas['file_type'] = $this->getMimeType(); $formDatas['file_caption'] = $this->getOriginName(); $formDatas['file_alt'] = $this->getOriginName(); diff --git a/app/Models/Cloudflare/AccountModel.php b/app/Models/Cloudflare/AccountModel.php index 4bcf764..2c1f488 100644 --- a/app/Models/Cloudflare/AccountModel.php +++ b/app/Models/Cloudflare/AccountModel.php @@ -3,25 +3,28 @@ namespace App\Models\Cloudflare; use App\Entities\Cloudflare\AccountEntity; -use CodeIgniter\Model; -use stdClass; +use App\Models\CommonModel; -class AccountModel extends Model +class AccountModel extends CommonModel { - protected $table = 'cloudflareaccount'; - protected $primaryKey = 'uid'; + + const TABLE = "cloudflarerecord"; + const PK = "uid"; + const TITLE = "id"; + protected $table = self::TABLE; + protected $primaryKey = self::PK; protected $useAutoIncrement = false; protected $returnType = AccountEntity::class; //object,array,entity명::class - protected $allowedFields = ['uid', 'id', 'apikey', 'oldkey', 'type', 'status', 'updated_at', 'created_at']; + protected $allowedFields = [self::PK, self::TITLE, 'apikey', 'oldkey', 'type', 'status', 'updated_at', 'created_at']; protected $useTimestamps = true; public function getTitleField(): string { - return 'id'; + return self::TITLE; } public function getFieldRule(string $field, array $rules): array { switch ($field) { - case "id": + case self::TITLE: $rules[$field] = "required|valid_emailvalid_email|is_unique[cloudflareauth.id]"; case "apikey": $rules[$field] = $rules[$field] = "required|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]";; diff --git a/app/Models/Cloudflare/RecordModel.php b/app/Models/Cloudflare/RecordModel.php index 041afa4..c51e45c 100644 --- a/app/Models/Cloudflare/RecordModel.php +++ b/app/Models/Cloudflare/RecordModel.php @@ -2,83 +2,99 @@ namespace App\Models\Cloudflare\API; -use App\Entities\Cloudflare\API\ZoneEntity; -use App\Entities\Cloudflare\API\RecordEntity; -use App\Libraries\Log\Log; use CodeIgniter\Model; +use App\Entities\Cloudflare\ZoneEntity; +use App\Entities\Cloudflare\RecordEntity; class RecordModel extends Model { - const PARENT_FIELD = "zone_uid"; - protected $DBGroup = 'default'; - protected $table = 'cloudflarerecord'; - protected $primaryKey = 'uid'; + const TABLE = "cloudflarerecord"; + const PK = "uid"; + const TITLE = "host"; + const PARENT = "zone_uid"; + protected $table = self::TABLE; + protected $primaryKey = self::PK; protected $useAutoIncrement = false; - protected $insertID = 0; - protected $returnType = 'array'; //object,array,entity명::class - protected $useSoftDeletes = false; - protected $protectFields = true; - protected $allowedFields = ['uid', 'zone_uid', 'type', 'host', 'content', 'ttl', 'proxiable', 'proxied', 'fixed', 'locked', 'updated_at', 'crated_at']; - - // Dates + protected $returnType = RecordEntity::class; //object,array,entity명::class + protected $allowedFields = [self::PK, self::PARENT, 'type', self::TITLE, 'content', 'ttl', 'proxiable', 'proxied', 'fixed', 'locked', 'updated_at', 'crated_at']; protected $useTimestamps = true; - protected $dateFormat = 'datetime'; - protected $createdField = 'created_at'; - protected $updatedField = 'updated_at'; - protected $deletedField = 'deleted_at'; - // Validation - protected $validationRules = [ - 'uid' => 'if_exist|min_length[10]|max_length[200]', - 'zone_uid' => 'if_exist|min_length[10]|max_length[200]', - 'host' => 'if_exist|string', - 'content' => 'if_exist|string', - 'type' => 'if_exist|string', - 'ttl' => 'if_exist|numeric', - 'proxiable' => 'if_exist|in_list[on,off]', - 'proxied' => 'if_exist|in_list[on,off]', - 'fixed' => 'if_exist|in_list[on,off]', - 'locked' => 'if_exist|in_list[on,off]', - 'updated_at' => 'if_exist|valid_date', - 'created_at' => 'if_exist|valid_date', - ]; - protected $validationMessages = []; - protected $skipValidation = true; - protected $cleanValidationRules = true; - - // Callbacks - protected $allowCallbacks = true; - protected $beforeInsert = []; - protected $afterInsert = []; - protected $beforeUpdate = []; - protected $afterUpdate = []; - protected $beforeFind = []; - protected $afterFind = []; - protected $beforeDelete = []; - protected $afterDelete = []; - - public function getTableName() + public function __construct() { - return $this->table; + parent::__construct(); } - - public function getEntity(string $uid): RecordEntity + public function getTitleField(): string { - $entity = $this->asObject(RecordEntity::class)->where('uid', $uid)->first(); - if (is_null($entity)) { - throw new \Exception(__METHOD__ . "에서 {$uid} 해당 정보가 없습니다."); + return self::TITLE; + } + public function getFieldRule(string $field, array $rules): array + { + switch ($field) { + case self::PARENT: + $rules[$field] = "required|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]";; + break; + case self::TITLE: + case "content": + case "type": + $rules[$field] = "required|trim|string"; + break; + case "ttl": + $rules[$field] = "if_exist|numeric"; + break; + case "proxied": + case "proxiable": + case "fixed": + case "locked": + $rules[$field] = "if_exist|in_list[on,off]"; + break; + default: + $rules = parent::getFieldRule($field, $rules); + break; } - return $entity; + return $rules; } - public function getEntitys(array $wheres) + public function getEntityByPK(int $uid): null | RecordEntity { - return $this->asObject(RecordEntity::class)->where($wheres)->findAll(); + $this->where(self::PK, $uid); + return $this->getEntity(); } - public function getEntitysByZone(ZoneEntity $zone) + public function getEntityByID(string $id): null | RecordEntity { - return $this->getEntitys([self::PARENT_FIELD => $zone->getPrimaryKey()]); + $this->where(self::TITLE, $id); + return $this->getEntity(); } + //create용 + public function create(array $formDatas = []): RecordEntity + { + return $this->create_process(new RecordEntity(), $formDatas); + } + //modify용 + public function modify(RecordEntity $entity, array $formDatas): RecordEntity + { + return $this->modify_process($entity, $formDatas); + } + public function getEntitysByParent(ZoneEntity $zone_entity) + { + $this->where(self::PARENT, $zone_entity->getPK()); + return $this->getEntitys(); + } + //도메인이 이미 존재하는지 체크 + public function isUniqueHost($zone_uid, string $host, string $content): bool + { + $this->where(self::PARENT, $zone_uid); + $this->where('host', $host); + $this->where('content', $content); + return is_null($this->first()) ? true : false; + } + //CDN값 수정 못하는 고정 Record 처리 + public function setFixedCDNRecord(array $hosts) + { + if (count($hosts)) { + $this->whereIn('host', $hosts)->set(['fixed' => 'on'])->update(); + log_message("notice", "-----set fixed Records " . implode(",", $hosts) . "처리 완료-----"); + } + } //Index 검색어용 public function setIndexWordFilter(string $word) { @@ -92,24 +108,6 @@ class RecordModel extends Model } public function setIndexOrderBy($field, $order = 'ASC') { - $this->orderBy("zone_uid ASC, host ASC, {$field} {$order}"); - } - - //도메인이 이미 존재하는지 체크 - public function isUniqueHost($zone_uid, string $host, string $content): bool - { - $this->where('zone_uid', $zone_uid); - $this->where('host', $host); - $this->where('content', $content); - return is_null($this->first()) ? true : false; - } - - //CDN값 수정 못하는 고정 Record 처리 - public function setFixedCDNRecord(array $hosts) - { - if (count($hosts)) { - $this->whereIn('host', $hosts)->set(['fixed' => 'on'])->update(); - Log::add("notice", "-----set fixed Records " . implode(",", $hosts) . "처리 완료-----"); - } + $this->orderBy(self::PARENT . " ASC, host ASC, {$field} {$order}"); } } diff --git a/app/Models/Cloudflare/ZoneModel.php b/app/Models/Cloudflare/ZoneModel.php index 1e6865a..5066156 100644 --- a/app/Models/Cloudflare/ZoneModel.php +++ b/app/Models/Cloudflare/ZoneModel.php @@ -2,37 +2,48 @@ namespace App\Models\Cloudflare; +use App\Models\CommonModel; +use App\Models\Cloudflare\API\RecordModel; use App\Entities\Cloudflare\ZoneEntity; -use CodeIgniter\Model; -use stdClass; +use App\Entities\Cloudflare\AccountEntity; -class ZoneModel extends Model +class ZoneModel extends CommonModel { - protected $table = 'cloudflarezone'; - protected $primaryKey = 'uid'; + const TABLE = "cloudflarezone"; + const PK = "uid"; + const TITLE = "domain"; + const PARENT = "account_uid"; + protected $table = self::TABLE; + protected $primaryKey = self::PK; protected $useAutoIncrement = false; protected $returnType = ZoneEntity::class; //object,array,entity명::class - protected $allowedFields = ['uid', 'account_uid', 'uid', 'domain', 'name_servers', 'original_name_servers', 'plan', 'development_mode', 'ipv6', 'security_level', 'status', 'updated_at', 'crated_at ']; + protected $allowedFields = [self::PK, self::PARENT, self::TITLE, 'name_servers', 'original_name_servers', 'plan', 'development_mode', 'ipv6', 'security_level', 'status', 'updated_at', 'crated_at ']; protected $useTimestamps = true; - const TITLE_FIELD = "id"; - const PARENT_FIELD = "account_uid"; + public function __construct() + { + parent::__construct(); + } + public function getTitleField(): string + { + return self::TITLE; + } public function getFieldRule(string $field, array $rules): array { switch ($field) { - case "account_uid": - $rules[$field] = $rules[$field] = "required|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]";; + case self::PARENT: + $rules[$field] = "required|regex_match[/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/]";; break; - case "domain": + case self::TITLE: case "plan": - $rules[$field] = "required|trim|string"; + $rules[$field] = "required|trim|string"; break; case "name_servers": case "security_level": - $rules[$field] = "if_exist|trim|string"; + $rules[$field] = "if_exist|trim|string"; break; case "development_mode": case "ipv6": - $rules[$field] = "if_exist|in_list[on,off]"; + $rules[$field] = "if_exist|in_list[on,off]"; break; default: $rules = parent::getFieldRule($field, $rules); @@ -42,15 +53,19 @@ class ZoneModel extends Model } public function getEntityByPK(int $uid): null | ZoneEntity { - $this->where($this->getPKField(), $uid); + $this->where(self::PK, $uid); return $this->getEntity(); } public function getEntityByID(string $id): null | ZoneEntity { - $this->where($this->getTitleField(), $id); + $this->where(self::TITLE, $id); return $this->getEntity(); } - + public function getEntitysByParent(AccountEntity $account_entity) + { + $this->where(self::PARENT, $account_entity->getPK()); + return $this->getEntitys(); + } //create용 public function create(array $formDatas = []): ZoneEntity { @@ -65,26 +80,24 @@ class ZoneModel extends Model //도메인이 이미 존재하는지 체크 public function isUniqueDomain(string $account_uid, string $domain): bool { - $this->where('account_uid', $account_uid); - $this->where('domain', $domain); + $this->where(self::PARENT, $account_uid); + $this->where(self::TITLE, $domain); return is_null($this->first()) ? true : false; } - //Index 검색용 - public function setIndexWordFilter(string $word) + public function setIndexWordFilter(string $word): void { - $subquery = $this->db->table('cloudflarerecord')->select('zone_uid')->like('content', $word, 'both'); - $this->like('domain', $word, 'both'); //befor , after , both - $this->orWhereIn('uid', $subquery); + $subquery = $this->db->table(RecordModel::TABLE)->select(RecordModel::PARENT)->like('content', $word, 'both'); + $this->like(self::TITLE, $word, 'both'); //befor , after , both + $this->orWhereIn(self::PK, $subquery); } - - public function setIndexDateFilter($start, $end) + public function setIndexDateFilter($start, $end): void { $this->where('created_at >=', $start); $this->where('created_at <=', $end); } public function setIndexOrderBy($field, $order = 'ASC') { - $this->orderBy("domain ASC, {$field} {$order}"); + $this->orderBy(self::TITLE . " ASC, {$field} {$order}"); } } diff --git a/app/Models/CommonModel.php b/app/Models/CommonModel.php index c5bc02f..c0d32c8 100644 --- a/app/Models/CommonModel.php +++ b/app/Models/CommonModel.php @@ -51,10 +51,6 @@ abstract class CommonModel extends Model parent::__construct(); } abstract public function getTitleField(): string; - final public function getTable(): string - { - return $this->table; - } final public function getPKField(): string { return $this->primaryKey; @@ -191,7 +187,9 @@ abstract class CommonModel extends Model var_export($this->errors(), true) )); } + log_message("debug", $this->table . "=> " . __FUNCTION__ . " 작업 완료"); } + log_message("debug", $this->table . "=> " . __FUNCTION__ . " 데이터 변환없음"); return $entity; } final protected function create_process($entity, array $formDatas): mixed @@ -209,7 +207,6 @@ abstract class CommonModel extends Model $pkField = $this->getPKField(); $entity->$pkField = $this->getInsertID(); } - // log_message("debug", $this->getTable() . " CREATE 작업 완료"); return $entity; } final protected function modify_process($entity, array $formDatas): mixed @@ -222,7 +219,6 @@ abstract class CommonModel extends Model $entity->$field = $this->convertEntityData($field, $formDatas); } $this->save_process($entity); - // log_message("debug", $this->getTable() . " MODIFY 작업 완료"); return $entity; } } diff --git a/app/Models/Mangboard/BoardModel.php b/app/Models/Mangboard/BoardModel.php index 6aee6a1..fe72b7a 100644 --- a/app/Models/Mangboard/BoardModel.php +++ b/app/Models/Mangboard/BoardModel.php @@ -3,8 +3,6 @@ namespace App\Models\Mangboard; use App\Entities\Mangboard\BoardEntity; -use App\Entities\Mangboard\BoardsEntity; -use App\Entities\Mangboard\UserEntity; use App\Models\CommonModel; // +-----------------+---------------------+------+-----+---------------------+----------------+ @@ -70,11 +68,15 @@ use App\Models\CommonModel; class BoardModel extends CommonModel { - protected $primaryKey = 'pid'; + // const TABLE = ""; + const PK = "pid"; + const TITLE = "title"; + // protected $table = self::TABLE; + protected $primaryKey = self::PK; protected $returnType = BoardEntity::class; protected $allowedFields = [ "gid", - "title", + self::TITLE, "user_pid", "user_id", "user_name", @@ -91,9 +93,13 @@ class BoardModel extends CommonModel $this->table = $table; parent::__construct(); } + public function getTable(): string + { + return $this->table; + } public function getTitleField(): string { - return 'title'; + return self::TITLE; } public function getFieldRule(string $field, array $rules): array { diff --git a/app/Models/Mangboard/BoardsModel.php b/app/Models/Mangboard/BoardsModel.php index 8175d9b..cec01e4 100644 --- a/app/Models/Mangboard/BoardsModel.php +++ b/app/Models/Mangboard/BoardsModel.php @@ -61,11 +61,14 @@ use App\Entities\Mangboard\BoardsEntity; class BoardsModel extends CommonModel { - protected $table = 'mb_boards'; - protected $primaryKey = 'pid'; + const TABLE = "mb_boards"; + const PK = "pid"; + const TITLE = "board_name"; + protected $table = self::TABLE; + protected $primaryKey = self::PK; protected $returnType = BoardsEntity::class; protected $allowedFields = [ - "board_name", + self::TITLE, "board_type", "description", "list_level", @@ -86,7 +89,7 @@ class BoardsModel extends CommonModel } public function getTitleField(): string { - return 'board_name'; + return self::TITLE; } public function getFieldRule(string $field, array $rules): array { diff --git a/app/Models/Mangboard/FileModel.php b/app/Models/Mangboard/FileModel.php index 6d5c748..4bb7d52 100644 --- a/app/Models/Mangboard/FileModel.php +++ b/app/Models/Mangboard/FileModel.php @@ -2,11 +2,7 @@ namespace App\Models\Mangboard; -use App\Entities\Mangboard\BoardEntity; -use App\Entities\Mangboard\BoardsEntity; use App\Entities\Mangboard\FileEntity; -use App\Entities\Mangboard\UserEntity; -use App\Libraries\MyStorage\MangboardStorage; use App\Models\CommonModel; // +------------------+----------------------+------+-----+---------------------+----------------+ @@ -36,8 +32,11 @@ use App\Models\CommonModel; class FileModel extends CommonModel { - protected $table = 'mb_files'; - protected $primaryKey = 'pid'; + const TABLE = "mb_files"; + const PK = "pid"; + const TITLE = "file_name"; + protected $table = self::TABLE; + protected $primaryKey = self::PK; protected $returnType = FileEntity::class; protected $allowedFields = [ "user_pid", @@ -45,7 +44,7 @@ class FileModel extends CommonModel "board_pid", "board_name", "table_name", - "file_name", + self::TITLE, "file_path", "file_type", "file_caption", @@ -61,7 +60,7 @@ class FileModel extends CommonModel } public function getTitleField(): string { - return 'file_name'; + return self::TITLE; } public function getFieldRule(string $field, array $rules): array { diff --git a/app/Models/Mangboard/UserModel.php b/app/Models/Mangboard/UserModel.php index 6002401..a3ce736 100644 --- a/app/Models/Mangboard/UserModel.php +++ b/app/Models/Mangboard/UserModel.php @@ -96,13 +96,16 @@ use App\Models\CommonModel; class UserModel extends CommonModel { - protected $table = 'mb_users'; - protected $primaryKey = 'pid'; + const TABLE = "mb_users"; + const PK = "pid"; + const TITLE = "user_name"; + protected $table = self::TABLE; + protected $primaryKey = self::PK; protected $returnType = UserEntity::class; protected $allowedFields = [ "user_id", "passwd", - "user_name", + self::TITLE, "user_email", "user_state", "user_level", @@ -114,7 +117,7 @@ class UserModel extends CommonModel } public function getTitleField(): string { - return 'user_name'; + return self::TITLE; } public function getFieldRule(string $field, array $rules): array { @@ -150,6 +153,16 @@ class UserModel extends CommonModel $this->where('user_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); + } public function getEntityByLoginCheck(string $id, string $password): null|UserEntity { $this->where('user_id', $id); @@ -220,15 +233,4 @@ class UserModel extends CommonModel } return $entity; } - - //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); - } } diff --git a/app/Models/SNSUserModel.php b/app/Models/SNSUserModel.php index 432da8f..64fc90f 100644 --- a/app/Models/SNSUserModel.php +++ b/app/Models/SNSUserModel.php @@ -7,8 +7,11 @@ use App\Models\CommonModel; class SNSUserModel extends CommonModel { - protected $table = 'sns_users'; - protected $primaryKey = 'uid'; + 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", @@ -23,7 +26,7 @@ class SNSUserModel extends CommonModel } public function getTitleField(): string { - return 'name'; + return self::TITLE; } public function getFieldRule(string $field, array $rules): array { diff --git a/app/Models/UserModel.php b/app/Models/UserModel.php index fe50f25..168eadf 100644 --- a/app/Models/UserModel.php +++ b/app/Models/UserModel.php @@ -7,8 +7,11 @@ use App\Models\CommonModel; class UserModel extends CommonModel { - protected $table = 'users'; - protected $primaryKey = 'uid'; + const TABLE = "users"; + const PK = "uid"; + const TITLE = "name"; + protected $table = self::TABLE; + protected $primaryKey = self::PK; protected $returnType = UserEntity::class; protected $allowedFields = [ "id",