From db6916451b37dec367d56647c668e88a0eac56c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=EC=B5=9C=EC=A4=80=ED=9D=A0?= Date: Fri, 13 Sep 2024 18:33:27 +0900 Subject: [PATCH] Automation init...3 --- app/Config/Routes.php | 3 +- app/Controllers/CrawlerController.php | 22 +-- app/Entities/Mangboard/BoardsEntity.php | 31 ++++ app/Libraries/Cloudflare/Account.php | 80 +++++++++ .../Cloudflare/CloudflareLibrary.php | 119 ++++++++++++++ app/Libraries/Cloudflare/Firewall.php | 96 +++++++++++ .../Cloudflare/Magictransit/AllowList.php | 103 ++++++++++++ app/Libraries/Cloudflare/Record.php | 127 +++++++++++++++ app/Libraries/Cloudflare/Zone.php | 152 ++++++++++++++++++ app/Libraries/MyCrawler/MyCrawlerLibrary.php | 6 +- app/Libraries/MyCrawler/YamapLibrary.php | 113 ++----------- app/Libraries/MySocket/WebLibrary.php | 69 +++----- .../MyStorage/Mangboard/BoardsLibrary.php | 108 +++++++++++++ .../MyStorage/Mangboard/FileLibrary.php | 73 +++++---- .../MyStorage/Mangboard/UserLibrary.php | 54 +++++++ app/Models/CommonModel.php | 5 +- app/Models/Mangboard/BoardModel.php | 1 - app/Models/Mangboard/BoardsModel.php | 143 ++++++++++++++++ app/Models/Mangboard/UserModel.php | 21 ++- 19 files changed, 1124 insertions(+), 202 deletions(-) create mode 100644 app/Entities/Mangboard/BoardsEntity.php create mode 100644 app/Libraries/Cloudflare/Account.php create mode 100644 app/Libraries/Cloudflare/CloudflareLibrary.php create mode 100644 app/Libraries/Cloudflare/Firewall.php create mode 100644 app/Libraries/Cloudflare/Magictransit/AllowList.php create mode 100644 app/Libraries/Cloudflare/Record.php create mode 100644 app/Libraries/Cloudflare/Zone.php create mode 100644 app/Libraries/MyStorage/Mangboard/BoardsLibrary.php create mode 100644 app/Libraries/MyStorage/Mangboard/UserLibrary.php create mode 100644 app/Models/Mangboard/BoardsModel.php diff --git a/app/Config/Routes.php b/app/Config/Routes.php index 5dd9457..821edbe 100644 --- a/app/Config/Routes.php +++ b/app/Config/Routes.php @@ -23,7 +23,8 @@ $routes->group('admin', ['namespace' => 'App\Controllers\Admin', 'filter' => 'au }); $routes->group('crawler', ['namespace' => 'App\Controllers'], function ($routes) { $routes->cli('yamap', 'CrawlerController::yamap'); - $routes->cli('yamap/(:any)', 'CrawlerController::yamap/$1'); + $routes->cli('yamap/(:alphanum)/(:any)', 'CrawlerController::yamap/$1/$2'); + $routes->cli('yamap/(:alphanum)/(:any)/(:any)', 'CrawlerController::yamap/$1/$2/$3'); }); $routes->group('mangboard', ['namespace' => 'App\Controllers\Mangboard'], function ($routes) { $routes->group('user', function ($routes) { diff --git a/app/Controllers/CrawlerController.php b/app/Controllers/CrawlerController.php index 20d2f5e..25cb947 100644 --- a/app/Controllers/CrawlerController.php +++ b/app/Controllers/CrawlerController.php @@ -4,29 +4,23 @@ namespace App\Controllers; use App\Libraries\MyCrawler\YamapLibrary as MyCrawler; use App\Controllers\CommonController; +use App\Libraries\MyStorage\Mangboard\UserLibrary; use App\Models\Mangboard\UserModel; class CrawlerController extends CommonController { - public function yamap(...$params): string + public function yamap(string $id = "", string $password = "", string $debug = "false"): string { try { + $id = $id === "" ? getenv("mangboard.login.default.id") : $id; + $password = $password === "" ? getenv("mangboard.login.default.password") : $password; //1. 사이트 로그인 처리 - $userModel = new UserModel(); - $userEntity = $userModel->getEntityByID("idcjp"); - // $daemonidc = new MySocketLibrary(getenv('daemonidc.host.url')); - // $daemonidc->setDebug($isDebug); - // $daemonidc->login( - // getenv('daemonidc.login.url'), - // getenv('daemonidc.login.user_id'), - // getenv('daemonidc.login.user_password') - // ); + $user_library = new UserLibrary(); + $user_entity = $user_library->login(getenv("mangboard.host.url"), $id, $password); //2. 필요한 로그인한 사용자정보,Socket,Storage 정의후 Crawler에게 전달. $crawler = new MyCrawler(); - $crawler->setUserEntity($userEntity); - if (in_array("debug", $params)) { - $crawler->setDebug(true); - } + $crawler->setUserEntity($user_entity); + $crawler->setDebug($debug === "true" ? true : false); $crawler->execute(); return "완료되었습니다."; } catch (\Exception $e) { diff --git a/app/Entities/Mangboard/BoardsEntity.php b/app/Entities/Mangboard/BoardsEntity.php new file mode 100644 index 0000000..813bbf1 --- /dev/null +++ b/app/Entities/Mangboard/BoardsEntity.php @@ -0,0 +1,31 @@ +getPK()}|{$this->getTitle()}"; + } + public function getTitle(): string + { + return $this->attributes['title']; + } + public function setTitle(string $title): void + { + $this->attributes['title'] = $title; + } + //Common Function + + public function getPK(): int + { + return $this->attributes['pid']; + } + public function getListLevel(): int + { + return $this->attributes['list_level']; + } +} diff --git a/app/Libraries/Cloudflare/Account.php b/app/Libraries/Cloudflare/Account.php new file mode 100644 index 0000000..3ff0f68 --- /dev/null +++ b/app/Libraries/Cloudflare/Account.php @@ -0,0 +1,80 @@ +_model = new \App\Models\Cloudflare\API\AccountModel(); + } + protected function setAdapter() + { + if (!is_null($this->_adapter)) { + throw new \Exception("Adapter가 이미 지정되었습니다."); + } + $apikey = new \Cloudflare\API\Auth\APIKey( + $this->getParent()->getAuthId(), + $this->getParent()->getAuthKey() + ); + $this->_adapter = new \Cloudflare\API\Adapter\Guzzle($apikey); + // throw new \Exception(var_export($this->_adapter, true)); + } + public function getClassName() + { + return 'Account'; + } + protected function getEntityByResult(\stdClass $cfResult): \App\Entities\Cloudflare\API\AccountEntity + { + // dd($cfResult);exit; + // [ + // {"id":"078e88a7735965b661715af13031ecb0", + // "name":"Cloudwin002@idcjp.jp's Account", + // "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"} + // ] + $entity = is_null($this->_entity) ? new \App\Entities\Cloudflare\API\AccountEntity() : $this->_entity; + $entity->uid = $cfResult->id; + $entity->auth_uid = $this->getParent()->getPrimaryKey(); + $entity->title = $cfResult->name; + $entity->type = $cfResult->type; + $entity->status = $this->getParent()->status; + $entity->updated_at = $cfResult->created_on; + $entity->created_at = $cfResult->created_on; + return $entity; + } + + public function insert(array $fieldDatas): \App\Entities\Cloudflare\API\AccountEntity + { + $options = [ + 'name' => $fieldDatas['name'], + 'type' => isset($fieldDatas['type']) ? $fieldDatas['type'] : 'standard', + ]; + $cfResult = $this->getAdapter()->post('accounts', $options); + $cfResult = json_decode($cfResult->getBody()); + if (!$cfResult->success) { + throw new \Exception(var_export($cfResult, true)); + } + $entity = $this->getEntityByResult($cfResult->result); + Log::add("warning", "Account API: {$entity->getTitle()} " . __FUNCTION__ . " 완료하였습니다."); + return $entity; + } + protected function getCFResults_List(int $page): array + { + $this->_endPoint = is_null($this->_endPoint) ? new \Cloudflare\API\Endpoints\Accounts($this->getAdapter()) : $this->_endPoint; + return $this->_endPoint->listAccounts($page, CF_ADAPTER_PERPAGE_MAX)->result; + } +} diff --git a/app/Libraries/Cloudflare/CloudflareLibrary.php b/app/Libraries/Cloudflare/CloudflareLibrary.php new file mode 100644 index 0000000..1911179 --- /dev/null +++ b/app/Libraries/Cloudflare/CloudflareLibrary.php @@ -0,0 +1,119 @@ +_parent = $parent; + $this->setAdapter(); + } + abstract public function getClassName(); + abstract protected function setAdapter(); + abstract protected function createEntity(\stdClass $cfResult); + abstract protected function getCFResults_List(int $page): array; + final protected static function getRequestCount() + { + return self::$_requestCount; + } + protected function setAdapter() + { + if (!is_null($this->_adapter)) { + throw new \Exception("Adapter가 이미 지정되었습니다."); + } + $apikey = new \Cloudflare\API\Auth\APIKey( + $this->getParent()->getAuthId(), + $this->getParent()->getAuthKey() + ); + $this->_adapter = new \Cloudflare\API\Adapter\Guzzle($apikey); + // throw new \Exception(var_export($this->_adapter, true)); + } + final protected function getAdapter(): \Cloudflare\API\Adapter\Guzzle + { + if (CF_REQUEST_MAX <= self::$_requestCount) { + log_message('warning', sprintf("--Cloudflare API Call %s초 대기 시작--", CF_REQUEST_WAITTIME)); + sleep(CF_REQUEST_WAITTIME); + self::$_requestCount = 0; + log_message('warning', sprintf("--Cloudflare API Call %s초 대기 종료--", CF_REQUEST_WAITTIME)); + } + self::$_requestCount++; + if (is_null($this->_adapter)) { + throw new \Exception("해당 Adapter가 없습니다."); + } + // throw new \Exception(var_export($this->_adapter, true)); + return $this->_adapter; + } + final public function getParent() + { + if (!isset($this->_parent)) { + throw new \Exception(__METHOD__ . "에서 오류발생: ParentEntity가 선언되지 않았습니다."); + } + return $this->_parent; + } + //reload관련 + //부모키를 기준으로 CF에 존재하지 않는 데이터 삭제용 + final protected function reload_delete(array $entitys) + { + $availableUids = array(); + if (count($entitys)) { + foreach ($entitys as $entity) { + array_push($availableUids, $entity->getPrimaryKey()); + } + $this->_model->where($this->_model::PARENT_FIELD, $this->getParent()->getPrimaryKey())->whereNotIn('uid', $availableUids)->delete(); + } else { + $this->_model->where($this->_model::PARENT_FIELD, $this->getParent()->getPrimaryKey())->delete(); + } + } + final protected function reload_entitys(array $cfResults): array + { + $entitys = array(); + if (count($cfResults)) { + $cnt = 1; + foreach ($cfResults as $cfResult) { + $entity = $this->getEntityByResult((object)$cfResult); + log_message("debug", "{$cnt}번째: {$entity->getTitle()} 저장"); + if (!$this->_model->save($entity)) { + log_message("error", __FUNCTION__ . "에서 호출:" . $this->_model->getLastQuery()); + log_message("error", implode("\n", $this->_model->errors())); + throw new \Exception(__FUNCTION__ . " 오류 발생.\n" . var_export($this->_model->errors(), true)); + } + array_push($entitys, $entity); + $cnt++; + } + } + return $entitys; + } + final protected function reload_cfResults(int $page_limit = 0) + { + $page = 1; //Page는 1부터 시작해야함 + $page_cnt = 1; + $cfResults = array(); + do { + $temp_cfResults = $this->getCFResults_List($page); + // throw new \Exception(var_export($temp_cfResults, true)); + $page = count($temp_cfResults) < CF_ADAPTER_PERPAGE_MAX ? 0 : $page + 1; + //Loop 갯수제한시 + if ($page_limit !== 0 && $page >= $page_limit + 1) { + $page = 0; + } + $cfResults = array_merge($cfResults, $temp_cfResults); + $page_cnt++; + } while (0 < $page); + return $cfResults; + } + + final public function reload(int $page_limit = 0): array + { + $cfResults = $this->reload_cfResults($page_limit); + log_message("notice", "-----{$this->getParent()->getTitle()} {$this->getClassName()} cfResult 처리[" . count($cfResults) . "개] 시작-----"); + $entitys = $this->reload_entitys($cfResults); + $this->reload_delete($entitys); + log_message("notice", "-----{$this->getParent()->getTitle()} {$this->getClassName()} DB 처리[" . count($entitys) . "개] 완료-----"); + return $entitys; + } +} diff --git a/app/Libraries/Cloudflare/Firewall.php b/app/Libraries/Cloudflare/Firewall.php new file mode 100644 index 0000000..e1115c5 --- /dev/null +++ b/app/Libraries/Cloudflare/Firewall.php @@ -0,0 +1,96 @@ +_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/Cloudflare/Magictransit/AllowList.php b/app/Libraries/Cloudflare/Magictransit/AllowList.php new file mode 100644 index 0000000..1b9061a --- /dev/null +++ b/app/Libraries/Cloudflare/Magictransit/AllowList.php @@ -0,0 +1,103 @@ +_model = new \App\Models\Cloudflare\Magictransit\AllowListModel(); + } + public function setParentAuthEntity($parent_uid): void + { + $parent_entity = $this->getAccountModel()->getEntity($parent_uid); + $this->setParent($parent_entity); + $auth_entity = $this->getAuthModel()->getEntity($parent_entity->getParentFieldData()); + $this->setAuth($auth_entity); + } + public function getClassName() + { + return 'AllowList'; + } + protected function getEndPoint() + { + return is_null($this->_endPoint) ? "client/v4/accounts/{$this->getParent()->getPrimaryKey()}5/magic/advanced_tcp_protection/configs/allowlist" : $this->_endPoint; + } + public function getEntityByResult(\stdClass $cfResult): AllowListEntity + { + $entity = is_null($this->_entity) ? new AllowListEntity() : $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(AllowListEntity $entity, array $fieldDatas): AllowListEntity + { + $this->setParentAuthEntity($entity->getParentFieldData()); + + $isChanged = false; + foreach ($fieldDatas as $field => $value) { + if ($entity->$field != $value) { + $entity->$field = $value; + $isChanged = true; + } + } + if (!$isChanged) { + return $entity; + } + $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() . '/AllowList/rules/' . $entity->getPrimaryKey(), $rule); + $cfResult = json_decode($cfResult->getBody()); + if (!$cfResult->success) { + throw new \Exception(var_export($cfResult, true)); + } + return $this->getEntityByResult($cfResult->result); + } + // public function delete(){ } + public function sync(AllowListEntity $entity): AllowListEntity + { + $this->setParentAuthEntity($entity->getParentFieldData()); + + $cfResult = $this->getAdapter()->get('zones/' . $this->getParent()->getPrimaryKey() . '/AllowList/rules/' . $entity->getPrimaryKey()); + $cfResult = json_decode($cfResult->getBody()); + if (!$cfResult->success) { + throw new \Exception(var_export($cfResult, true)); + } + return $this->getEntityByResult($cfResult->result); + } + protected function getCFResults_List(int $page): array + { + return $this->getEndPoint()->listAllowListRules($this->getParent()->getPrimaryKey(), $page, CF_ADAPTER_PERPAGE_MAX)->result; + } +} diff --git a/app/Libraries/Cloudflare/Record.php b/app/Libraries/Cloudflare/Record.php new file mode 100644 index 0000000..c079cbb --- /dev/null +++ b/app/Libraries/Cloudflare/Record.php @@ -0,0 +1,127 @@ +_model = new \App\Models\Cloudflare\API\RecordModel(); + } + 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 'Record'; + } + protected function getEntityByResult(\stdClass $cfResult): \App\Entities\Cloudflare\API\RecordEntity + { + // throw new \Exception(var_export($cfResult, true)); + $entity = is_null($this->_entity) ? new \App\Entities\Cloudflare\API\RecordEntity() : $this->_entity; + // throw new \Exception(var_export($cfResult, true)); + $entity->uid = $cfResult->id; + $entity->zone_uid = $cfResult->zone_id; + $entity->host = $cfResult->name; + $entity->type = $cfResult->type; + $entity->content = $cfResult->content; + $entity->ttl = (int) $cfResult->ttl; + $entity->proxiable = $cfResult->proxiable ? "on" : "off"; + $entity->proxied = $cfResult->proxied ? "on" : "off"; + $entity->locked = "on"; + if (isset($cfResult->locked) && $cfResult->locked) { + $entity->locked = "off"; + } + // $entity->updated_at = $cfResult->modified_on; + $entity->created_at = $cfResult->created_on; + // throw new \Exception(var_export($cfResult, true)); + return $entity; + } + + public function insert(array $fieldDatas): \App\Entities\Cloudflare\API\RecordEntity + { + //TTL값은 CDN(proxied)가 사용함일때는 무조건 1, 않함일때는 120이 적용 + $options = [ + 'name' => $fieldDatas['host'], + 'type' => $fieldDatas['type'], + 'content' => $fieldDatas['content'], + 'proxied' => isset($fieldDatas['proxied']) && $fieldDatas['proxied'] === 'on' ? true : false + ]; + // throw new \Exception(var_export($options, true)); + $cfResult = $this->getAdapter()->post('zones/' . $this->getParent()->getPrimaryKey() . '/dns_records', $options); + $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 update(\App\Entities\Cloudflare\API\RecordEntity $entity, array $fieldDatas): \App\Entities\Cloudflare\API\RecordEntity + { + //TTL값은 CDN(proxied)가 사용함일때는 무조건 1, 않함일때는 120이 적용 + $options = [ + 'type' => isset($fieldDatas['type']) ? $fieldDatas['type'] : $entity->type, + 'name' => isset($fieldDatas['host']) ? $fieldDatas['host'] : $entity->host, + 'content' => isset($fieldDatas['content']) ? $fieldDatas['content'] : $entity->content, + 'proxied' => $entity->proxied == 'on' ? true : false, + 'ttl' => intval($entity->ttl) + ]; + //변경작업: 2024-08-09 + if (isset($fieldDatas['proxied']) && $fieldDatas['proxied'] === 'on') { + $options['proxied'] = true; + $options['ttl'] = 1; + } elseif (isset($fieldDatas['proxied']) && $fieldDatas['proxied'] === 'off') { + $options['proxied'] = false; + $options['ttl'] = 120; + } + //dd($options); + // throw new \Exception(var_export($fieldDatas, true) . "
" . var_export($options, true)); + $cfResult = $this->getAdapter()->put('zones/' . $this->getParent()->getPrimaryKey() . '/dns_records/' . $entity->getPrimaryKey(), $options); + $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); + } + public function delete(\App\Entities\Cloudflare\API\RecordEntity $entity) + { + $cfResult = $this->getAdapter()->delete('zones/' . $this->getParent()->getPrimaryKey() . '/dns_records/' . $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__ . " 완료하였습니다."); + } + public function sync(\App\Entities\Cloudflare\API\RecordEntity $entity): \App\Entities\Cloudflare\API\RecordEntity + { + $cfResult = $this->getAdapter()->get('zones/' . $this->getParent()->getPrimaryKey() . '/dns_records/' . $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\DNS($this->getAdapter()) : $this->_endPoint; + return $this->_endPoint->listRecords($this->getParent()->getPrimaryKey(), '', '', '', $page, CF_ADAPTER_PERPAGE_MAX)->result; + } +} diff --git a/app/Libraries/Cloudflare/Zone.php b/app/Libraries/Cloudflare/Zone.php new file mode 100644 index 0000000..7a39d7a --- /dev/null +++ b/app/Libraries/Cloudflare/Zone.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/Libraries/MyCrawler/MyCrawlerLibrary.php b/app/Libraries/MyCrawler/MyCrawlerLibrary.php index 4626767..1c732a4 100644 --- a/app/Libraries/MyCrawler/MyCrawlerLibrary.php +++ b/app/Libraries/MyCrawler/MyCrawlerLibrary.php @@ -33,9 +33,9 @@ abstract class MyCrawlerLibrary extends CommonLibrary protected function save(string $url, string $mediaType, int $file_sequence): mixed { - $data = $this->getMySocket()->download($url); - $this->getMyStorage()->setOriginName($this->getMySocket()->getFileName()); - $this->getMyStorage()->setOriginContent($data); + list($file_name, $content) = $this->getMySocket()->download($url); + $this->getMyStorage()->setOriginName($file_name); + $this->getMyStorage()->setOriginContent($content); $this->getMyStorage()->setOriginType($mediaType); $this->getMyStorage()->setOriginSequence($file_sequence); return $this->getMyStorage()->save(); diff --git a/app/Libraries/MyCrawler/YamapLibrary.php b/app/Libraries/MyCrawler/YamapLibrary.php index 49def7a..6b86819 100644 --- a/app/Libraries/MyCrawler/YamapLibrary.php +++ b/app/Libraries/MyCrawler/YamapLibrary.php @@ -2,19 +2,16 @@ namespace App\Libraries\MyCrawler; +use App\Entities\Mangboard\UserEntity; use App\Libraries\MySocket\WebLibrary as MySocketLibrary; use App\Libraries\MyStorage\Mangboard\FileLibrary as MyStorageLibrary; -use App\Entities\Mangboard\BoardEntity; -use App\Entities\Mangboard\UserEntity; -use App\Models\Mangboard\BoardModel; +use App\Libraries\MyStorage\Mangboard\BoardsLibrary; use Symfony\Component\DomCrawler\Crawler; class YamapLibrary extends MyCrawlerLibrary { private $_user_entity = null; - private $_board_model = null; - private $_board_name = null; - private $_board_level = null; + private $_boards_library = null; private $_media_tags = []; public function __construct() { @@ -31,18 +28,18 @@ class YamapLibrary extends MyCrawlerLibrary { if ($this->_myStorage === null) { $this->_myStorage = new MyStorageLibrary(getenv('yamap.storage.upload.path')); - $this->_myStorage->setBoardName($this->getBoardName()); - $this->_myStorage->setBoardTable($this->getBoardModel()->getTable()); + $this->_myStorage->setBoardsLibrary($this->getBoardsLibrary()); $this->_myStorage->setUserEntity($this->getUserEntity()); } return $this->_myStorage; } - public function getBoardModel(): BoardModel + public function getBoardsLibrary(): BoardsLibrary { - if ($this->_board_model === null) { - $this->_board_model = new BoardModel("mb_" . $this->getBoardName()); + if ($this->_boards_library === null) { + $this->_boards_library = new BoardsLibrary(getenv('yamap.storage.board.name')); + $this->_boards_library->setUserEntity($this->getUserEntity()); } - return $this->_board_model; + return $this->_boards_library; } public function getUserEntity(): UserEntity { @@ -55,61 +52,10 @@ class YamapLibrary extends MyCrawlerLibrary { $this->_user_entity = $_user_entity; } - public function getBoardName(): string - { - if ($this->_board_name === null) { - $this->_board_name = getenv('yamap.storage.board.name'); - } - return $this->_board_name; - } - public function getBoardLevel(): int - { - if ($this->_board_level === null) { - $this->_board_level = getenv('yamap.storage.board.level'); - } - return intval($this->_board_level); - } - - private function createBoard(array $listInfo): BoardEntity - { - //미디어관련정보 entity에 넣기 - $formDatas = []; - $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['level'] = $this->getBoardLevel(); - $formDatas['hit'] = $listInfo['hit']; - $formDatas['reg_date'] = date("Y-m-d H:i:s", strtotime($listInfo['date'])); - $formDatas['data_type'] = "html"; - $formDatas['editor_type'] = "S"; - $formDatas['image_path'] = ""; - $formDatas['content'] = ""; - //망보드 게시판에 등록 - $entity = $this->getBoardModel()->create($formDatas); - log_message("notice", message: __FUNCTION__ . " 작업 완료"); - return $entity; - } - private function modifyBoard(BoardEntity $entity) - { - $content = implode("\n", $this->_media_tags["content"]); - if ($content !== "") { - $formDatas = [ - "image_path" => array_shift($this->_media_tags["image_path"]), - "content" => $content - ]; - $this->getBoardModel()->modify($entity, $formDatas); - log_message("notice", __FUNCTION__ . " 작업 완료"); - } else { - $this->getBoardModel()->delete([$this->getBoardModel()->getPKField() => $entity->getPK()]); - log_message(level: "warning", message: __FUNCTION__ . "내용이 없어 삭제처리 : {$entity->getPK()}=>{$entity->getTitle()}"); - } - } - private function mainPage(string $url): array { $listInfos = []; - $response = $this->getMySocket()->getResponse($url); + $response = $this->getMySocket()->getContent($url); $selector = $this->getSelector($response, getenv("yamap.list.tag")); //div.bbs_item를 가진 객체를 찾아서 같은 형식의 객체(sibling)를 배열로 넘김 // log_message("debug", sprintf("\n-------------MainPage------------\n%s\n--------------------------\n", $selector->html())); @@ -138,37 +84,7 @@ class YamapLibrary extends MyCrawlerLibrary protected function save(string $url, string $mediaType, int $file_sequence): mixed { $myStorageLibrary = parent::save($url, $mediaType, $file_sequence); - $content = ""; - //Board 게시판 image_path , content용 데이터 배열에 추가 후 modifyBoard에서 처리 - switch ($this->getMyStorage()->getOrintginType()) { - case "image": - $content = sprintf( - "\"%s\"", - getenv("mangboard.uloads.url"), - $this->getMyStorage()->getPath(), - $this->getMyStorage()->getOriginName(), - $this->getMyStorage()->getOriginName() - ); - break; - case "video": - $content = sprintf( - "", - $this->getMyStorage()->getOriginName(), - getenv("mangboard.uloads.url"), - $this->getMyStorage()->getPath(), - $this->getMyStorage()->getOriginName(), - $this->getMyStorage()->getMimeType(), - ); - break; - } - log_message("debug", sprintf( - "\n--------%s--------\n%s\n--------------------\n", - __FUNCTION__, - $content - )); + $content = $this->getMyStorage()->getHTMLTag(); if ($content === "") { throw new \Exception(__FUNCTION__ . " Content의 내용없음"); } @@ -180,10 +96,9 @@ class YamapLibrary extends MyCrawlerLibrary private function detailPage(array $listInfo): void { //1. Yamap ViewPage의 이미지나영상데이터가 있으면 - $response = $this->getMySocket()->getResponse($listInfo['detail_url']); + $response = $this->getMySocket()->getContent($listInfo['detail_url']); //1.망보드 일반게시판에 게시물 생성 처리 - $board_entity = $this->createBoard($listInfo); - $this->getMyStorage()->setBoardEntity($board_entity); + $this->getBoardsLibrary()->createBoard($listInfo); $this->_media_tags = ["image_path" => [], "content" => []]; $selector = $this->getSelector($response, getenv("yamap.view.content.tag")); //3. Image 처리 @@ -192,7 +107,7 @@ class YamapLibrary extends MyCrawlerLibrary //4. Video(mp4) 처리 $myStorageLibrarys = $this->download("video", $selector, ["tag" => "video", "attr" => "src"], $myStorageLibrarys); //5.망보드 일반게시판에 게시물 수정 처리 - $this->modifyBoard($board_entity); + $this->getBoardsLibrary()->modifyBoard($this->_media_tags); log_message("notice", __FUNCTION__ . " 작업 완료"); } diff --git a/app/Libraries/MySocket/WebLibrary.php b/app/Libraries/MySocket/WebLibrary.php index 9975e55..079fd26 100644 --- a/app/Libraries/MySocket/WebLibrary.php +++ b/app/Libraries/MySocket/WebLibrary.php @@ -9,7 +9,6 @@ class WebLibrary extends MySocketLibrary { private $_client = null; private $_cookieJar = null; - private $_file_name = ""; public function __construct(string $host) { parent::__construct($host); @@ -37,17 +36,8 @@ class WebLibrary extends MySocketLibrary return strpos($url, 'http://') !== false || strpos($url, 'https://') !== false; } - public function getResponse(string $url, $type = "default"): string + public function getResponseOptions(string $type, array $options = []): array { - //url에 http 나 https가 포함되어 있지않으면 - if (!($this->isContainsHttpOrHttps($url))) { - $url = $this->gethost() . $url; - } - //기본 - $options = [ - 'cookies' => $this->getCookieJar(), - 'timeout' => getenv("socket.web.timeout"), // 5초 안에 응답이 없으면 타임아웃 - ]; switch ($type) { case 'agent': // User-Agent 목록 배열 @@ -65,51 +55,40 @@ class WebLibrary extends MySocketLibrary ]; break; } + return $options; + } + public function getResponse(string $url, $method = "get", array $options = []): mixed + { + //url에 http 나 https가 포함되어 있지않으면 + if (!($this->isContainsHttpOrHttps($url))) { + $url = $this->gethost() . $url; + } + //기본 Option + $options['cookies'] = $this->getCookieJar(); //쿠키값 + $options['timeout'] = getenv("socket.web.timeout"); // 5초 안에 응답이 없으면 타임아웃 log_message("debug", "Socket URL-> " . $url); - $response = $this->getClient()->get($url, $options); + return $this->getClient()->$method($url, $options); + } + + public function getContent(string $url, $method = "get", array $options = []): string + { + $response = $this->getResponse($url, $method, $options); if ($response->getStatusCode() == 200) { return $response->getBody()->getContents(); // return $response->getBody(); - } else { - throw new \Exception("error", "{$url} 접속실패: " . $response->getStatusCode()); } + throw new \Exception("error", "{$url} 접속실패: " . $response->getStatusCode()); } - // 로그인 메서드 - public function login($url, $username, $password): bool - { - $response = $this->getClient()->post($this->gethost() . $url, [ - 'form_params' => [ - 'username' => $username, - 'password' => $password, - ], - 'cookies' => $this->getCookieJar(), - ]); - if ($response->getStatusCode() == 200) { - log_message("notice", "로그인 성공"); - if ($this->getDebug()) { - echo var_dump($response); - } - return true; - } { - log_message("error", "로그인 실패: " . $response->getStatusCode()); - return false; - } - } - - final public function getFileName(): string - { - return $this->_file_name; - } - final public function download(string $url): string + final public function download(string $url): array { $file_names = explode('/', $url); if (!is_array($file_names) || !count($file_names)) { throw new \Exception("Socket URL Error:" . $this->getHost() . $url); } - $this->_file_name = array_pop($file_names); - $response = $this->getResponse($url); - log_message("notice", "{$this->_file_name} 파일이 다운로드되었습니다!"); - return $response; + $file_name = array_pop($file_names); + $response = $this->getContent($url); + log_message("notice", "{$file_name} 파일이 다운로드되었습니다!"); + return array($file_name, $response); } } diff --git a/app/Libraries/MyStorage/Mangboard/BoardsLibrary.php b/app/Libraries/MyStorage/Mangboard/BoardsLibrary.php new file mode 100644 index 0000000..fc1908f --- /dev/null +++ b/app/Libraries/MyStorage/Mangboard/BoardsLibrary.php @@ -0,0 +1,108 @@ +_board_name = $board_name; + $this->_boards_entity = $this->getBoardsModel()->getEntityByID($this->getBoardName()); + } + public function getBoardsModel(): BoardsModel + { + if ($this->_boards_model === null) { + $this->_boards_model = new BoardsModel(); + } + return $this->_boards_model; + } + public function getBoardsEntity(): BoardsEntity + { + return $this->_boards_entity; + } + public function setBoardsEntity(BoardsEntity $boards_entity): void + { + $this->_boards_entity = $boards_entity; + } + //---------------------------------------------------------------------// + public function getBoardName(): string + { + return $this->_board_name; + } + public function getBoardModel(): BoardModel + { + if ($this->_board_model === null) { + $this->_board_model = new BoardModel("mb_" . $this->getBoardName()); + } + return $this->_board_model; + } + public function getBoardEntity(): BoardEntity + { + if ($this->_board_entity === null) { + throw new \Exception("{$this->getBoardName()} 게시판 정보가 없습니다."); + } + return $this->_board_entity; + } + public function setBoardEntity(BoardEntity $board_entity): void + { + $this->_board_entity = $board_entity; + } + public function getUserEntity(): UserEntity + { + if ($this->_user_entity === null) { + throw new \Exception("사용자정보가 없습니다."); + } + return $this->_user_entity; + } + public function setUserEntity(UserEntity $user_entity): void + { + $this->_user_entity = $user_entity; + } + + public function createBoard(array $listInfo): void + { + //미디어관련정보 entity에 넣기 + $formDatas = []; + $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['level'] = $this->getBoardsEntity()->getListLevel(); + $formDatas['hit'] = $listInfo['hit']; + $formDatas['reg_date'] = date("Y-m-d H:i:s", strtotime($listInfo['date'])); + $formDatas['data_type'] = "html"; + $formDatas['editor_type'] = "S"; + $formDatas['image_path'] = ""; + $formDatas['content'] = ""; + //망보드 게시판에 등록 + $this->setBoardEntity($this->getBoardModel()->create($formDatas)); + log_message("notice", message: __FUNCTION__ . "=>{$this->getBoardName()} 생성 작업 완료"); + } + public function modifyBoard(array $media_tags): void + { + $content = implode("\n", $media_tags["content"]); + if ($content !== "") { + $formDatas = [ + "image_path" => array_shift($media_tags["image_path"]), + "content" => $content + ]; + $this->getBoardModel()->modify($this->getBoardEntity(), $formDatas); + log_message("notice", __FUNCTION__ . "=>{$this->getBoardEntity()->getPK()}:{$this->getBoardEntity()->getTitle()} 수정 작업 완료"); + } else { + $this->getBoardModel()->delete([$this->getBoardModel()->getPKField() => $this->getBoardEntity()->getPK()]); + log_message("warning", __FUNCTION__ . "=>{$this->getBoardEntity()->getPK()}:{$this->getBoardEntity()->getTitle()} 내용이 없어 삭제처리"); + } + } +} diff --git a/app/Libraries/MyStorage/Mangboard/FileLibrary.php b/app/Libraries/MyStorage/Mangboard/FileLibrary.php index c4d6fd2..a8a064d 100644 --- a/app/Libraries/MyStorage/Mangboard/FileLibrary.php +++ b/app/Libraries/MyStorage/Mangboard/FileLibrary.php @@ -2,7 +2,6 @@ namespace App\Libraries\MyStorage\Mangboard; -use App\Entities\Mangboard\BoardEntity; use App\Entities\Mangboard\FileEntity; use App\Entities\Mangboard\UserEntity; use App\Libraries\MyStorage\FileLibrary as MyStorageLibrary; @@ -13,9 +12,7 @@ class FileLibrary extends MyStorageLibrary { private $_file_model = null; private $_user_entity = null; - private $_board_name = null; - private $_board_table = null; - private $_board_entity = null; + private $_boards_library = null; private $_file_entity = null; private $_imageLibrary = null; public function __construct(string $path) @@ -42,27 +39,16 @@ class FileLibrary extends MyStorageLibrary { $this->_file_entity = $file_entity; } - public function getBoardName(): string + public function getBoardsLibrary(): BoardsLibrary { - if ($this->_board_name === null) { - throw new \Exception("Board Name이 없습니다."); + if ($this->_boards_library === null) { + throw new \Exception("Board Library가 정의되지 않았습니다."); } - return $this->_board_name; + return $this->_boards_library; } - public function setBoardName(string $board_name): void + public function setBoardsLibrary(BoardsLibrary $boards_library): void { - $this->_board_name = $board_name; - } - public function getBoardTable(): string - { - if ($this->_board_table === null) { - throw new \Exception("Board Table이 없습니다."); - } - return $this->_board_table; - } - public function setBoardTable(string $board_table): void - { - $this->_board_table = $board_table; + $this->_boards_library = $boards_library; } public function getUserEntity(): UserEntity { @@ -75,22 +61,47 @@ class FileLibrary extends MyStorageLibrary { $this->_user_entity = $user_entity; } - public function getBoardEntity(): BoardEntity + final public function getHTMLTag(string $content = ""): string { - return $this->_board_entity; + //Board 게시판 image_path , content용 데이터 배열에 추가 후 modifyBoard에서 처리 + switch ($this->getOrintginType()) { + case "image": + $content = sprintf( + "\"%s\"", + getenv("mangboard.uloads.url"), + $this->getPath(), + $this->getOriginName(), + $this->getOriginName() + ); + break; + case "video": + $content = sprintf( + "", + $this->getOriginName(), + getenv("mangboard.uloads.url"), + $this->getPath(), + $this->getOriginName(), + $this->getMimeType(), + ); + break; + } + log_message("debug", sprintf( + "\n--------%s--------\n%s\n--------------------\n", + __FUNCTION__, + $content + )); + return $content; } - public function setBoardEntity(BoardEntity $board_entity): void - { - $this->_board_entity = $board_entity; - } - public function save(): static { parent::save(); //파일관리 table에 등록 $formDatas = []; //Board PID 넣기 - $formDatas['board_pid'] = $this->getBoardEntity()->getPk(); + $formDatas['board_pid'] = $this->getBoardsLibrary()->getBoardEntity()->getPk(); //작은이미지생성후 Path/파일명 넣기 $fileInfos = pathinfo($this->_imageLibrary->getDestinationPath() . DIRECTORY_SEPARATOR . $this->getOriginName(), PATHINFO_ALL); $dstFile = $fileInfos['filename'] . "_small." . $fileInfos['extension']; @@ -103,8 +114,8 @@ class FileLibrary extends MyStorageLibrary $formDatas['user_pid'] = $this->getUserEntity()->getPK(); $formDatas['user_name'] = $this->getUserEntity()->getTitle(); - $formDatas['board_name'] = $this->getBoardName(); - $formDatas['table_name'] = $this->getBoardTable(); + $formDatas['board_name'] = $this->getBoardsLibrary()->getBoardName(); + $formDatas['table_name'] = $this->getBoardsLibrary()->getBoardModel()->getTable(); $formDatas['file_name'] = $this->getOriginName(); $formDatas['file_type'] = $this->getMimeType(); $formDatas['file_caption'] = $this->getOriginName(); diff --git a/app/Libraries/MyStorage/Mangboard/UserLibrary.php b/app/Libraries/MyStorage/Mangboard/UserLibrary.php new file mode 100644 index 0000000..beb06be --- /dev/null +++ b/app/Libraries/MyStorage/Mangboard/UserLibrary.php @@ -0,0 +1,54 @@ +_user_model === null) { + return $this->_user_model = new UserModel(); + } + return $this->_user_model; + } + public function getWebLibrary(string $host): WebLibrary + { + if ($this->_web_library === null) { + $this->_web_library = new WebLibrary($host); + } + return $this->_web_library; + } + // 로그인 메서드 + public function login(string $host, string $id, string $password): bool|UserEntity + { + $response = $this->getWebLibrary($host)->getResponse( + $host . getenv("mangboard.login.url"), + "post", + [ + 'form_params' => [ + 'user_id' => $id, + 'password' => $password, + ], + ] + ); + if ($response->getStatusCode() == 200) { + // $entity = $this->getUserModel()->getEntityByLoginCheck($id, $password); + $entity = $this->getUserModel()->getEntityByID($id); + if ($entity === null) { + throw new \Exception("{$id}는 회원이 아니거나 암호가 맞지 않습니다."); + } + } else { + throw new \Exception("연결실패:" . $response->getStatusCode()); + } + log_message("notice", "{$id}로 로그인 성공"); + return $entity; + } +} diff --git a/app/Models/CommonModel.php b/app/Models/CommonModel.php index 38e62ec..81bca62 100644 --- a/app/Models/CommonModel.php +++ b/app/Models/CommonModel.php @@ -51,7 +51,10 @@ 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; diff --git a/app/Models/Mangboard/BoardModel.php b/app/Models/Mangboard/BoardModel.php index f42dd1a..273d631 100644 --- a/app/Models/Mangboard/BoardModel.php +++ b/app/Models/Mangboard/BoardModel.php @@ -68,7 +68,6 @@ use App\Entities\Mangboard\BoardEntity; class BoardModel extends CommonModel { - // protected $table = 'mb_board_free'; protected $primaryKey = 'pid'; protected $returnType = BoardEntity::class; protected $allowedFields = [ diff --git a/app/Models/Mangboard/BoardsModel.php b/app/Models/Mangboard/BoardsModel.php new file mode 100644 index 0000000..1fab02b --- /dev/null +++ b/app/Models/Mangboard/BoardsModel.php @@ -0,0 +1,143 @@ +where($this->getPKField(), $uid); + return $this->getEntity(); + } + public function getEntityByID(string $board_name): null | BoardsEntity + { + $this->where('board_name', $board_name); + return $this->getEntity(); + } + + //create용 + public function create(array $formDatas = []): BoardsEntity + { + return $this->create_process(new BoardsEntity(), $formDatas); + } + //modify용 + public function modify(BoardsEntity $entity, array $formDatas): BoardsEntity + { + return $this->modify_process($entity, $formDatas); + } +} diff --git a/app/Models/Mangboard/UserModel.php b/app/Models/Mangboard/UserModel.php index 12cc888..6002401 100644 --- a/app/Models/Mangboard/UserModel.php +++ b/app/Models/Mangboard/UserModel.php @@ -150,6 +150,12 @@ class UserModel extends CommonModel $this->where('user_id', $id); return $this->getEntity(); } + public function getEntityByLoginCheck(string $id, string $password): null|UserEntity + { + $this->where('user_id', $id); + $this->where('passwd', password_hash($password, PASSWORD_DEFAULT)); + return $this->getEntity(); + } private function getLevelByPoint(UserEntity $entity): int { @@ -160,19 +166,20 @@ class UserModel extends CommonModel } //사용자 Point별 Level 계산 - $level = intval($entity->getPoint() / getenv('mangboard.point.unit') * getenv('mangboard.point.unit') / getenv('mangboard.point.unit')); + $levelup_point = getenv('mangboard.level.up.point.unit'); + $level = intval($entity->getPoint() / $levelup_point * $levelup_point / $levelup_point); //운영자면 7~9 - if (getenv('mangboard.manager.level.min') <= $level && $level <= getenv('mangboard.manager.level.max')) { - $level = $level < getenv('mangboard.manager.level.min') ? getenv('mangboard.manager.level.min') : $level; - $level = getenv('mangboard.manager.level.max') < $level ? getenv('mangboard.manager.level.max') : $level; + 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.user.level.min') <= $level && $level <= getenv('mangboard.user.level.max')) { - $level = $level < getenv('mangboard.user.level.min') ? getenv('mangboard.user.level.min') : $level; - $level = getenv('mangboard.user.level.max') < $level ? getenv('mangboard.user.level.max') : $level; + 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;